跳到正文
DEV Community· David fadoju·· 3 小時前AI 評分41

AlphaAgent:記住預測者刪除內容的預測審計智能體

AlphaAgent: A prediction auditor that remembers what tipsters delete

AI 導讀

AlphaAgent 是建基於 Sui Testnet 和 Walrus Memory 的量化盡職審查智能體及自動跟單機械人,透過六道統計關卡審核預測者,並核對鏈上承諾與歷史預測。系統要求至少 15 個已驗證預測才可給予 FOLLOW 判定,並以 Fractional Kelly Criterion 為已驗證預測者設定倉位;外部 AI Agent 可付 0.01 SUI 購買簽署的審核證明。

正文

Building a memory-powered quantitative due-diligence agent and autonomous copy-trading bot with Tatum, Sui Testnet, and Walrus Memory

We have built sports betting and prediction platforms that record almost everything about a wager.

The matchup. The side. The stake. The payout. Whether the bet won or lost.

But there is something critical that almost every public leaderboard, social feed, and tipster marketplace still forgets.

Every weekend the same headlines appear across X, Telegram, and Discord: a self-proclaimed sports "guru" is 5–0 this week, boasting a 100% win rate and selling access to a VIP picks group for \$500 a month.

Someone sees the streak, trusts the screenshot, and copies the next bet. When the bet loses, the post quietly disappears. By Monday morning, the losing ticket is gone, the bio still says "78% lifetime accuracy," and the next visitor starts evaluating that forecaster from zero.

Questions that should be central to any financial due-diligence process rarely get answered:

  • Was that prediction actually locked before kickoff, or posted after the opening drive?
  • How many losing picks were made and quietly deleted along the way?
  • Did the forecaster actually beat the closing market odds, or just bet heavy favorites at -400?
  • Is a 5–0 run genuine predictive skill, or the 1-in-32 coin-flip variance that happens by pure chance every single week?

A raw win-loss counter can show a streak. It almost never preserves the denominator, the closing market baseline, or the unrevealed bets behind it.

That gap became the foundation for AlphaAgent, a decentralized quantitative due-diligence agent and autonomous copy-trading bot built for the Tatum × Walrus Total Recall Hackathon.


The Problem: We See Streaks, Not the Deleted Denominator

Imagine following a sports forecaster online. They post five consecutive winners across NFL and NBA games. Five wins, zero losses.

On the surface, 5–0 looks extraordinary. Most leaderboards immediately rank that account at the top, and most copy-traders rush to allocate bankroll.

Yet three different realities can hide behind the exact same 5–0 headline:

  1. Pure coin-flip variance: If 32 people flip a fair coin five times, one of them will land five heads in a row ((0.5)^5 = 3.125%, or 1 in 32). A 5–0 streak requires zero predictive skill to occur naturally.
  2. Selective deletion (cherry-picking): A tipster locks ten picks before kickoff, watches four of them fall behind by halftime, and only reveals or publicizes the six that won. Without an immutable record of every pre-game commitment, the four abandoned picks vanish from the denominator.
  3. Zero-edge favorites: Picking five heavy favorites at 85% implied market probability and going 5–0 is not alpha—and when the inevitable upset arrives, the bettor's bankroll is wiped out.

Your wallet knows how much SUI you hold. A block explorer knows that a transaction occurred. Neither automatically remembers whether a forecaster's historical edge beats the closing line after accounting for sample-size shrinkage, forfeited commitments, and category-specific blindspots.

We have plenty of tools for placing bets and displaying leaderboards, but remarkably few tools for preserving verifiable forecasting judgment over time.

Knowing that someone won five bets is surface noise. Knowing when they locked each pick, what the market odds were at commitment time, which commits they refused to reveal, and why their historical calibration fails in specific odds bands is what protects capital.

I wanted to build an agent that preserves all of that evidence permanently and enforces it mathematically before a single SUI is risked. Not a hype leaderboard. Not a blind copy-trader.

A quantitative due-diligence agent with permanent memory. That is how AlphaAgent began.


Introducing AlphaAgent

AlphaAgent is a cryptographic due-diligence auditor and Fractional Kelly copy-trading agent built on Sui Testnet and Walrus Memory. It combines four core capabilities:

  • Pre-kickoff blockchain commitments: Tatum connects AlphaAgent to Sui Testnet RPC to verify alphaagent::commits::PickCommitted events stamped against the official on-chain Sui Clock (0x6), inspect transaction blocks, and check live SUI balances.
  • Permanent episodic and behavioral memory: Walrus Memory (@mysten-incubation/memwal and direct Walrus Testnet publisher nodes) stores resolved episodes, forfeited commits, synthesized behavioral lessons, and verdict transitions in tamper-evident blobs.
  • Deterministic 6-gate statistical auditing: A mathematical decision engine evaluates Forfeit Rate, Minimum Sample Size (n >= 15), Market Information Depth, Bayesian-shrunk Brier Skill Score (k = 10), 2,000-iteration Bootstrap Confidence, and Category/Lesson overrides before issuing a verdict.
  • Safe-Shield autonomous copy-trading & x402 agent commerce: An automated copy-trading bot sizes positions using the Fractional Kelly Criterion (f* = (p - m) / (1 - m)) exclusively for verified FOLLOW forecasters, while an HTTP 402 Payment Required gateway lets external AI agents purchase signed audit attestations for 0.01 SUI.

The experience walks a quantitative bettor or Web3 trader through the complete lifecycle:

  1. Connect & Explore Directory (/tipsters): Provision a 1-Click Guest Sandbox wallet pre-funded on Sui Testnet (or connect a browser wallet), inspect the live leaderboard sorted by shrunk Brier Skill Score rather than raw streaks, and whitelist verified forecasters.
  2. Cryptographic Due-Diligence Audit (/check): Paste any Sui address to run the independent mathematical gates, reconcile on-chain Sui commitments against Walrus memory blobs, and inspect every historical pick against the closing market line.
  3. The Math Behind The Gate (/luck-lab): Drag interactive sliders in the Luck Lab to see why a 5–0 run happens 1 in 32 times by coin-flip chance and why AlphaAgent requires at least 15 verified picks before unlocking a FOLLOW verdict.
  4. Locking an Immutable Prediction (/pick): Select a live upcoming fixture fetched directly from the ESPN Scoreboard API (NBA, NFL, EPL, UCL, La Liga, Serie A, Bundesliga, NHL), enter a win probability, and commit a salted SHA-256 hash on Sui before kickoff alongside a permanent Walrus storage blob.
  5. Autonomous Copy-Trading Bot (/copy-bot): Configure bankroll, Fractional Kelly multiplier (Quarter, Half, or Full Kelly), maximum bet cap, and minimum edge threshold—then run the Audit & Copy Scan to watch Safe-Shield block WATCH (5–0 coin-toss streaks) and SKIP (cherry-pickers) while executing mathematically sized copy-trades with on-chain Sui digests and Walrus blob receipts.

Every audit produces one of three explicit verdicts:

  • FOLLOW: Verified predictive alpha. The forecaster has cleared all 6 mathematical gates (n >= 15 resolved picks, forfeit rate <= 10%, market information depth >= 1.0, shrunk Brier Skill Score >= +0.02, 80% bootstrap lower bound > 0, and no active LESSON override).
  • WATCH: Insufficient statistical proof. The record looks promising (such as a 5–0 hot streak), but the sample size is too small to rule out coin-flip luck. AlphaAgent refuses to risk capital until more picks resolve.
  • SKIP: Negative skill, cherry-picking, or behavioral blindspot. The forecaster either underperforms closing market odds, hides more than 10% of their on-chain commits, or triggers a learned Walrus LESSON rule.

The result is a closed-loop accountability pipeline:

Commit Pre-Kickoff → Verify on Sui via Tatum → Reveal & Capture Market Odds → Resolve Outcome → Persist to Walrus Memory → Synthesize Lessons → Audit & Gate → Size via Fractional Kelly


Why Tatum and Walrus?

Building a lie detector for forecasters required two fundamentally different layers of infrastructure.

The first layer needed to answer questions about cryptographic time and on-chain state:

  • Did this forecaster commit their pick hash before the game kicked off according to the Sui blockchain clock?
  • How many total PickCommitted events has this wallet emitted on Sui?
  • Did an external buyer agent's 0.01 SUI payment transaction actually succeed on-chain?

The second layer needed to answer questions about longitudinal memory and behavioral patterns:

  • What were the revealed details, de-vigged market probabilities, and resolved outcomes of every past prediction?
  • Which on-chain commits were abandoned and never revealed after the game started?
  • Does this forecaster consistently lose money when betting high-confidence NBA favorites (>= 75%) or heavy underdogs (<= 40%), even if their overall record looks acceptable?
  • If the local server database is wiped completely, can the agent reconstruct every forecaster's exact reputation, shrunk Brier Skill Score, and verdict from decentralized memory alone?

Neither layer can do the job alone. Blockchain timestamps prove when a commitment happened, but storing rich multi-field evaluation episodes, market baselines, and semantic behavioral lessons directly in smart contract state is rigid and expensive. Conversely, Walrus Memory preserves rich historical episodes and lessons permanently, but needs Tatum's Sui RPC verification to anchor each memory to an unforgeable pre-kickoff timestamp.

AlphaAgent bridges both layers through a deterministic reconciliation and scoring engine.


The Application Architecture

                       LIVE ESPN SCOREBOARD & ODDS FEED
                  Matchups / Kickoff Times / Market Baselines
                                       |
                                       v
                         PRE-KICKOFF PICK COMMITMENT
                    Canonical JSON + 32-Byte Salt -> SHA-256
                                       |
                    +------------------+------------------+
                    |                                     |
                    v                                     v
                TATUM API                           WALRUS MEMORY
           Sui Testnet JSON-RPC               MemWal SDK + Publisher Nodes
                    |                                     |
      Sui Clock (0x6) Timestamp Check          EPISODE / STATUS / LESSON
      PickCommitted Event Queries             VERDICT Schemas & Blob Proofs
      Account Balance & Tx Inspection         Semantic Recall & Namespace List
                    |                                     |
                    +------------------+------------------+
                                       |
                                       v
                        COMPLETENESS AUDIT INVARIANT
           Sui Commits == Resolved + Forfeited + Disputed + Pending
                                       |
                                       v
                      6-GATE MATHEMATICAL DECISION ENGINE
              Shrunk Brier Skill Score (k=10) + 2,000x Bootstrap
              + Dynamic Lesson Override -> FOLLOW / WATCH / SKIP
                                       |
                    +------------------+------------------+
                    |                                     |
                    v                                     v
           SAFE-SHIELD COPY BOT                   x402 AGENT GATEWAY
      Fractional Kelly: f*=(p-m)/(1-m)         HTTP 402 Challenge (0.01 SUI)
      Blocks WATCH/SKIP · Copies FOLLOW        Signed HMAC-SHA256 Attestation

Every module in the repository maps directly to one stage of this pipeline, ensuring that neither Tatum nor Walrus is treated as a decorative wrapper.


Integrating Tatum: Cryptographic Time and On-Chain Verification

Tatum serves as AlphaAgent's gateway to Sui Testnet. In src/lib/tatumClient.ts, the TatumClient class wraps @mysten/sui/jsonRpc (SuiJsonRpcClient and JsonRpcHTTPTransport) configured with env.TATUM_SUI_RPC_URL and authenticates requests via the x-api-key header on the backend so credentials are never exposed to browser clients.

Token-bucket rate pacing and resilient failover

Public and free-tier RPC gateways enforce strict throughput limits (~3 requests per second). To prevent burst failures during multi-forecaster directory audits, TatumClient implements a deterministic token-bucket RateLimiter enforcing a minimum 350ms interval between consecutive RPC dispatches, paired with:

  • An indefinite LRU cache (max: 10,000 entries) for immutable transaction block lookups (getTransactionBlock), so once a commit or payment digest is verified, it never consumes redundant RPC quota.
  • A 60-second TTL cache for queryEvents calls looking up MoveEventType: "${PACKAGE_ID}::commits::PickCommitted".
  • Automatic failover to the Sui Testnet fullnode (https://fullnode.testnet.sui.io:443) if a gateway timeout or protocol error occurs, ensuring zero downtime during live demos.

Enforcing the Anti-Time Travel and 2-Minute Anti-Stale gates

When a forecaster locks a prediction in src/lib/commitProtocol.ts, AlphaAgent canonicalizes the pick payload (category, eventId, probability, salt, side with alphabetically sorted keys), hashes it with SHA-256, and builds a Programmable Transaction Block (PTB) calling alphaagent::commits::commit with the official Sui Clock object (0x0000000000000000000000000000000000000000000000000000000000000006).

When the forecaster reveals the pick in src/services/revealService.ts, AlphaAgent uses Tatum to fetch the on-chain transaction block (showInput, showEffects, showEvents, showObjectChanges) and enforces three cryptographic gates:

  1. Hash Parity Gate: The revealed fields and 32-byte salt must hash to the exact commit_hash emitted in the on-chain PickCommitted event. Any altered side or probability is rejected as HASH_MISMATCH.
  2. Pre-Kickoff Timestamp Gate: The on-chain committed_at_ms timestamp recorded by the Sui Clock must be strictly prior to the game's kickoff timestamp (commitTs < gameStartTimeTs). Late posts are rejected as AFTER_KICKOFF.
  3. 2-Minute Anti-Stale Line Gate: Forecasters cannot commit a hash early and wait an hour to see whether injury news moves the betting line in their favor before revealing. If revealTs - commitTs > 120 seconds, the reveal is flagged LATE and counted toward the forecaster's forfeit rate.

The Completeness Audit Invariant

In src/services/auditService.ts, AlphaAgent queries all on-chain PickCommitted events for a forecaster via Tatum and reconciles them one-by-one against that forecaster's Walrus Memory namespace. It enforces a strict accounting invariant:

$$\text{Total Commits on Sui} \equiv \text{Resolved Episodes} + \text{Forfeited} + \text{Disputed} + \text{Voided} + \text{Pending}$$

If a forecaster commits a pick on Sui and refuses to reveal it after their team loses, the unrevealed commit cannot be hidden. AlphaAgent records a FORFEITED status in Walrus Memory and penalizes the forecaster. Any forecaster whose forfeit rate exceeds 10% (MAX_FORFEIT_RATE = 0.10) automatically fails Gate 1 and receives an immediate SKIP verdict.


Integrating Walrus: Permanent Episodic and Behavioral Memory

While Tatum proves what was committed on Sui and when, Walrus Memory gives AlphaAgent a permanent, reconstructible brain that remembers how each forecaster performs over time and why specific categories or confidence bands are dangerous.

In src/lib/walrusClient.ts, WalrusClient integrates both:

  1. Direct Walrus Testnet Publisher Nodes (https://publisher.walrus-testnet.walrus.space/v1/blobs?epochs=5, with automatic fallback across secondary testnet publishers) to store raw memory buffers and return verifiable on-chain Walrus Blob IDs and Sui Object IDs.
  2. The Walrus Memory SDK (@mysten-incubation/memwal) connected to the Walrus Memory relayer for namespace-scoped storage and semantic vector recall (recallMemories), governed by a 2,000ms paced write queue so burst logging never triggers relayer throttling.

Four canonical Walrus Memory schemas

Rather than dumping unstructured JSON into storage, AlphaAgent defines four versioned, human-readable, pipe-delimited canonical schemas in MemoryCodec (src/lib/walrusClient.ts) stored under forecaster-specific partitions (aa-f-<address_prefix>) and a global discovery registry (aa-registry):

  1. EPISODE (Resolved Pick Record):
   EPISODE | v1 | forecaster 0x... | category NBA | event nba_game_42 | pick HOME | forecast 0.6500 | market 0.5000 (OddsAPI, de-vigged, ts 1730246400) | outcome win | commit_tx tx_digest_99 | commit_ts 1730246400 | sources agree 2/2 | resolved 1730300000
  1. STATUS (Forfeited, Disputed, or Voided Commit):
   STATUS | v1 | forecaster 0x... | commit_tx tx_abandoned_1 | state forfeited | reason unrevealed by kickoff | ts 1730248000
  1. LESSON (Synthesized Behavioral Blindspot Rule):
   LESSON | v1 | forecaster 0x... | category NBA | band confident | finding: 1 of 5 confident picks won, raw BSS -0.76 | rule: SKIP confident NBA picks until n>=8 and BSS>0 | trigger_n 5 | ts 1730300000
  1. VERDICT (Reputation State Transition & Cited Blobs):
   VERDICT | v1 | forecaster 0x... | state_transition WATCH -> SKIP | category NBA | score -0.7600 | sample_n 5 | cited_lessons blob_id_1 | ts 1730300000

Dynamic Lesson Synthesis: Memory that overrides future decisions

One of the most important capabilities in src/services/lessonEngine.ts is that AlphaAgent doesn't just passively archive outcomes—it actively learns from them.

Every 5 resolved picks, LessonEngine.analyzeAndSynthesizeLessons groups a forecaster's history by sport category and probability band:

  • underdog: forecast <= 0.40
  • balanced: 0.41 <= forecast <= 0.74
  • confident: forecast >= 0.75

If a forecaster exhibits severe negative calibration in a specific band (for example, rawBss < -0.20, winning fewer than 40% of confident picks, or going 0-for-3+ on underdog picks), AlphaAgent automatically synthesizes a LESSON record and writes it to Walrus Memory along with a VERDICT state-transition blob citing that lesson.

Later, when a new pick arrives for that forecaster, decisionEngine.evaluateWithMemoryRecall queries Walrus Memory (checkLessonOverrideForPick). If an active LESSON matches the upcoming pick's category and confidence band, the recalled memory overrides the evaluation and forces a SKIP verdict—even if the forecaster's aggregate win rate across other bands looks healthy.


Building a Mathematical Decision Engine That Refuses the 5–0 Streak

Like a disciplined quantitative fund, AlphaAgent does not ask an LLM to guess whether a tipster "sounds trustworthy." The scoring and decision engines (src/lib/scoringEngine.ts and src/services/decisionEngine.ts) are 100% deterministic.

1. Proper scoring against the de-vigged closing line

For every resolved episode $i \in {1, \dots, n}$ with forecaster probability $f_i$, de-vigged market baseline probability $m_i$, and binary outcome $o_i \in {0, 1}$, AlphaAgent computes the quadratic Brier Score for both the forecaster and the bookmaker market:

$$\text{BS}{\text{user}, i} = (f_i - o_i)^2, \qquad \text{BS}{\text{mkt}, i} = (m_i - o_i)^2$$

The raw Brier Skill Score ($\text{BSS}_{\text{raw}}$) measures the forecaster's proportional improvement over the closing market baseline:

$$\text{BSS}{\text{raw}} = 1 - \frac{\sum{i=1}^{n} \text{BS}{\text{user}, i}}{\sum{i=1}^{n} \text{BS}_{\text{mkt}, i}}$$

A positive $\text{BSS}_{\text{raw}}$ means the forecaster is more accurate than the de-vigged closing market; a negative score means copying them loses money relative to the market line.

2. Bayesian prior shrinkage ($k = 10$) and 2,000-iteration bootstrap

Small samples produce extreme, noisy raw skill scores. To prevent a 5–0 coin-flip run from fooling the system, AlphaAgent dampens $\text{BSS}_{\text{raw}}$ toward a zero-skill prior with weight $k = 10$:

$$\text{BSS}{\text{shrunk}} = \text{BSS}{\text{raw}} \cdot \frac{n}{n + k} = \text{BSS}_{\text{raw}} \cdot \frac{n}{n + 10}$$

At $n = 5$ picks, two-thirds of the raw score is shrunk away ($\frac{5}{15} = 0.333$). For example, a 5–0 streak with a raw Brier Skill Score of +41.2% is dampened to +13.7%, and simultaneously blocked by the minimum sample gate ($n \ge 15$). In addition, ScoringEngine runs 2,000 bootstrap resampling iterations with replacement to compute the empirical 80% confidence lower bound (bootstrapLowerBound80).

3. The 6 independent audit gates

Before any forecaster can earn a FOLLOW verdict, they must pass all six gates in DecisionEngine.evaluate:

Gate Requirement What It Prevents
1. Forfeit Rate Gate forfeitRate <= 10.0% Cherry-picking and deleting losing picks after kickoff
2. Minimum Sample Size Gate n >= 15 resolved picks Coin-flip hot streaks (5–0 happens 1 in 32 times by chance)
3. Market Information Depth Gate $\sum \text{BS}_{\text{mkt}} \ge 1.000$ Padding win rates by only betting -500 heavy favorites
4. Shrunk Skill Score Gate $\text{BSS}_{\text{shrunk}} \ge +0.0200$ Following forecasters who fail to beat closing market odds
5. 80% Bootstrap Confidence Gate bootstrapLowerBound80 > 0 High-variance flukes where skill isn't statistically distinct from zero
6. Category & Lesson Gate $n_{\text{cat}} \ge 8$, $\text{BSS}_{\text{cat}} > 0$, no SKIP Lesson Copying a soccer specialist when they make an overconfident NBA pick

Proving That Walrus Is the True Brain: The Database Wipe & Rebuild Test

A common failure mode in hackathon projects is treating decentralized memory as a write-only log while actually serving the application from a local SQLite or JSON file.

To prove that Walrus Memory is AlphaAgent's genuine source of truth, I built an automated disaster recovery verification script in scripts/wipe-and-rebuild.ts (pnpm run test:wipe-rebuild):

  1. Seed a 3-Forecaster Cohort into Walrus Memory:
    • Novice (0x1111...): 5–0 record (n = 5 wins). Expected verdict: WATCH.
    • Verified Pro (0x2222...): 18–7 record (n = 25 resolved picks beating the closing line, 0 forfeits). Expected verdict: FOLLOW.
    • Cherry-Picker (0x3333...): 10 resolved wins plus 3 unrevealed FORFEITED commits (23.1% forfeit rate). Expected verdict: SKIP.
  2. Snapshot Pre-Wipe Verdicts: AlphaAgent evaluates all three forecasters and writes their verdicts, shrunk Brier Skill Scores, and sample sizes to data/local-cache.json.
  3. Simulate Total Server Failure (unlinkSync): The script deletes data/local-cache.json from disk and cold-boots the evaluation pipeline with zero local cache.
  4. Cold-Boot Reconstruction from Walrus: AlphaAgent queries the global aa-registry namespace on Walrus, discovers all registered forecaster addresses, streams every EPISODE, STATUS, and LESSON blob from each aa-f-<prefix> partition, and recomputes every statistical profile.
  5. Bit-for-Bit Parity Assertion: The script asserts that every restored verdict (WATCH, FOLLOW, SKIP), sample size (5, 25, 10), and shrunk Brier Skill Score matches the pre-wipe snapshot within < 0.0001 tolerance.

Safe-Shield Autonomous Copy-Trading and Fractional Kelly Sizing

Auditing tipsters is valuable for human bettors, but AlphaAgent goes a step further by embedding those verdicts directly into an Autonomous Copy-Trading Bot (src/services/copyTradingBot.ts and src/lib/kellyCalculator.ts).

When the bot scans pending pre-kickoff fixtures from monitored forecasters, every candidate trade must pass Three-Stage Gate Enforcement:

  1. Stage 1 — Anti-Time Travel Gate: The match must be more than 1 minute away from kickoff (minsUntilKickoff > 1), and no duplicate position can exist for that event and forecaster.
  2. Stage 2 — AlphaAgent Safe-Shield Gate: The bot queries the forecaster's Walrus Memory namespace and runs decisionEngine.evaluate. Only forecasters with a verified FOLLOW verdict are eligible. Any candidate pick from a WATCH forecaster (such as StreakKing at 5–0) or a SKIP forecaster (such as HypeTips with an 18% forfeit rate) is automatically blocked before capital is touched.
  3. Stage 3 — Fractional Kelly Sizer: For approved FOLLOW picks, KellyCalculator.calculate computes the exact mathematical stake from the forecaster's probability $p$ and de-vigged market probability $m$ (where fair decimal odds $O = 1/m$ and net odds $b = O - 1$):

$$f^* = \frac{b \cdot p - (1 - p)}{b} = \frac{p - m}{1 - m}$$

To protect the bankroll from estimation variance, AlphaAgent multiplies $f^$ by the user's chosen **Fractional Kelly multiplier* (default Quarter Kelly, 0.25x) and caps any single position at a configurable maximum percentage of bankroll (e.g., 2.5% or 5.0%), rejecting any bet whose edge $p - m$ falls below the minimum edge threshold (minEdge = 2.0%).

Every executed copy-trade generates a salted SHA-256 commitment hash, logs a permanent COPY_TRADE | v1 | ... record to Walrus storage (returning a verifiable Walrus Blob ID and Sui Object ID), and records the transaction receipt in the Executed Copy Trades Ledger.


Machine-to-Machine Agent Commerce via HTTP 402 (x402)

AlphaAgent is designed not only for human bettors via its web interface, but also as an oracle for other autonomous trading agents in the Web3 agent economy.

In src/services/x402Service.ts and scripts/buyer-agent.ts, AlphaAgent implements the x402 micropayment protocol (protocol: "x402/sui-v1"):

  1. Unauthenticated Inquiry → HTTP 402 Payment Required: When an external AI agent queries /api/v1/verdict?forecaster=0x...&category=NBA without payment headers, AlphaAgent returns an HTTP 402 challenge containing a unique cryptographic nonce (inv_...), a 10-minute expiration window, and an invoice for 0.01 SUI (10,000,000 MIST).
  2. On-Chain Settlement & Tatum Verification: The buyer agent transfers 0.01 SUI on Sui Testnet and retries the request with X-Payment-Digest and X-Invoice-Nonce headers. X402Service.verifyPayment inspects the transaction block via Tatum RPC (effects.status.status === "success") and enforces replay protection so a transaction digest can never be redeemed twice.
  3. Cryptographically Attested Verdict Bundle: Upon verification, AlphaAgent releases the full PaidVerdictResponse—including the 6-gate VerdictBundle, cited Walrus Memory blob IDs, Sui commit digests, and an HMAC-SHA256 cryptographic attestation seal signed by AlphaAgent_DueDiligence_Authority_SuiTestnet.

The Technical Stack and Engineering Decisions

AlphaAgent is built with a fast, zero-bloat TypeScript stack designed for deterministic verification and instant judge onboarding.

Layer Technology Responsibility
Application & API Server Node.js, TypeScript (tsx), Native HTTP (src/server.ts) Multi-route web UI (/, /tipsters, /check, /memory, /luck-lab, /pick, /copy-bot, /profile), REST API, and x402 gateway
Blockchain & Clock Sui Testnet via Tatum JSON-RPC (@mysten/sui) Token-bucket rate-paced (350ms) RPC queries, PickCommitted event indexing, balance checks, and tx verification
Permanent Memory Walrus Memory SDK (@mysten-incubation/memwal) & Walrus Publisher Nodes Paced (2,000ms) blob writes, canonical EPISODE / STATUS / LESSON / VERDICT codecs, and semantic recall
Live Sports & Odds ESPN Live Scoreboard API & OddsEngine (src/lib/oddsEngine.ts) Real-time fixtures across 9 leagues (NBA, NFL, EPL, UCL, UEL, La Liga, Serie A, Bundesliga, NHL) and de-vigged market baselines
Statistical & Decision Core ScoringEngine, DecisionEngine, LessonEngine Shrunk Brier Skill Score ($k=10$), 2,000-iteration bootstrap CI, 6-gate verdict logic, and blindspot rule synthesis
Copy-Trading & Sizing CopyTradingBotService & KellyCalculator Three-stage Safe-Shield enforcement and Fractional Kelly position sizing
1-Click Onboarding JudgeModeService (src/services/judgeModeService.ts) Instant Ed25519 guest sandbox wallet provisioning on Sui Testnet with zero browser extension friction

Verification and the 1-Command Proof Suite

Every mathematical and infrastructure claim in the repository is backed by automated test suites (tests/*.test.ts) and a single end-to-end verification command (pnpm run prove in scripts/prove.ts) that validates all 8 core stages:

  • Stage 1: Tatum Sui RPC token-bucket rate limiter (>= 350ms spacing verified).
  • Stage 2: Walrus MemoryCodec lossless serialization and parsing roundtrips.
  • Stage 3: Brier Skill Score and Bayesian prior shrinkage ($\text{BSS}{\text{shrunk}} = \text{BSS}{\text{raw}} \cdot \frac{n}{n+10}$) plus 2,000-iteration bootstrap bounds.
  • Stage 4: The 5–0 Refusal—proving that a 5-0 record (100% win rate) is assigned WATCH rather than FOLLOW with explicit missing-sample criteria.
  • Stage 5: 30-Pick Master Qualification—proving that a 30-pick forecaster with positive shrunk edge and 0 forfeits clears all 6 gates to earn FOLLOW.
  • Stage 6: Dynamic Lesson Synthesis & Recall Override—proving that a forecaster losing 4 of 5 confident (>= 78%) NBA picks triggers a Walrus LESSON blob (SKIP confident NBA picks until n>=8 and BSS>0) that overrides their next confident NBA pick to SKIP.
  • Stage 7: Completeness Audit Invariant—reconciling 3 Sui commits against 2 resolved episodes and 1 forfeit status (100% completeness, 33.3% forfeit rate).
  • Stage 8: x402 Machine-to-Machine Micropayment—issuing an HTTP 402 challenge for 0.01 SUI, verifying settlement on Sui Testnet, and releasing the signed verdict bundle.

Challenges and Lessons From Building AlphaAgent

Building AlphaAgent highlighted several practical truths about designing memory-powered financial and prediction agents.

1. A leaderboard without the denominator is an illusion

In prediction markets and sports betting, raw win streaks are the easiest metric to game. Preserving unrevealed commitments as explicit FORFEITED status blobs in Walrus Memory turned out to be just as important as storing winning episodes. Once the denominator is immutable, selective memory stops working.

2. Memory should be able to veto a decision

Storing historical episodes is table stakes; the real breakthrough came when LessonEngine began synthesizing recurring failure patterns (confident favorites or underdog traps) into LESSON records that actively veto future picks during semantic recall. Memory becomes far more valuable when it can override a naive aggregate score.

3. Bayesian shrinkage is essential for small-sample agent safety

Without prior dampening ($k = 10$) and a minimum sample gate ($n \ge 15$), any autonomous copy-trading bot will inevitably over-allocate bankroll to lucky novices on 4–0 or 5–0 coin-flip runs. Encoding statistical skepticism directly into the decision engine protects capital before the Kelly sizer ever runs.

4. Real-world RPC and relayer budgets require disciplined pacing

Operating against live Tatum Sui RPC endpoints and Walrus Memory relayers meant designing around rate limits from day one. Adding a 350ms token-bucket queue with indefinite tx-digest caching for Tatum and a 2,000ms write queue with multi-publisher fallback for Walrus made the application fast and resilient under load.

5. Zero-friction onboarding makes verification accessible

Not every hackathon judge or visitor wants to install a wallet extension and hunt for testnet faucet tokens before testing an audit flow. Building 1-Click Guest Mode—which provisions an ephemeral Sui keypair and lets users lock picks on Sui, inspect Walrus blobs, and run the Copy Bot immediately—made the entire verification loop testable in seconds.


What Comes Next for AlphaAgent?

The current version of AlphaAgent proves a foundational thesis: prediction track records and copy-trading decisions should be governed by pre-kickoff cryptographic timestamps and permanent, reconstructible memory rather than self-reported streaks.

Next, I plan to expand AlphaAgent across several dimensions:

  • Multi-oracle decentralized resolution: Extending ResolutionEngine beyond two-source sportsbook/ESPN consensus to support on-chain optimistic oracle feeds and automated smart-contract escrow settlement.
  • Encrypted pre-kickoff commitments with automated keeper reveals: Allowing forecasters to store encrypted pick payloads that reveal automatically at kickoff so honest forecasters never accidentally forfeit if they are offline when a game starts.
  • Cross-protocol prediction market adapters: Expanding beyond sportsbook moneyline markets to audit forecasters across on-chain prediction markets, price-target feeds, and governance outcomes.
  • Portfolio-level Kelly covariance: Upgrading KellyCalculator to account for simultaneous correlated positions across games kicking off in the same time window.

Final Thoughts: Screenshots Show Streaks. Memory Preserves Evidence.

For years, online tipsters and prediction gurus have relied on the same playbook: broadcast the winners, delete the losers, and let short coin-flip streaks masquerade as expertise.

When you combine Tatum and Sui with Walrus Memory, that playbook breaks down:

  • With Sui and Tatum, every prediction is anchored to an official blockchain timestamp before kickoff, and every commit must be accounted for.
  • With Walrus Memory, every resolved episode, every unrevealed forfeit, and every learned behavioral blindspot is preserved permanently—surviving even a complete local database wipe.
  • With Bayesian shrinkage and the 6-gate decision engine, a 5–0 coin-flip streak is recognized as WATCH rather than FOLLOW.
  • And with the Safe-Shield Fractional Kelly Copy Bot, capital is allocated by verifiable mathematical edge rather than hype.

Because seeing a 5–0 streak is easy. Remembering every pick that was locked, every loss that was hidden, and why the math says to wait is what actually protects your bankroll.

Evidence over streaks.


Explore AlphaAgent

來源:DEV Community · dev.to