Skip to content
maziofweb3Public

About

Autonomous AI Trading Protocol and Live Streamer Arena on Solana

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

SolByte: Autonomous AI Trading Protocol and Live Streamer Arena on Solana

SolByte is an institutional-grade autonomous AI trading protocol, live streamer arena, and on-chain intelligence network built on Solana. It pairs non-custodial on-chain vault delegation with machine micropayments, real-time technical analysis, and interactive esports broadcasting.

Solana Devnet Anchor 1.0.1 Byte Arena Spec Pollar Powered Solana Mobile Stack


Table of Contents

  1. Verified On-Chain Deployments
  2. System Architecture
  3. Anchor Smart Contract Specification
  4. Mathematical Models and Fee Accounting
  5. Autonomous Trading Engine
  6. Machine Payments and Verification Protocols
  7. Byte Arena Game Engine Specification
  8. Client Implementations
  9. Project Directory Layout
  10. Build and Execution Guide
  11. Security Model and Risk Guardrails
  12. License

Verified On-Chain Deployments

The core SolByte vault program is compiled for the Solana Sealevel runtime (SBF) and deployed on Solana Devnet.

Parameter Value
Program ID 5xR55RZ1rpY89howmdirQ5fYTRihAM7hTxuT8FQnmQyW
Deploy Transaction 2g6QPhzkrDzVhmuqJhQyHcxgJYtNFT8mGPXv8W2pDxczUcVmeDJGucwscxTdETyoujdDpnbR1dNxk2jY2xwdWieR
Upgrade Authority 57Vnwcq5vxcx6NCJbUBAeNXMAE8tj8p6UNzPfRspoKhW
ProgramData Account 7KmbKxCcCVrxEYzrkgGKDZu9gpoPpSqoPKJmpp2X9FCe
Network Cluster Solana Devnet (Slot 525834444+)
Anchor Framework 1.0.1 (anchor-lang 0.31.1, solana-program 2.2.1)

System Architecture

SolByte is organized into three interacting operational layers:

flowchart TD
    subgraph Clients
        WebTrader["Web Terminal: apps/web\nNext.js + Pollar Social Auth"]
        MobileTrader["Mobile Terminal: apps/mobile\nReact Native + Solana Mobile Stack"]
        Spectator["Arena Audience\n/watch/:runId Prediction Pool"]
        ExtAgent["External AI Agents\nOutbound x402 Alpha Consumer"]
    end

    subgraph SolByte Core Services
        AgentBrain["Autonomous Trading Intelligence\nRSI, EMA, Bollinger, Pyth Validation"]
        ByteEngine["Byte Arena State Machine\nTurn-based Market Scenarios"]
        SignalAPI["Outbound x402 Signal Gate\nGET /api/x402/signals"]
    end

    subgraph External Infrastructure
        PythOracle["Pyth Network Price Feeds"]
        PayShRelay["pay.sh Solana MPP Gateway"]
        WurkReview["WURK x402 Human Review Protocol"]
        PollarGas["Pollar Paymaster Relayer"]
    end

    subgraph Solana Program State
        AnchorProg["solbyte_vault Program\n5xR55RZ1rpY89howmdirQ5fYTRihAM7hTxuT8FQnmQyW"]
        ConfigState[("ProtocolConfig PDA\n[protocol-config]")]
        UserVault[("TradingVault PDA\n[vault, owner]")]
        DelegationState[("AgentDelegation PDA\n[delegation, vault]")]
        ArenaPoolState[("ArenaPool PDA\n[arena-pool, run_id]")]
        ProtocolTreasury[("Protocol Treasury")]
    end

    WebTrader -->|Pollar Auth & Gas Sponsorship| PollarGas
    WebTrader -->|Deposit / Delegate / Configure| AnchorProg
    MobileTrader -->|Native MWA Intent Signing| AnchorProg
    Spectator -->|Place Pari-Mutuel Bet| ArenaPoolState
    ExtAgent -->|Pay $0.03 USDC via x402| SignalAPI

    AgentBrain -->|HTTP 402 MPP Micropayments| PayShRelay
    AgentBrain -->|Crowd Sentiment Verification| WurkReview
    AgentBrain -->|Real-time Price Validation| PythOracle
    AgentBrain -->|Delegated Sub-400ms Swaps| AnchorProg

    ByteEngine -->|Settle Game Outcomes| ArenaPoolState

    AnchorProg -->|0.50% Execution Fee Split| ProtocolTreasury
    AnchorProg -->|10% HWM Performance Fee| ProtocolTreasury
    ArenaPoolState -->|4.0% Arena Rake| ProtocolTreasury
Loading

Layer Separation

  1. Sol Layer (DeFi Execution and Custody): Non-custodial Program Derived Address (PDA) vaults where depositors maintain full key ownership. Autonomous agents are delegated limited trade execution rights bounded by user-defined slippage, stop-loss, and daily spending limits.
  2. Byte Layer (Agentic Intelligence and Arena): An autonomous execution brain that monitors technical indicators, validates pricing against Pyth oracles, queries premium orderflow via machine micropayments (pay.sh), triggers human validation reviews (WURK x402), and runs turn-based competitive market scenarios in compliance with the Byte Arena specification.
  3. Distribution Layer (Web, Mobile, and API): A 12-column institutional web terminal, a native Android mobile application leveraging the Solana Mobile Stack (MWA), and a monetized outbound x402 HTTP API providing Alpha-as-a-Service to external trading agents.

Anchor Smart Contract Specification

The smart contract is written in Anchor and located in programs/solbyte-vault/src/. It enforces state isolation, non-custodial custody, and immutable fee ceilings.

Account State Definitions

1. ProtocolConfig (src/state.rs)

Global protocol parameters, treasury routing, and hard-coded fee caps:

  • admin: Public key with administrative authority to update fees within immutable limits.
  • treasury: Public key receiving accumulated protocol fees.
  • execution_fee_bps: Trade execution fee in basis points (default: 50 / 0.50%). Capped at MAX_EXECUTION_FEE_BPS = 100 (1.00%).
  • referral_share_bps: Percentage of execution fee routed to referrer (default: 2000 / 20%).
  • performance_fee_bps: Fee on net realized profits above High-Water Mark (default: 1000 / 10%). Capped at MAX_PERFORMANCE_FEE_BPS = 2000 (20.00%).
  • arena_rake_bps: Pari-mutuel spectator pool fee (default: 400 / 4.00%). Capped at MAX_ARENA_RAKE_BPS = 500 (5.00%).
  • is_paused: Global emergency pause flag.

2. TradingVault (src/state.rs)

Per-user non-custodial vault PDA derived from seeds [b"vault", owner.key()]:

  • owner: Public key of the vault owner. Only the owner can withdraw or update delegation.
  • balance: Current lamport balance held in the vault.
  • high_water_mark: Highest net capital baseline used for performance fee calculations.
  • total_deposited: Lifetime deposits in lamports.
  • total_withdrawn: Lifetime withdrawals in lamports.
  • accumulated_fees: Lifetime fees paid to protocol.
  • is_active: Operational status flag.
  • created_at / last_trade_at: Timestamps for audit and rate-limiting.

3. AgentDelegation (src/state.rs)

Delegation parameters derived from seeds [b"delegation", vault.key()]:

  • agent: Authorized agent public key allowed to execute rebalances.
  • max_slippage_bps: Maximum permissible slippage per swap (e.g. 100 = 1.00%).
  • daily_spending_cap: Maximum lamports the agent may trade within a 24-hour window.
  • daily_spent: Lamports traded within the active 24-hour window.
  • stop_loss_pct: Maximum drawdown percentage before automated delegation revoking.
  • last_reset_timestamp: Slot timestamp of the active spending window.

4. ArenaPool and PredictionTicket (src/state.rs)

Pari-mutuel spectator prediction market for Byte Arena runs:

  • ArenaPool: Derived from [b"arena-pool", run_id.as_bytes()]. Tracks total lamports staked across three discrete outcomes: Win, Loss, and Liquidated.
  • PredictionTicket: User stake tracking for pool outcome claims.

Instruction Set

Instruction Signers Description
initialize_protocol admin Initializes global configuration, fee schedules, and treasury routing.
initialize_vault owner Derives and initializes a new non-custodial TradingVault PDA.
deposit owner Transfers SOL from owner to vault PDA. Adjusts High-Water Mark 1:1 with deposited capital.
withdraw owner Withdraws SOL from vault PDA. Calculates and deducts 10% performance fee strictly on profits exceeding the High-Water Mark, and reduces High-Water Mark proportionally.
delegate_agent owner Grants execution authority to an agent public key under specified slippage and spending bounds.
execute_trade agent Executes a trade instruction. Deducts 0.50% fee split between protocol treasury and optional referrer. Verifies spending cap and slippage constraints.
create_arena_pool authority Opens a pari-mutuel prediction market for a specific Byte Arena run ID.
place_prediction bettor Deposits stake into an open ArenaPool for a selected outcome.
settle_arena_pool authority Resolves game outcome, deducts 4.00% protocol rake, and enables ticket redemption.
emergency_pause owner or admin Suspends execution on a user vault or across the entire protocol.

Mathematical Models and Fee Accounting

1. High-Water Mark (HWM) Performance Fee

To prevent double-charging on recovered drawdowns, SolByte uses a strict High-Water Mark accounting mechanism:

Deposit Adjustment

Depositing new capital increases the watermark dollar-for-dollar without triggering performance fees:

$$\text{HWM}_{\text{new}} = \text{HWM}_{\text{old}} + \Delta_{\text{deposit}}$$

Performance Fee on Withdrawal

Performance fees are assessed only when the current vault balance exceeds the recorded High-Water Mark:

$$\text{Net Profit} = \max\left(0, \text{Balance} - \text{HWM}\right)$$

$$\text{Performance Fee} = \text{Net Profit} \times 10%$$

$$\text{Disbursed Amount} = \text{Requested Amount} - \text{Performance Fee}$$

Proportional Watermark Adjustment

When a user withdraws principal, the High-Water Mark is scaled down proportionally to prevent penalizing future gains:

$$\text{HWM}_{\text{new}} = \text{HWM}_{\text{old}} \times \left(1 - \frac{\text{Requested Amount}}{\text{Balance}}\right)$$

2. Delegated Execution Fee

Each swap initiated by an authorized agent incurs an execution fee of 0.50% (50 basis points):

$$\text{Fee}_{\text{total}} = \text{Swap Amount} \times 0.0050$$

When a valid referral account is provided:

  • Protocol Treasury receives 80% of fee (0.40% of trade volume).
  • Referrer receives 20% of fee (0.10% of trade volume).

3. Profit-Gated Agent Intelligence Budget Rule

The autonomous agent is economically bounded to ensure data acquisition costs never exceed trade revenue:

$$\text{Trade Volume} \times 0.50% \ge 3 \times \text{Cost}_{\text{intelligence}}$$

  • If a pay.sh orderflow query costs $0.02 and a WURK sentiment check costs $0.05 (total: $0.07), the agent will only execute these queries when the batched trade size exceeds $42.00, guaranteeing a minimum 67% gross operational margin.
  • Query results are cached for 60 seconds and amortized across all active user vaults simultaneously.

4. Pari-Mutuel Arena Prediction Settlement

Audience prediction pools calculate payouts proportionally from the net pool after a 4.00% protocol rake:

$$\text{Net Pool} = \text{Total Pool Lamports} \times (1 - 0.04)$$

$$\text{Payout}_{\text{user}} = \text{Stake}_{\text{user}} \times \frac{\text{Net Pool}}{\text{Winning Outcome Pool Lamports}}$$


Autonomous Trading Engine

Located in services/agent-core/, the autonomous trading engine monitors market conditions, validates signals, and submits low-latency transactions.

Market Analyzer (analyzer.ts)

Calculates composite technical indicators on live tick streams:

  • Relative Strength Index (RSI 14): Identifies oversold (< 30) and overbought (> 70) conditions.
  • Exponential Moving Average (EMA 9 / EMA 21): Golden cross and death cross directional trend detection.
  • Bollinger Bands (20 periods, 2 standard deviations): Dynamic volatility envelopes and mean-reversion triggers.
  • Volume Surge Delta: Compares current candle volume against a 20-period moving average to filter false breakouts.

Risk Controller (risk.ts)

  • Enforces user delegation limits on-chain before signing.
  • Evaluates the profit-gated intelligence budget rule before calling external paid APIs.
  • Checks drawdown against user-configured stop-loss thresholds.

Execution Service (executor.ts)

  • Dynamic Priority Fees: Queries recent prioritization fees via getRecentPrioritizationFees and sets ComputeBudgetProgram.setComputeUnitPrice to secure next-slot inclusion.
  • Pre-Simulation: Simulates transactions locally before RPC broadcast to prevent failed transaction fees.
  • RPC Routing: Directs transaction payloads to low-latency validator endpoints with pre-flight checks enabled.

Machine Payments and Verification Protocols

Located in services/payments/, SolByte integrates autonomous machine-to-machine payment rails.

pay.sh MPP Client (paysh.ts)

Integrates the Solana Machine Payment Protocol (MPP) for programmatic data purchasing:

  1. Agent queries a premium data endpoint.
  2. Endpoint returns an HTTP 402 Payment Required response containing an MPP payment request challenge.
  3. Client decodes challenge parameters (recipient, lamport amount, memo).
  4. Client signs and transmits an on-chain micropayment transaction via @solana/mpp/client.
  5. Upon confirmation, client retries the request with the transaction signature in the Authorization: Bearer <signature> header.

WURK x402 Human Review Client (x402-wurk.ts)

When composite model confidence lands in an ambiguous window (60% to 75% confidence):

  • Agent posts a microjob to WURK crowd workers requesting rapid sentiment verification.
  • Worker responses are aggregated and scored.
  • If crowd sentiment aligns with technical signals, trade execution proceeds; otherwise, execution is deferred.

Outbound Alpha-as-a-Service (apps/web/src/app/api/x402/signals/route.ts)

External autonomous agents can consume SolByte's composite signals via an inbound HTTP 402 endpoint:

  • Request: GET /api/x402/signals?symbol=SOL
  • Initial Response: HTTP 402 Payment Required with payment requirement: $0.03 USDC payable to protocol treasury.
  • Authorized Response: Returns real-time RSI, EMA, Bollinger, and Pyth-validated price bias.

Byte Arena Game Engine Specification

SolByte is fully compliant with the Byte Arena Specification. It models market navigation as a turn-based interactive game suitable for AI streamers and esports broadcasting.

Action Set

The engine exposes a closed list of 6 discrete actions:

Action Name Description Terminal
buy_sol Allocates available cash into a SOL long position. No
sell_sol Reduces or closes active SOL long position into cash. No
take_profit Realizes accumulated profits and resets position risk. No
boost_leverage Multiplies position exposure (increases upside and liquidation risk). No
pay_for_alpha Spends game balance to purchase a pay.sh signal reveal for next turns. No
cash_out Closes all open positions, records final score, and concludes the run. Yes

Game Specification Document

{
  "name": "SolByte Trading Arena",
  "api": {
    "baseUrl": "https://solbyte.app",
    "start": {
      "method": "POST",
      "path": "/api/byte/start",
      "body": { "scenario": "solana-flash-crash" },
      "save": { "runId": "runId", "apiKey": "apiKey" }
    },
    "auth": { "header": "Authorization", "value": "Bearer {{apiKey}}" },
    "state": { "method": "GET", "path": "/api/byte/state?runId={{runId}}" },
    "actions": [
      { "name": "buy_sol", "method": "POST", "path": "/api/byte/action", "body": { "runId": "{{runId}}", "action": "buy_sol" } },
      { "name": "sell_sol", "method": "POST", "path": "/api/byte/action", "body": { "runId": "{{runId}}", "action": "sell_sol" } },
      { "name": "take_profit", "method": "POST", "path": "/api/byte/action", "body": { "runId": "{{runId}}", "action": "take_profit" } },
      { "name": "boost_leverage", "method": "POST", "path": "/api/byte/action", "body": { "runId": "{{runId}}", "action": "boost_leverage" } },
      { "name": "pay_for_alpha", "method": "POST", "path": "/api/byte/action", "body": { "runId": "{{runId}}", "action": "pay_for_alpha" } },
      { "name": "cash_out", "method": "POST", "path": "/api/byte/action", "body": { "runId": "{{runId}}", "action": "cash_out" }, "terminal": true }
    ],
    "finish": { "path": "status", "equals": ["dead", "won", "cashed_out"] },
    "result": {
      "win": { "path": "status", "equals": ["won"] },
      "score": { "path": "portfolioBalance", "label": "USD Equity" }
    },
    "watchUrl": "https://solbyte.app/watch/{{runId}}"
  }
}

Pre-Configured Scenarios

  • solana-flash-crash: Simulates rapid price drawdowns and sudden liquidity gaps requiring defensive hedging.
  • bull-run-breakout: High-momentum rally scenario rewarding disciplined leverage and scale-outs.
  • crab-market-range: Sideways chop scenario testing mean-reversion and patience.

Client Implementations

1. Web Trading Terminal (apps/web)

  • Framework: Next.js 14 App Router, TypeScript, Tailwind CSS.
  • Theme and Typography: Obsidian theme (#090B0E), hairline borders (rgba(255, 255, 255, 0.07)), Geist typography with tabular numeric formatting (font-variant-numeric: tabular-nums).
  • Charting: TradingView lightweight-charts v5 with real-time WebSocket ticks, EMA/Bollinger overlays, and interactive price lines.
  • Dual Authentication Modal:
    • Web2 Social Path: Powered by @pollar/core and @pollar/react (^0.12.0). Users authenticate with Google, Twitter/X, or Apple; Pollar sponsors initial account creation, rent, and first 5 transactions.
    • Web3 Native Path: Wallet Adapter supporting Phantom, Solflare, Backpack, and Mobile Wallet Adapter.
  • Spectator Broadcast View (/watch/[runId]): 16:9 responsive HUD featuring live PnL odometer roll, turn log feed, and pari-mutuel prediction pool controls.

2. Native Android Mobile App (apps/mobile)

  • Framework: React Native, Expo prebuild with native Android bridge.
  • Solana Mobile Stack (SMS): Integrates @solana-mobile/mobile-wallet-adapter-protocol (useMWA.ts) to request authorization and sign transactions via Android Intents against Seed Vault, Phantom Mobile, or Solflare Mobile.
  • Mobile-First UX: 48px+ tap targets, thumb-zone trade controls, and haptic feedback.
  • dApp Store Ready: Contains dapp-store.json specification for publishing to the Solana dApp Store.
  • Packaging: Native APK output at apps/mobile/build/solbyte-release.apk.

Project Directory Layout

solbyte/
├── Cargo.toml                       # Cargo workspace configuration
├── Anchor.toml                      # Anchor workspace and Devnet configuration
├── package.json                     # Monorepo root scripts and dependencies
├── pnpm-workspace.yaml              # Workspace directory mappings
│
├── programs/
│   └── solbyte-vault/               # Anchor Solana smart contract
│       ├── Cargo.toml
│       ├── Xargo.toml
│       └── src/
│           ├── lib.rs               # Program entrypoint and instruction routing
│           ├── state.rs             # ProtocolConfig, TradingVault, AgentDelegation, ArenaPool
│           ├── errors.rs            # Custom error codes and fee ceiling constants
│           └── instructions/
│               ├── initialize_protocol.rs
│               ├── initialize_vault.rs
│               ├── deposit.rs
│               ├── withdraw.rs
│               ├── delegate.rs
│               ├── execute_trade.rs
│               ├── arena_pool.rs
│               └── pause.rs
│
├── services/
│   ├── agent-core/                  # Autonomous trading logic
│   │   ├── analyzer.ts              # RSI, EMA, Bollinger, and volume metrics
│   │   ├── risk.ts                  # Delegation guardrails and budget rule
│   │   └── executor.ts              # Priority fees and transaction simulation
│   ├── payments/                    # Machine payment clients
│   │   ├── paysh.ts                 # pay.sh Solana MPP HTTP 402 client
│   │   └── x402-wurk.ts             # WURK human-in-the-loop verification
│   ├── byte-arena/                  # Byte Arena game engine
│   │   ├── engine.ts                # Turn-based state engine and transitions
│   │   ├── scenarios.ts             # Market scenario generators
│   │   └── spec.md                  # Byte Arena specification documentation
│   └── pollar/                      # Social onboarding and sponsored gas
│       └── pollar-client.ts         # Pollar SDK client with sponsorship quota
│
├── apps/
│   ├── web/                         # Next.js trading terminal and spectator HUD
│   │   ├── package.json
│   │   ├── tailwind.config.js
│   │   └── src/
│   │       ├── app/
│   │       │   ├── page.tsx         # Main 12-column trading terminal
│   │       │   ├── arena/page.tsx   # Byte Arena interactive runner
│   │       │   ├── watch/[runId]/   # 16:9 spectator HUD
│   │       │   └── api/             # Byte Arena & x402 API endpoints
│   │       └── components/          # TradingView chart, Vault deck, Telemetry HUD
│   │
│   └── mobile/                      # Native Android React Native / SMS app
│       ├── package.json
│       ├── app.json
│       ├── dapp-store.json          # Solana dApp Store publishing metadata
│       └── src/
│           ├── hooks/useMWA.ts      # Mobile Wallet Adapter hook
│           ├── screens/             # Trade and Vault screens
│           └── App.tsx
│
└── scripts/
    ├── simulate-agent.ts            # End-to-end integration test and simulator
    └── build-apk.sh                 # Native Android APK build script

Build and Execution Guide

Prerequisites

  • Node.js v20.x or higher, with pnpm (corepack enable pnpm)
  • Rust 1.89+ and Cargo
  • Solana CLI Suite (Agave 2.2+ or 4.3.1+)
  • Anchor CLI 1.0.1
  • Android SDK (for compiling mobile APK)

1. Compile Smart Contracts

# Build SBF program binary
cargo-build-sbf --manifest-path programs/solbyte-vault/Cargo.toml --sbf-out-dir target/deploy --offline

# Verify compiled binary
ls -lh target/deploy/solbyte_vault.so

2. Deploy to Solana Devnet

solana program deploy \
  --program-id target/deploy/solbyte_vault-keypair.json \
  --url devnet \
  --with-compute-unit-price 100000 \
  --commitment confirmed \
  target/deploy/solbyte_vault.so

3. Run Autonomous Simulation

Test market analysis, profit-gated intelligence rule, pay.sh micropayments, Byte Arena state transitions, and Pollar onboarding in an automated run:

npx tsx scripts/simulate-agent.ts

4. Run Web Application

cd apps/web
pnpm install
pnpm dev
# Navigate to http://localhost:3000

5. Build Native Android Mobile APK

bash scripts/build-apk.sh
# Generated APK: apps/mobile/build/solbyte-release.apk

Security Model and Risk Guardrails

  1. Non-Custodial Account Isolation: Vault accounts enforce has_one = owner. The agent cannot withdraw capital, modify ownership, or re-delegate authority.
  2. Immutable Fee Caps: Hard-coded program limits prevent fee gouging:
    • Maximum Execution Fee: 100 bps (1.00%)
    • Maximum Performance Fee: 2000 bps (20.00%)
    • Maximum Arena Rake: 500 bps (5.00%)
  3. Execution Guardrails: Every delegated trade checks that:
    • The trade size does not exceed the remaining daily_spending_cap.
    • The price slip does not exceed max_slippage_bps.
    • The active price matches the Pyth oracle feed within acceptable staleness thresholds.
  4. Emergency Pause Switch: Either the vault owner or the global protocol admin can pause vault execution at any time without waiting for open trades to settle.

License

MIT License. Open source and built for the Solana ecosystem.

About

Autonomous AI Trading Protocol and Live Streamer Arena on Solana

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages