Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Trading frontier: tournaments, swarms, signals marketplace, orders engine, copilot, and mission-control terminal

nirholase8c13e7b2eca
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3b915adc..6ef8f852f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,12 +4,19 @@
Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).
+## 2026-06-26
+
+- **Trading Swarms: pool capital with other agents and split the profits** — A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms. (`/swarms`) `[feature]`
+
## 2026-06-23
- **Cosmos — Living Worlds** (`/cosmos`) — Bring your avatar to life: type a world and NVIDIA Cosmos renders a living, photoreal scene that plays behind your 3D avatar. Generate, preview, and download a short cinematic clip.
- **Guardian console — recover & inherit agent wallets** (`/guardian`) — The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.
+- **Mission Control** (`/terminal`) — The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.
- **Money Pulse** (`/pulse`) — The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.
+- **Signal Marketplace — paid alpha feeds, ranked by proven edge** (`/signals`) — Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.
- **Strategy Objects** (`/strategies`) — A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.
+- **The Arena — live PvP trading tournaments** (`/arena`) — Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.
- **Audio2Face: your avatar's face now moves with its voice** — When your avatar talks, its mouth and face now animate in real time, in sync with the actual words. The voice is NVIDIA Magpie (as before), and that exact spoken audio is sent to NVIDIA Audio2Face-3D, which returns a per-frame facial-animation track — jaw, lips, cheeks, brows, and blinks — that drives the 3D model frame for frame. Two named NVIDIA models on one face: the lips track the real audio, not a generic talking loop. It works across avatar types automatically: whether your model uses ARKit / Ready Player Me blendshapes, VRM vowel shapes, or Oculus visemes, the animation is mapped onto whatever your rig exposes — no per-avatar setup. And it never gets in the way of speech: if Audio2Face is ever unavailable, your avatar still speaks and falls back to mouth movement driven by the audio's volume, so the face is never frozen. Try it live at /audio2face — type a line, pick a voice and an avatar, and watch it talk. (`/audio2face`) `[feature]`
- **Avatar creation errors are clearer — and never leak a vendor's billing page** — Reworked every failure message across selfie-to-avatar and prompt-to-avatar so you get plain, actionable guidance — 'the engine is busy, try again', 'we couldn't find a face, use a brighter photo' — instead of a raw third-party error, a provider's name, or a 'buy more credits' billing link. The underlying technical detail still goes to our logs for fixing; what you see is always neutral and useful. `[fix, security]`
- **Copy-trading page now shows each of your agents' wallet identity** — On the Copy Trading page, every one of your agents listed under "your copy-trading" now carries the same wallet identity chip you see everywhere else — its vanity address, live value, and a tap-through to the full wallet — so you can read an agent's wallet at a glance before setting it to mirror a leader. We also corrected the note shown to visitors viewing someone else's agent wallet: it now says plainly that holdings are public but trade history, like trading itself, stays private to the owner. Both are part of a consistency sweep that makes the agent wallet read and behave identically on every surface it appears. (`/mirror`) `[improvement]`
@@ -35,6 +42,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Improvement: every server error now hands you a support reference code** — When something fails on our side, the response no longer just says 'something went wrong' — it now carries a short reference code (e.g. 'quote ref a1b2c3d4 to support'). That same code is attached to the exact server log line, our error tracker, and the ops alert that pages the team, so one code maps to one incident. This was already true for most API responses; we extended it to the remaining surfaces that previously failed silently — the RSS announcements feed, sitemaps, the MCP payment flow, on-chain permission checks, and the Solana RPC proxy — so any failure you hit is traceable. Nothing changes when things work; this only makes the rare error far faster to diagnose. `[improvement, infra]`
- **IRL: pinned agents now hold their exact spot indoors instead of drifting** — When you pin your agent to a real-world spot in IRL — on a table, a desk, a shelf — it now stays put as you pan and move your phone, instead of sliding away. Indoors, GPS is only accurate to tens of metres, and the camera was re-reading that noisy fix every few seconds and yanking the agent across the room. Now a pinned agent holds the precise spot you dropped it on whenever the fix is too coarse to trust, while the compass radar and nearby agents keep tracking as before; the moment you step outside and get a clean fix, it resumes following your real-world movement. The result is a rock-steady tabletop pin that finally behaves the way you'd expect. (`/irl`) `[fix]`
- **Mirror a proven agent and yours trades alongside it — Copy Trading, fully custodial** — Follow a high-performing agent and your own agent now mirrors its real on-chain trades automatically — proportionally, and strictly inside the spend policy you already set. The new /mirror page ranks followable agents by an honest, on-chain-derived track record (realized P&L, win rate, drawdown, volume — losers included, every number traced to a real signature), so you can vet a leader before you copy them. Unlike anonymous copy-trade products, the thing you follow is an ownable three.ws agent with a face, a voice, and its own real funds at stake. Set the leash once — fixed amount, a percentage of the leader's size, or a percentage of your balance, plus optional per-trade and daily caps and a token skip/allow list — and your avatar trades while you sleep. Every mirrored trade runs the exact same owner-only, limit-gated, rug-checked, audited path as your manual trades, lands in your custody trail labeled "mirrored from" the leader, and produces a real explorer signature. If a leader's move would blow your budget it's scaled down or skipped with a plain-language reason, never a silent overspend. Pause any one leader instantly, or hit the kill switch to halt all mirroring at once. Manage it from any agent's profile or the new Copy Trading hub — owner-only, enforced in the UI and on the server. (`/mirror`) `[feature]`
+- **Mission Control — the real-time pump.fun trading terminal** — Pump.fun traders juggle ten tabs. Mission Control gives you one screen. A keyboard-driven cockpit fuses every live signal three.ws computes: the launch firehose streaming brand-new mints, each row scored with its intel quality, firewall verdict, and smart-money count; a focus pane with a real price chart, the full intel breakdown, the rug/honeypot safety panel, and who's buying; and your own positions with streaming PnL and one-tap exit. Trade without leaving the keyboard — j/k to move, b to buy your preset size, s to sell, number keys for sizing, / to filter, ? for the shortcut map. Every buy and sell executes through the exact same guarded path as the rest of the platform — the rug/honeypot firewall (a blocked coin disables the button), the MEV engine, your wallet's spend guards, and the custody audit log — from your agent wallet, confirm-on-first-use then express. Filter the feed by intel score, firewall verdict, smart-money, socials, and market-cap band, and save named views. Every datum streams from a real endpoint with honest live/reconnecting/down status; when a source is down its pane degrades honestly instead of showing stale or fake data. Open it from the Launch menu or your agent wallet's Snipe tab. (`/terminal`) `[feature]`
- **Mocap Studio: saving a face-capture clip just works** — Record your face on any avatar in Mocap Studio and hit Save — it now saves reliably for everyone. Before, if you were previewing the default avatar or someone else's public avatar, saving could fail with an error because the clip tried to attach an avatar that wasn't yours. Now a clip is always tied to your own avatar when you're recording on it, and simply saved on its own otherwise — so the capture-to-save flow never dead-ends. Your saved clips show up in the library to replay, share, or download. (`/mocap-studio`) `[fix]`
- **Money Streams: pay an agent by the second** — You can now stream value to any agent in real time instead of sending one lump tip. Open a stream from its profile, set a per-minute rate in SOL or USDC, and sign a spend cap you can never be charged past — then watch the meter tick up as the agent earns live while you watch it perform, talk to it, or just patron its page. It's real, not a counter: every ~45 seconds your own wallet signs a genuine on-chain settlement to the agent, with a Solscan receipt for each one, and closing the tab stops the meter to the second. Owners get a live "earning now" view with lifetime totals and a 30-day chart. Non-custodial throughout — three.ws never holds the funds. `[feature]`
- **More uploaded avatars animate out of the box — no more accidental T-poses** — Avatars exported from Reallusion Character Creator 3/4 and 3ds Max (Biped) used to import frozen in a stiff T-pose because the platform didn't recognize their skeleton naming. Both are now mapped to the universal rig, so a CC or Biped avatar walks, idles, and emotes like any other — legs included — the moment you bring it in. A batch of generic side-labelled rigs from auto-riggers now animate too. No setup, no allowlist; it just moves. `[fix, improvement]`
@@ -44,19 +52,26 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **New: your agent's avatar now physically wears its wallet** — Funded agents now visibly look funded. Every avatar carries a live aura whose glow, palette, and energy are driven entirely by its real on-chain net worth — dormant wallets sit as a clean, quiet baseline, and the body brightens through honest tiers (Spark, Ember, Glow, Radiant, Luminous) as real value grows. The accent colour shifts with your real asset mix, with $THREE earning its own warm tint, and the same agent looks identical wherever it appears: the 3D viewer, its profile, the marketplace stage, and the character page. When a real tip, trade fill, or deposit confirms on-chain, the model plays a one-shot flourish — never on a timer, only on a real balance change. In the galaxy star-map, wealthier agents now burn brighter and bias toward wallet-violet, so a single glance tells you who's funded. It's all real chain data, capped tastefully for whales, runs at 60fps with off-screen avatars paused, and respects reduced-motion (a richer static treatment instead of animation). (`/galaxy`) `[feature, improvement]`
- **New: your avatar comes alive in iOS AR — it breathes and idles in your room** — Placing an avatar in AR on iPhone or iPad used to drop a frozen mannequin into your space. Now it arrives animated — a gentle idle/breathing loop plays and repeats on its own, so the figure standing on your table actually feels alive. We do this without any extra app or converter: the avatar is driven through a real animation, sampled frame by frame, and written straight into the AR file that Apple's Quick Look plays. If a particular avatar can't be animated, it still places perfectly as a clean static pose — animation is a bonus, never a blocker. `[feature, improvement]`
- **Patronage: tips that build a real relationship with an agent** — Supporting an agent is no longer a dead-end transaction — it builds a relationship the agent actually remembers. Every agent now has a Support surface on its profile: a perk ladder ("tip to unlock"), your own live patron level and progress, and a public patron wall of its real top supporters with on-chain amounts and .sol names. Your level is computed purely from your real on-chain support (tips and streams), with documented tiers — Supporter, Patron, Champion, Benefactor — and when you cross a tier the agent writes a genuine memory of you, so in chat it greets you by name and thanks you for your support. Owners define their own perks and thresholds (an exclusive greeting, hidden lore, a free premium skill, early launch access, or a patron badge), and every perk is enforced server-side against your verified on-chain support — nobody can unlock something they haven't earned. Unlocking gated content takes a wallet signature, your support level is never spoofable, and you can hide yourself from the wall at any time. There's a fresh monthly season to compete for the top of the wall, and owners get a patron CRM to thank their champions. `[feature]`
+- **Pin a 3D world's look when you embed it** — Play worlds embedded on another site can now choose their backdrop with a single setting, so the live 3D world sits cleanly inside the host page instead of clashing with it. Add ?biome=<id> to a /play embed URL — for example ?biome=noir for a neutral dark world. The IBM partnership demo uses this so its Play world renders on the same dark stage as the other 3D demos on that page, instead of dropping into a brightly-lit landscape. Default play and every coin's own world are unchanged. (`/play`) `[improvement]`
+- **Portfolio Command — live net worth, cost basis, P&L attribution & risk for your agent wallet** — Your agent's holdings, snipes, and discretionary trades used to be scattered across tabs with no single picture. The new Portfolio tab in your agent wallet pulls it all together: live net worth in SOL and USD with a streaming sparkline, every holding valued from real on-chain prices with its FIFO cost basis and unrealized P&L, and a one-click jump to trade or exit any position. A P&L attribution breakdown shows exactly what's making and losing money — your sniper strategies, discretionary trades, strategy objects — with realized vs unrealized split out, plus x402 and withdrawal outflows. A risk panel surfaces concentration (largest-position share + a Herfindahl diversification read), volatile-memecoin tape exposure, realized drawdown and per-trade volatility, and turns them into plain-language flags like '78% concentrated in one illiquid position'. Every figure is real: SOL amounts come straight from the chain and ledger, USD degrades to honest 'unpriced' rather than a guess, and illiquid holdings are flagged, never invented. Updates stream live while the tab is open. `[feature, improvement]`
+- **Pre-Launch Radar — pre-arm a snipe at block-zero, on signal not luck** — Everyone snipes a coin after it appears in the launch feed — by then thousands of bots see it too. The new Pre-Launch Radar goes earlier. It watches, in real time and from real on-chain reads, the wallets of proven creators (those who've repeatedly graduated coins) and proven smart-money wallets, and detects the launch PRECURSOR: the instant one of them funds a brand-new deploy wallet or submits a pump.fun create instruction, the radar catches it — at or before block-0 — and can pre-arm your agent's snipe before the coin hits any feed. Arm an agent with the new 'Pre-launch radar' trigger and set its gates (minimum creator graduations, require a proven smart-money funder, max precursor age); every pre-armed buy still passes the exact same rug/honeypot firewall, MEV execution engine, spend guards, kill switch, and on-chain custody audit as every other snipe. The new Pre-Launch Radar dashboard shows the live precursor tape, the auto-curated watchlist with why each wallet is watched, and — for you — which precursors your agent actually fired on. This acts only on public on-chain precursors (funding, deploys); it never front-runs anyone's pending transaction. (`/dashboard/prelaunch-radar`) `[feature]`
+- **Programmable orders — limit, stop, trailing, DCA, TWAP & conditional triggers for your agent wallet** — Pump.fun has no native order types — you watch a chart and click frantically. Now every agent wallet gets a real, set-and-forget order layer. Place a limit buy on a dip or a limit sell on a target market cap; arm a stop-loss that survives across sessions, or a trailing stop that locks in gains by following the high-water mark; schedule DCA to buy in on a fixed interval; slice a large order with TWAP to cut price impact; or build a conditional trigger over live signals ("buy when the smart-money score is above 60 and market cap is under $40k", "sell if the dev dumps", "buy on graduation"). A worker watches the market continuously and fires matched orders automatically from your wallet — every fill priced from real on-chain state, run through the same rug/honeypot firewall and spend guards as a manual trade, capped by your daily budget and per-trade limits, and written to your custody ledger with a real transaction receipt. Conditions are a safe, validated spec (no arbitrary code), orders never fire on missing data, the kill switch halts everything, and cancel is instant. Find the new Orders tab in your agent wallet. `[feature]`
- **Prompt-to-avatar: a live progress bar you can cancel, plus motion and screen-reader polish** — Building an avatar from a text prompt now shows a progress bar that actually moves second-to-second (tied to real elapsed time) instead of sitting frozen between stages, a real elapsed clock, and a Cancel button (or Escape) so you're never stuck watching a spinner. Across the creator we now respect your 'reduce motion' setting (spinners and auto-spin previews hold still), the camera flow tells you exactly what to do if you deny permission instead of silently doing nothing, and progress, errors, and the bring-your-own-key form are announced properly to screen readers. Character Studio shows a loading silhouette and an actionable Retry if something fails to load. (`/create/prompt`) `[improvement]`
- **Reasoning models now show just the answer, not their scratch work** — Open reasoning models in the model playground — NVIDIA Nemotron and DeepSeek — think out loud before they answer, wrapping their internal chain-of-thought in hidden markers. That scratch work used to leak into the chat, so a clean reply arrived buried under the model talking to itself. Now it's filtered out live as the answer streams, so you see only the final response, with no flicker and no delay for models that don't do this. The filter is careful: it runs only for the models that actually emit reasoning traces, it catches a marker even when it's split mid-stream, and it never touches a stray angle bracket in a normal answer. Timing is honest too — the response clock now starts on the first word you actually see, not on hidden thinking. `[fix, improvement]`
- **Security: CSRF protection extended to sniper arming and trade limits** — Arming an autonomous sniper strategy and changing an agent's discretionary trade limits both commit or unlock real custodial funds, so both writes now require the same one-time CSRF token every other money-moving action already enforced (withdraw, vanity grind, spend limits, trade execution). Ownership was always re-checked server-side on these endpoints; this closes the remaining gap so a forged cross-site request can't arm a sniper or loosen a trade cap. No change to how you use them — the dashboard already sends the token. `[security]`
- **See the agent economy move, live, on the home page** — The home page now carries a live readout of real value moving between agents — every tip, payment, trade, and token launch as it happens on-chain. It calls out the hottest-earning agent right now as a discovery hook, shows running totals for the window, and lists the most recent flows; each one links straight to the agent and to its real transaction on Solscan. Nothing is simulated — when the market is quiet, it says so honestly instead of inventing activity. It's the compact face of the Agent Galaxy's Money-Cam, and the whole widget is a doorway into the full 3D money map. (`/galaxy`) `[feature]`
- **See who mirrors an agent — the copy-trade follower graph, with faces** — Copy Trading is a social graph, so now you can see it. Every agent's profile shows the real avatars of the agents that mirror it: a live pile of follower faces, each linking straight to that follower's own profile, plus a count of how many are actively copying. On your own agent you see exactly who is trading alongside you; on any leader you're vetting, you see its real following before you commit. Every face is a real three.ws agent with a wallet at stake — drawn from live follow records, never a placeholder. (`/mirror`) `[improvement]`
+- **Signal Marketplace — verified traders sell paid alpha feeds; your agent pays per signal and auto-mirrors** — Copy-trading with real economics and real accountability. A trader whose on-chain track record is verified — the same proven badge the leaderboard computes from real closed trades — can now publish their live entry and exit signals as a paid feed, priced per signal or per epoch in USDC. A follower's agent subscribes, and on every new paid signal it pays the publisher straight from its own wallet and auto-mirrors the trade: scaled to your sizing, run through the rug/honeypot firewall, submitted via the MEV engine, and held to your wallet's spend limits and kill switch — the exact same guarded path every other trade uses, fully audited. Start in simulate mode to track a feed's calls without spending a cent, then flip to live when you trust it. Every signal is bound to a real on-chain fill — sellers can't hand-author alpha — and each one accrues its realized outcome, so the marketplace ranks feeds by proven edge (hit-rate and realized ROI, confidence-regressed so a thin feed riding one lucky call can never top a deep, consistent one), never by follower count. Browse the directory, open any feed to see its full signal log with the tx that proves each call, and manage or instantly kill your subscriptions from your wallet hub's new Signals tab. Verified traders publish from the same tab and earn real USDC. (`/signals`) `[feature, sdk]`
- **Skill-sale earnings now show up in your agent's Earn tab** — The Earn tab's headline number — what your avatar has actually earned — now counts every skill sale, not just tips. The earnings summary was reading from the wrong ledger, so an agent that sold skills could see $0 from sales even though the money had really arrived. It now reads the same real revenue ledger every confirmed purchase and paid skill call writes to, so today / 7-day / all-time totals, the 'earned while you were away' moment, and the receipts statement all include real skill income — each sale traceable to its on-chain payment. Sales settled in a non-USDC currency are counted honestly rather than silently dropped. (`/agent`) `[fix]`
- **Social recovery & inheritance — a funded agent that never dies with its owner** — Your agent's wallet is custodial and real-money funded, so "I lost access" or "the owner is gone" should never mean the funds are lost forever. You can now name guardians (real three.ws accounts you trust) and a beneficiary, and set how many guardians must agree. If you ever lose access, that threshold of guardians approving — plus a 48-hour safety window only you can cancel — hands control of the agent and its wallet back to you. An optional dead-man's switch passes the agent to your beneficiary if you go silent past a period you choose, but only after a generous, cancellable grace window and an explicit confirmation — and you abort the whole thing instantly just by showing up (a login, a trade, or tapping "I'm here"). Crucially, no private key is ever exported or exposed: recovery and inheritance only change who owns the agent, and the same encrypted, server-held key keeps signing for the new owner. Every step is time-locked, reversible until commit, and written to your custody trail; the wallet is frozen against autonomous spending during any contested process so it can never be drained out from under you. Guardians act from a new Guardian console — the agents you're trusted to protect, where you approve a recovery or confirm an inheritance without ever touching anyone's funds. (`/guardian`) `[feature, security]`
- **Steadier 3D generation and token stats when free providers get busy** — Two backend reliability fixes. The free image step behind text→3D now shrugs off a brief blip from NVIDIA's gateway — if it answers with a fast, transient hiccup, we retry once before handing off, so fewer prompts have to fall through to a slower backup and fewer fail outright. (A real timeout still hands off immediately, so nothing waits twice.) Separately, live token stats lean on several market-data sources; when one hits its monthly quota we already pause it, but each fresh server instance used to re-discover that the hard way and waste another doomed call. That pause is now shared across the whole fleet, so the moment one instance sees a source is exhausted, none of the others retry it — quieter, faster, and no wasted quota. `[fix, infra]`
- **Strategy Objects: equip an ownable, forkable trade strategy on your agent** — A trading strategy is now a first-class thing you can own, share, and equip — not a buried setting. Build a rule-based plan (which fresh launches to buy, how big, take-profit, stop-loss, trailing stop, max hold, max concurrent positions, cooldown), then equip it on your agent and it trades the rules for real, on-chain, strictly inside that agent's spend policy and full custody audit trail. Every strategy carries an honest, on-chain track record: strategies with no closed trades show as Unproven rather than a made-up backtest curve, and the marketplace ranks published strategies by real live ROI. Fork any published strategy into your own library with credit to the author — forking copies only the rules, never any wallet access, and you run them under your own limits. A global kill switch halts every strategy you run at once, and equipped strategies surface right on each agent's profile next to copy-trading. Browse and manage everything at /strategies. (`/strategies`) `[feature]`
- **Strategy Objects: equip an ownable, forkable trading strategy on your agent** — A trading strategy is now a real thing you own — not a buried setting. A Strategy Object encodes a rule-based plan (snipe launches under N minutes old with the liquidity and market-cap you want, size each buy, take profit at 2×, stop out at −40%, cap concurrent positions, cool down between entries) as a named, versioned, ownable object. Equip it on your agent and it trades the rules for real, on-chain — every entry triggered by a real pump.fun launch, every exit by a real on-chain re-quote, and every order routed through the exact same spend-policy guardrails, rug/honeypot firewall, and custody audit trail as your manual trades. It can never exceed your leash: a strategy buy is gated by your per-trade cap, daily budget, and price-impact breaker, labeled strategy:<name> in the custody trail, and one global kill switch halts all your strategies at once. Publish your strategy to the new marketplace at /strategies, fork anyone else's into your library (you copy the rules with full credit to the author — never any wallet access; you run them under your own spend policy), and watch the leaderboard rank strategies by verified live ROI from real closed positions. Strategies with no closed trades are honestly labeled "Unproven" — there are no fabricated backtest curves. Manage equipped strategies, their live positions, and the kill switch right on your agent's profile, next to copy-trading. Owner-only to configure; find it at /strategies or on any agent's profile. (`/strategies`) `[feature]`
- **Talk to your agent and it trades — the Conversational Wallet** — Your avatar's wallet now takes voice and text commands. Tell your agent "tip 0.1 SOL to vault.sol", "snipe that mint with half a SOL", "sell half my $THREE", or "withdraw 2 SOL to my Phantom" — it parses your intent with Claude, shows you exactly what it will do next to your own words (real quote, USD value, fees, network), and waits for an explicit "yes" or a tap before anything moves. Confirmed trades come back with a real on-chain signature and explorer link, and the avatar celebrates the moment it lands. Every action runs the same owner-only, spend-limit-gated, audited path as the rest of the wallet — visitors can chat but can never move funds, by any phrasing. A wrong hearing is caught at the read-back, "cancel" is always one word away, and there's a full keyboard path with no mic required. `[feature]`
+- **Talk to your agent to trade — the Conversational Trading Copilot** — Your agent's wallet now has a Copilot tab where you trade by talking. Ask it things like "how's my portfolio?", "is this coin safe to buy?", or "buy 0.25 SOL of <mint>" — by text or voice — and it answers with real, live numbers: your balance and open positions, the rug/honeypot firewall verdict, smart-money count, price impact, and a fresh quote. It never invents figures, and it never trades on its own. When you ask to buy, sell, or change your risk limits, it hands you a confirm card showing the quote and safety verdict; only when you confirm does the trade run — through the exact same spend guards, firewall, kill switch, and on-chain custody audit as the manual Trade tab. Turn on the speaker to hear replies in your agent's own voice, and every executed trade is logged with a Solscan link. Owner-only. `[feature]`
- **Talk to your avatar — a new free speech-to-text lane closes the voice loop** — Your avatar could already speak for free; now it can listen for free too. A new /api/asr endpoint turns spoken audio into text using NVIDIA's hosted Riva recognition on the same free key that already powers avatar voices, 3D generation, and chat — so voice-in costs nothing extra. Until now, talking to an avatar relied on the browser's built-in recognizer, which only exists in Chrome and Edge and quietly sends your microphone to Google; the new lane is server-side and works the same everywhere. It's purely additive: when the lane isn't switched on, voice keeps working exactly as before — nothing changes for anyone. Send a short WAV, PCM, FLAC, or Ogg clip and get back the transcript, the language detected, and optional word-level timestamps, all metered fairly so it can't be abused. `[feature]`
- **Talk to your avatar out loud — in any browser** — Your avatar could already think and speak; now it can listen. Open Talk mode on any avatar, hold the mic button, and say what you want — your words appear live as you speak, and the avatar reasons and replies in its own voice, completing a hands-free conversation. Speech recognition now runs on NVIDIA Riva on our servers, so it works everywhere — including Firefox, where the old browser-only mic never did — and your audio goes to us, not a third party. Hold to talk with the button or the spacebar, watch the ring pulse with your voice, and read the transcript as it forms. If you'd rather not use a mic, or your browser blocks it, the text box is always right there — nothing is ever a dead end. `[feature]`
+- **The Arena — live PvP trading tournaments with $THREE prizes** — Trading is now a spectator sport. The new Arena hosts time-boxed PvP tournaments where AI agents go head-to-head on real, verified pump.fun P&L — and because every number is computed from the agents' own on-chain closed trades, the performance can't be faked. Create a competition with a window, a scoring rule (composite TraderScore, realized P&L, or ROI), and an optional $THREE prize pool; enter one of your agents and only the trades it opens inside the window count, so everyone starts fair. The live competition view ranks entrants in real time with the leader spotlighted as a 3D avatar, a verified badge, a recent-trades ticker, and rank-change animations, all over a live stream. Anti-cheat is built in: simulated/paper trades never earn prizes (there's a clearly-labelled practice bracket for them), the same min-trades / unique-coins / churn gates that power the verification badge decide prize eligibility, and high-churn single-coin patterns are flagged. When a tournament closes, its final standings are committed to Solana as a tamper-evident on-chain attestation linked from the results page, and $THREE prizes settle to the winners' wallets with a real transaction — honestly reported as blocked, never faked, if prize funding isn't configured. (`/arena`) `[feature]`
- **The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time** — The payment card that appears when you unlock a paid skill inside an embedded agent got a polish-and-correctness pass. It now glides in with a soft fade-and-scale instead of snapping open, dims the page behind it, and stays fully usable on small screens (it scrolls inside itself rather than overflowing). It's now properly keyboard-accessible: press Escape to close it, Tab stays trapped inside the card so focus can't slip behind it, the pay button is focused the moment it opens, and when you close it focus returns exactly where you were. While the dollar equivalent of the price loads it shows a gentle shimmer instead of jumping the layout, every button has a clear focus ring, and all of it respects reduced-motion. We also fixed a display bug where a larger dollar receipt could be shown a million times too small — the amount on every receipt is now always correct. (`/marketplace`) `[improvement, fix]`
- **The walking companion, page narrator, and 3D tour are smoother, kinder to your battery, and never start on a blank canvas** — The three avatars that walk and talk over a page got a polish pass focused on the moments before and around them. The corner companion now greets you with a soft loading shimmer instead of an empty box while its 3D body streams in, and the guided tour opens with an honest 'waking your guide' loader — a real readiness cue, never a fake bar — instead of a frozen page. All four 3D surfaces (the corner companion, the full-page walk playground, the drop-in page narrator, and the feature tour) now pause their animation the instant you switch to another tab, and the page narrator also pauses when it scrolls out of view — so a living avatar never quietly burns your laptop battery in a background tab. The narrator's mute button now shows the correct state from the very first frame, the tour's loader always clears cleanly when you exit, and several small resource leaks (timers and drag handlers left running after a companion or narrator was dismissed) are fixed. Reduced-motion preferences are honored throughout. (`/walk`) `[improvement, fix]`
- **three.ws opens cleanly inside in-app browsers** — Opening a three.ws link from inside the X (Twitter) app, and other in-app browsers that sandbox local storage, could throw an error before the page finished setting up its language — leaving some visitors on a broken first screen. Language preference now degrades gracefully when storage is blocked instead of failing, so the site loads normally everywhere. We also quieted a class of harmless background network blips (an expired draft model link, a dropped request) that were being logged as errors even though the viewer already shows its designed "couldn't load" card and recovers. `[fix]`
diff --git a/api/_lib/agent-mirror.js b/api/_lib/agent-mirror.js
index aad12f275..7f11dbe1b 100644
--- a/api/_lib/agent-mirror.js
+++ b/api/_lib/agent-mirror.js
@@ -133,6 +133,7 @@ export async function loadFollower(followerId) {
// pipeline — the gate is shared, never reimplemented.
export async function runFollowerTrade({
follower, side, mint, network, solAmount, tokenAmountRaw, slippageBps, idempotencyKey, leaderRef,
+ firewallLevel = 'block',
}) {
const { id, ownerId, meta, address, encryptedSecret } = follower;
if (!address || !encryptedSecret) return { status: 'failed', code: 'wallet_preparing' };
@@ -195,13 +196,17 @@ export async function runFollowerTrade({
quoteAmount: BigInt(quote.inAtomics), priceImpactPct: quote.priceImpactPct,
}).catch(() => null);
if (assessment) {
+ // Honour the caller's firewall level: 'block' refuses a block-verdict
+ // trade (the safe default every mirror uses); 'warn' records the verdict
+ // but lets the trade through. A down firewall degrades to allow, never stalls.
+ const enforced = firewallLevel === 'block' && assessment.verdict === 'block';
recordFirewallDecision({
mint, network, side: 'buy', verdict: assessment.verdict, score: assessment.score,
simulated: assessment.simulated, checks: assessment.checks, reasons: assessment.reasons,
source: 'mirror', agentId: id, userId: ownerId,
- quoteLamports: BigInt(quote.inAtomics), enforced: assessment.verdict === 'block',
+ quoteLamports: BigInt(quote.inAtomics), enforced,
}).catch(() => {});
- if (assessment.verdict === 'block') return { status: 'skipped', code: 'firewall_blocked' };
+ if (enforced) return { status: 'skipped', code: 'firewall_blocked' };
}
}
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 29da13ebd..fd597f12c 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -960,6 +960,16 @@ export const env = {
get THREE_REWARDS_WALLET() {
return opt('THREE_REWARDS_WALLET');
},
+ // Solana prize wallet for the Social Trading Arena (api/tournaments/*). Holds the
+ // $THREE used to pay tournament winners; the settlement module pays each winning
+ // entry a real on-chain SPL transfer from this wallet. Never logged, never
+ // returned. Accepts a Base58 64-byte secret (or base64); the settlement module
+ // also accepts the base64 CLUB_SOLANA_TREASURY_SECRET_KEY_B64 as a fallback. When
+ // unset, prizes settle as BLOCKED(payout_unconfigured) — the tournament still runs
+ // and ranks, it just can't pay until this is configured.
+ get THREE_PRIZE_PAYOUT_KEY() {
+ return opt('THREE_PRIZE_PAYOUT_KEY');
+ },
// Burn address — defaults to the Solana incinerator, whose associated token
// account is unspendable (no key exists), so tokens transferred there are
// permanently removed from circulation. Verifiable as a plain destination.
diff --git a/api/_lib/migrations/20260623120000_tournaments.sql b/api/_lib/migrations/20260623120000_tournaments.sql
new file mode 100644
index 000000000..eed692488
--- /dev/null
+++ b/api/_lib/migrations/20260623120000_tournaments.sql
@@ -0,0 +1,95 @@
+-- Migration: Social Trading Arena — time-boxed PvP trading tournaments.
+--
+-- The Arena turns the verified track-record layer (trader-stats.js over the
+-- on-chain agent_sniper_positions ledger) into a recurring competitive product:
+-- agents enter a time-boxed competition, are ranked LIVE on real, signature-proven
+-- realized PnL over the window, the final standings are committed to Solana as a
+-- tamper-evident attestation (kind threews.tournament.v1), and $THREE prizes settle
+-- to the winners' wallets.
+--
+-- Two tables, by design:
+-- tournaments — the competition definition + lifecycle + prize pool.
+-- tournament_entries — one row per (tournament, agent), with the join-time
+-- baseline snapshot and, after close, the final rank +
+-- prize + settlement record.
+--
+-- Integrity is the entire point: rankings derive ONLY from trades OPENED inside
+-- the window (snapshotted at join so nothing can be backfilled), prize brackets
+-- exclude simulated/paper positions, and every prize payout records a real tx.
+
+begin;
+
+create table if not exists tournaments (
+ id uuid primary key default gen_random_uuid(),
+ name text not null check (length(name) between 1 and 120),
+ description text,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ -- What the live rank is sorted on. All three derive from the same pure
+ -- computeTraderMetrics over the window, so they can never disagree with the
+ -- leaderboard or the trader profile.
+ scoring text not null default 'score' check (scoring in ('score','realized_pnl','roi_pct')),
+ -- 'prize' — real on-chain trades only; winners receive $THREE.
+ -- 'practice'— simulated/paper trades allowed, clearly labelled, no prizes.
+ bracket text not null default 'prize' check (bracket in ('prize','practice')),
+ starts_at timestamptz not null,
+ ends_at timestamptz not null,
+ -- Anti-cheat + access gates: { min_closed, min_unique_coins, max_churn_pct,
+ -- gated:boolean, allow_agents:[uuid] }. Defaults applied in the scoring engine.
+ entry_rules jsonb not null default '{}'::jsonb,
+ -- Prize pool in $THREE base units (atomics; THREE_TOKEN_DECIMALS). Practice
+ -- brackets keep this 0.
+ prize_pool_three numeric(40, 0) not null default 0,
+ -- Payout structure as basis points of the pool by rank: [{rank,bps}, …].
+ -- Must sum to <= 10000; the remainder (if any) stays unallocated.
+ prize_splits jsonb not null default '[]'::jsonb,
+ status text not null default 'upcoming'
+ check (status in ('draft','upcoming','live','closed','settled','cancelled')),
+ -- Set at close: the Solana tx signature of the standings attestation.
+ attestation_sig text,
+ attestation_kind text,
+ created_by uuid references users(id) on delete set null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint tournaments_window_ordered check (ends_at > starts_at),
+ constraint tournaments_prize_nonneg check (prize_pool_three >= 0)
+);
+
+create index if not exists tournaments_status_start_idx on tournaments (status, starts_at desc);
+create index if not exists tournaments_network_end_idx on tournaments (network, ends_at desc);
+
+create table if not exists tournament_entries (
+ id uuid primary key default gen_random_uuid(),
+ tournament_id uuid not null references tournaments(id) on delete cascade,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ -- The agent's Solana trading wallet at join time — the prize destination and
+ -- the attestation subject. Denormalized so a later wallet rotation can't redirect
+ -- a prize the entrant already earned.
+ wallet text,
+ joined_at timestamptz not null default now(),
+ -- All-time metrics snapshot at join (computeTraderMetrics) + closed_count, so
+ -- the window scoping is auditable and pre-window history can't be claimed.
+ starting_snapshot jsonb not null default '{}'::jsonb,
+ status text not null default 'active'
+ check (status in ('active','disqualified','withdrawn')),
+ dq_reason text,
+ -- Filled at close.
+ final_rank int,
+ final_score numeric,
+ prize_three numeric(40, 0) not null default 0,
+ settlement_status text not null default 'none'
+ check (settlement_status in ('none','pending','settled','blocked')),
+ settlement_tx text,
+ settlement_note text,
+ settled_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (tournament_id, agent_id)
+);
+
+create index if not exists tournament_entries_tid_idx on tournament_entries (tournament_id);
+create index if not exists tournament_entries_agent_idx on tournament_entries (agent_id);
+-- Idempotency guard for prize settlement: one tx can settle exactly one entry.
+create unique index if not exists tournament_entries_settlement_tx_uniq
+ on tournament_entries (settlement_tx) where settlement_tx is not null;
+
+commit;
diff --git a/api/_lib/migrations/20260623160000_programmable_orders.sql b/api/_lib/migrations/20260623160000_programmable_orders.sql
new file mode 100644
index 000000000..f638c385c
--- /dev/null
+++ b/api/_lib/migrations/20260623160000_programmable_orders.sql
@@ -0,0 +1,122 @@
+-- Programmable Orders Engine (trading-frontier/02).
+--
+-- A real, set-and-forget order layer for agent-wallet pump.fun trading: limit,
+-- stop, trailing stop, DCA, TWAP, and validated conditional triggers. A worker
+-- (workers/agent-orders) sweeps active orders, re-quotes each mint off live
+-- on-chain state, evaluates the trigger/schedule, and on fire executes through
+-- the SAME firewall + spend-guard + custody pipeline as every other agent trade
+-- (api/agents/agent-trade.js executeAgentTrade). `orders` is the rule; the
+-- `order_fills` rows are the per-execution audit trail (each linked to its
+-- agent_custody_events row, the canonical spend ledger).
+
+-- ── orders ──────────────────────────────────────────────────────────────────
+CREATE TABLE IF NOT EXISTS orders (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL,
+ user_id UUID NOT NULL,
+ network TEXT NOT NULL DEFAULT 'mainnet',
+ mint TEXT NOT NULL,
+ symbol TEXT,
+ type TEXT NOT NULL, -- limit|stop|trailing|dca|twap|conditional
+ side TEXT NOT NULL, -- buy|sell
+
+ -- sizing: buys spend SOL (size_sol); sells dispose tokens (size_tokens raw
+ -- base units) OR a fraction of the live holding (sell_pct, 0–100).
+ size_sol NUMERIC,
+ size_tokens NUMERIC,
+ sell_pct NUMERIC,
+
+ -- price triggers. The metric these values are expressed in is `trigger_metric`
+ -- (see CHECK). limit_price/stop_price are the target in that metric; trail_pct
+ -- is the drawdown/run-up percent for a trailing stop and peak_price its tracked
+ -- high/low-water mark (also in trigger_metric units).
+ trigger_metric TEXT NOT NULL DEFAULT 'mcap_usd', -- price_sol|mcap_sol|mcap_usd
+ limit_price NUMERIC,
+ stop_price NUMERIC,
+ trail_pct NUMERIC,
+ peak_price NUMERIC,
+ reference_price NUMERIC, -- metric value at creation (display + change conditions)
+
+ -- DCA / TWAP schedule. { interval_seconds, slices, filled_slices }
+ schedule JSONB,
+ next_fire_at TIMESTAMPTZ,
+
+ -- conditional trigger: a validated, code-free condition spec
+ -- { all|any: [ { signal, op, value } ] }
+ condition JSONB,
+
+ -- execution params
+ slippage_bps INTEGER NOT NULL DEFAULT 500,
+ max_price_impact_pct NUMERIC,
+ expires_at TIMESTAMPTZ,
+
+ -- lifecycle state
+ status TEXT NOT NULL DEFAULT 'active', -- active|partial|firing|paused|filled|cancelled|expired|error
+ filled_sol NUMERIC NOT NULL DEFAULT 0,
+ filled_tokens NUMERIC NOT NULL DEFAULT 0,
+ fill_count INTEGER NOT NULL DEFAULT 0,
+ last_eval_at TIMESTAMPTZ,
+ last_price NUMERIC, -- last observed metric value
+ last_error TEXT,
+
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ cancelled_at TIMESTAMPTZ,
+
+ CONSTRAINT orders_type_check CHECK (type IN ('limit','stop','trailing','dca','twap','conditional')),
+ CONSTRAINT orders_side_check CHECK (side IN ('buy','sell')),
+ CONSTRAINT orders_status_check CHECK (status IN ('active','partial','firing','paused','filled','cancelled','expired','error')),
+ CONSTRAINT orders_network_check CHECK (network IN ('mainnet','devnet')),
+ CONSTRAINT orders_metric_check CHECK (trigger_metric IN ('price_sol','mcap_sol','mcap_usd')),
+ CONSTRAINT orders_slippage_check CHECK (slippage_bps BETWEEN 1 AND 5000)
+);
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE tablename = 'orders' AND indexname = 'idx_orders_agent') THEN
+ CREATE INDEX idx_orders_agent ON orders(agent_id, network, created_at DESC);
+ END IF;
+END $$;
+
+-- The worker's hot work-set: orders still in play, ordered for scheduling.
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE tablename = 'orders' AND indexname = 'idx_orders_active') THEN
+ CREATE INDEX idx_orders_active ON orders(network, next_fire_at)
+ WHERE status IN ('active','partial','firing');
+ END IF;
+END $$;
+
+-- ── order_fills ─────────────────────────────────────────────────────────────
+CREATE TABLE IF NOT EXISTS order_fills (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ order_id UUID NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
+ agent_id UUID NOT NULL,
+ network TEXT NOT NULL,
+ slice_index INTEGER, -- DCA/TWAP slice number (0-based)
+ side TEXT NOT NULL,
+ trigger_reason TEXT, -- 'limit', 'trailing_stop', 'condition', 'dca_slice', …
+ trigger_price NUMERIC, -- metric value that fired the order
+ sol_amount NUMERIC, -- SOL spent (buy) / SOL received (sell)
+ token_amount NUMERIC, -- base units bought/sold
+ price_impact_pct NUMERIC,
+ venue TEXT, -- bonding_curve|amm
+ signature TEXT,
+ custody_event_id BIGINT, -- FK-ish into agent_custody_events.id
+ status TEXT NOT NULL DEFAULT 'pending', -- pending|confirmed|failed|simulated|unconfirmed
+ detail TEXT,
+ meta JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT order_fills_status_check CHECK (status IN ('pending','confirmed','failed','simulated','unconfirmed'))
+);
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE tablename = 'order_fills' AND indexname = 'idx_order_fills_order') THEN
+ CREATE INDEX idx_order_fills_order ON order_fills(order_id, created_at DESC);
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE tablename = 'order_fills' AND indexname = 'idx_order_fills_agent') THEN
+ CREATE INDEX idx_order_fills_agent ON order_fills(agent_id, created_at DESC);
+ END IF;
+END $$;
diff --git a/api/_lib/migrations/20260626000000_trading_swarms.sql b/api/_lib/migrations/20260626000000_trading_swarms.sql
new file mode 100644
index 000000000..01eb8d2e3
--- /dev/null
+++ b/api/_lib/migrations/20260626000000_trading_swarms.sql
@@ -0,0 +1,121 @@
+-- Agent Trading Swarms — pooled custodial treasury + weighted-consensus trading +
+-- pro-rata payouts. A swarm is itself an agent-owned custodial wallet (the
+-- treasury), provisioned through the normal agent-wallet path, with a dedicated
+-- agent_sniper_strategies row that carries its trade policy (budget, per-trade
+-- cap, stop-loss/take-profit) so the existing position sweep manages and exits
+-- its positions for free. The consensus engine fires buys from the treasury only
+-- when reputation-weighted member agreement clears the swarm's threshold;
+-- realized profit distributes pro-rata to members via real on-chain SOL transfers.
+--
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260626000000_trading_swarms.sql
+-- Idempotent.
+
+BEGIN;
+
+CREATE TABLE IF NOT EXISTS swarms (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ owner_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ owner_agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ -- The custodial treasury agent (its own provisioned Solana wallet). Trades and
+ -- payouts move real SOL through this wallet; the ledger ties to its on-chain balance.
+ treasury_agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ -- The treasury's sniper strategy row (carries budget/per-trade/exit policy).
+ strategy_id uuid REFERENCES agent_sniper_strategies(id) ON DELETE SET NULL,
+ name text NOT NULL CHECK (LENGTH(name) > 0 AND LENGTH(name) <= 80),
+ description text,
+ network text NOT NULL DEFAULT 'mainnet' CHECK (network IN ('mainnet','devnet')),
+ status text NOT NULL DEFAULT 'open'
+ CHECK (status IN ('open','active','paused','killed','closed')),
+ -- policy jsonb: { min_consensus(0..1), max_per_trade_lamports, daily_budget_lamports,
+ -- creator_fee_bps(0..2000), max_member_share_bps(0..10000), require_smart_money(bool),
+ -- min_smart_money_score(0..100), stop_loss_pct, take_profit_pct, trailing_stop_pct,
+ -- max_hold_seconds, slippage_bps, firewall_level, join_open(bool),
+ -- kill_threshold_bps(0..10000), exit_policy('settle_at_mark'|'wait_to_close') }
+ policy jsonb NOT NULL DEFAULT '{}'::jsonb,
+ killed_at timestamptz,
+ killed_by_user_id uuid REFERENCES users(id) ON DELETE SET NULL,
+ kill_reason text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS swarms_status ON swarms(status, network) WHERE status IN ('open','active','paused');
+CREATE INDEX IF NOT EXISTS swarms_owner ON swarms(owner_user_id);
+CREATE UNIQUE INDEX IF NOT EXISTS swarms_treasury_unique ON swarms(treasury_agent_id);
+
+CREATE TABLE IF NOT EXISTS swarm_members (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ swarm_id uuid NOT NULL REFERENCES swarms(id) ON DELETE CASCADE,
+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ -- Net SOL the member has funded into the treasury (lamports), and what they have
+ -- already redeemed back out on exit/partial withdraw. Net contribution =
+ -- contribution_lamports - withdrawn_lamports drives share_bps.
+ contribution_lamports numeric(40,0) NOT NULL DEFAULT 0,
+ withdrawn_lamports numeric(40,0) NOT NULL DEFAULT 0,
+ -- Recomputed share of the treasury in basis points (0..10000) from net contributions.
+ share_bps int NOT NULL DEFAULT 0 CHECK (share_bps >= 0 AND share_bps <= 10000),
+ -- Cached verified trader reputation (0..100) — the consensus vote weight.
+ reputation real,
+ reputation_at timestamptz,
+ status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','exited')),
+ is_creator boolean NOT NULL DEFAULT false,
+ last_fund_sig text,
+ joined_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ exited_at timestamptz,
+ UNIQUE (swarm_id, agent_id)
+);
+CREATE INDEX IF NOT EXISTS swarm_members_swarm ON swarm_members(swarm_id) WHERE status = 'active';
+CREATE INDEX IF NOT EXISTS swarm_members_agent ON swarm_members(agent_id);
+CREATE INDEX IF NOT EXISTS swarm_members_user ON swarm_members(user_id);
+
+-- Every consensus decision (fire or skip) with the full reputation-weighted vote
+-- breakdown — the auditable record of why the treasury did or did not trade.
+CREATE TABLE IF NOT EXISTS swarm_votes (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ swarm_id uuid NOT NULL REFERENCES swarms(id) ON DELETE CASCADE,
+ mint text NOT NULL,
+ network text NOT NULL DEFAULT 'mainnet',
+ decision text NOT NULL CHECK (decision IN ('fire','skip')),
+ consensus real, -- weighted agreement 0..1
+ min_consensus real,
+ conviction real, -- combined edge that sized the trade
+ size_lamports numeric(40,0),
+ members_long int,
+ members_total int,
+ smart_money_score real,
+ breakdown jsonb NOT NULL DEFAULT '[]'::jsonb, -- [{agent_id,name,reputation,long,weight}]
+ position_id uuid, -- agent_sniper_positions.id when fired
+ reason text,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS swarm_votes_swarm ON swarm_votes(swarm_id, created_at DESC);
+CREATE INDEX IF NOT EXISTS swarm_votes_fired ON swarm_votes(swarm_id, position_id) WHERE decision = 'fire';
+
+-- Pro-rata distributions and exit redemptions — one row per member per event, each
+-- backed by a real on-chain SOL transfer. Idempotent via idempotency_key so a
+-- retried settlement never double-pays.
+CREATE TABLE IF NOT EXISTS swarm_payouts (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ swarm_id uuid NOT NULL REFERENCES swarms(id) ON DELETE CASCADE,
+ member_id uuid REFERENCES swarm_members(id) ON DELETE SET NULL,
+ agent_id uuid, -- recipient member agent (denormalized)
+ position_id uuid, -- the closed position that realized the profit (null for exit)
+ kind text NOT NULL CHECK (kind IN ('profit','exit','fee')),
+ amount_lamports numeric(40,0) NOT NULL CHECK (amount_lamports >= 0),
+ share_bps int,
+ destination text, -- recipient Solana address
+ signature text, -- on-chain tx signature
+ status text NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending','confirmed','failed')),
+ idempotency_key text NOT NULL,
+ meta jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (idempotency_key)
+);
+CREATE INDEX IF NOT EXISTS swarm_payouts_swarm ON swarm_payouts(swarm_id, created_at DESC);
+CREATE INDEX IF NOT EXISTS swarm_payouts_member ON swarm_payouts(member_id);
+CREATE INDEX IF NOT EXISTS swarm_payouts_position ON swarm_payouts(position_id) WHERE kind = 'profit';
+
+COMMIT;
diff --git a/api/_lib/orders.js b/api/_lib/orders.js
new file mode 100644
index 000000000..4b292c354
--- /dev/null
+++ b/api/_lib/orders.js
@@ -0,0 +1,576 @@
+/**
+ * Programmable Orders Engine — data model, validated condition language, and the
+ * owner-facing CRUD layer (trading-frontier/02).
+ *
+ * This module is the single source of truth for what a valid order IS. The HTTP
+ * endpoint (api/agents/orders.js) and the evaluation worker (workers/agent-orders)
+ * both import from here so the rules can never drift between "what you can create"
+ * and "what fires". Trigger + condition evaluation are exported as PURE functions
+ * (no I/O) so they are unit-testable and identical on both sides.
+ *
+ * Order types:
+ * limit — fill at a target price/market-cap (buy on a dip, sell on a rise)
+ * stop — fill when a level is breached (stop-loss sell / breakout buy)
+ * trailing — fill on a % drawdown from the high-water mark (or run-up from the low)
+ * dca — recurring buys/sells on a fixed interval, N slices
+ * twap — slice ONE large order over time to cut price impact, N slices
+ * conditional — fill when a validated signal condition is true
+ *
+ * No arbitrary code in conditions — only a closed set of real signals + operators.
+ */
+
+import { validateSolanaAddress } from './agent-trade-guards.js';
+import { sql } from './db.js';
+
+export const ORDER_TYPES = Object.freeze(['limit', 'stop', 'trailing', 'dca', 'twap', 'conditional']);
+export const ORDER_SIDES = Object.freeze(['buy', 'sell']);
+export const TRIGGER_METRICS = Object.freeze(['price_sol', 'mcap_sol', 'mcap_usd']);
+
+// The closed set of live signals a conditional trigger may reference. Each maps to
+// a real, on-chain-or-derived value the worker computes per sweep (see
+// workers/agent-orders/market.js). `kind` gates which operators are legal.
+export const CONDITION_SIGNALS = Object.freeze({
+ price_sol: { kind: 'number', label: 'Price (SOL/token)' },
+ mcap_sol: { kind: 'number', label: 'Market cap (SOL)' },
+ mcap_usd: { kind: 'number', label: 'Market cap (USD)' },
+ price_change_pct: { kind: 'number', label: 'Price change since created (%)' },
+ smart_money_score: { kind: 'number', label: 'Smart-money score (0–100)' },
+ dev_dump: { kind: 'bool', label: 'Dev has dumped' },
+ graduated: { kind: 'bool', label: 'Graduated to AMM' },
+});
+
+export const NUMBER_OPS = Object.freeze(['gt', 'gte', 'lt', 'lte', 'eq', 'ne']);
+export const BOOL_OPS = Object.freeze(['is_true', 'is_false']);
+
+const OP_LABEL = {
+ gt: '>', gte: '≥', lt: '<', lte: '≤', eq: '=', ne: '≠', is_true: 'is', is_false: 'is not',
+};
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+function err(code, message) {
+ return { ok: false, error: code, message };
+}
+
+function num(v) {
+ if (v === null || v === undefined || v === '') return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+function posNum(v) {
+ const n = num(v);
+ return n != null && n > 0 ? n : null;
+}
+
+// ── condition language ────────────────────────────────────────────────────────
+
+/**
+ * Validate a condition spec. Shape: `{ all: [leaf, …] }` or `{ any: [leaf, …] }`,
+ * where each leaf is `{ signal, op, value }`. One level deep — no nested groups,
+ * no expressions, no code. Returns { ok, spec } or { ok:false, error, message }.
+ */
+export function validateCondition(raw) {
+ if (!raw || typeof raw !== 'object') return err('invalid_condition', 'a condition object is required');
+ const mode = 'all' in raw ? 'all' : 'any' in raw ? 'any' : null;
+ if (!mode) return err('invalid_condition', 'condition must have an "all" or "any" array');
+ const leaves = raw[mode];
+ if (!Array.isArray(leaves) || leaves.length === 0) return err('invalid_condition', `"${mode}" must be a non-empty array`);
+ if (leaves.length > 8) return err('invalid_condition', 'a condition may have at most 8 clauses');
+
+ const clean = [];
+ for (const leaf of leaves) {
+ if (!leaf || typeof leaf !== 'object') return err('invalid_condition', 'each clause must be an object');
+ const signal = String(leaf.signal || '');
+ const def = CONDITION_SIGNALS[signal];
+ if (!def) return err('invalid_condition', `unknown signal "${signal}"`);
+ const op = String(leaf.op || '');
+ if (def.kind === 'bool') {
+ if (!BOOL_OPS.includes(op)) return err('invalid_condition', `"${signal}" needs is_true or is_false`);
+ clean.push({ signal, op });
+ } else {
+ if (!NUMBER_OPS.includes(op)) return err('invalid_condition', `"${signal}" needs one of ${NUMBER_OPS.join(', ')}`);
+ const value = num(leaf.value);
+ if (value == null) return err('invalid_condition', `"${signal}" ${op} needs a numeric value`);
+ clean.push({ signal, op, value });
+ }
+ }
+ return { ok: true, spec: { [mode]: clean } };
+}
+
+function compareNumber(op, a, b) {
+ switch (op) {
+ case 'gt': return a > b;
+ case 'gte': return a >= b;
+ case 'lt': return a < b;
+ case 'lte': return a <= b;
+ case 'eq': return a === b;
+ case 'ne': return a !== b;
+ default: return false;
+ }
+}
+
+/**
+ * Evaluate a (pre-validated) condition spec against a `signals` map of live
+ * values. A signal that is null/undefined is treated as INDETERMINATE: it never
+ * counts as satisfied and is reported in `missing` so the worker can stay honest
+ * about data gaps (it must not fire on absent data). Pure — no I/O.
+ *
+ * @returns {{ fired: boolean, missing: string[] }}
+ */
+export function evaluateCondition(spec, signals) {
+ const mode = 'all' in spec ? 'all' : 'any';
+ const leaves = spec[mode];
+ const missing = [];
+ const results = leaves.map((leaf) => {
+ const def = CONDITION_SIGNALS[leaf.signal];
+ const v = signals?.[leaf.signal];
+ if (v == null) { missing.push(leaf.signal); return false; }
+ if (def.kind === 'bool') return leaf.op === 'is_true' ? v === true : v === false;
+ const n = Number(v);
+ if (!Number.isFinite(n)) { missing.push(leaf.signal); return false; }
+ return compareNumber(leaf.op, n, leaf.value);
+ });
+ const fired = mode === 'all' ? results.every(Boolean) : results.some(Boolean);
+ return { fired, missing };
+}
+
+/** Signals a condition spec references — so the worker only fetches what it needs. */
+export function conditionSignals(spec) {
+ const mode = 'all' in spec ? 'all' : 'any';
+ return [...new Set((spec[mode] || []).map((l) => l.signal))];
+}
+
+// ── price-trigger logic (limit / stop / trailing) ─────────────────────────────
+
+/**
+ * Decide whether a price-driven order fires at the observed metric value, given
+ * its tracked peak (for trailing). Pure. Returns true when the order should fire.
+ *
+ * - limit buy : fire when value <= target (patient entry on a dip)
+ * - limit sell: fire when value >= target (take profit on a rise)
+ * - stop buy : fire when value >= target (breakout entry)
+ * - stop sell: fire when value <= target (stop-loss)
+ * - trailing buy : fire when value >= trough * (1 + trail_pct/100)
+ * - trailing sell: fire when value <= peak * (1 - trail_pct/100)
+ */
+export function shouldFirePrice(order, value, peak) {
+ if (!Number.isFinite(value)) return false;
+ if (order.type === 'limit') {
+ const t = Number(order.limit_price);
+ return order.side === 'buy' ? value <= t : value >= t;
+ }
+ if (order.type === 'stop') {
+ const t = Number(order.stop_price);
+ return order.side === 'buy' ? value >= t : value <= t;
+ }
+ if (order.type === 'trailing') {
+ const p = Number(peak);
+ if (!Number.isFinite(p) || p <= 0) return false;
+ const tp = Number(order.trail_pct) / 100;
+ return order.side === 'sell' ? value <= p * (1 - tp) : value >= p * (1 + tp);
+ }
+ return false;
+}
+
+// ── order normalization / validation ──────────────────────────────────────────
+
+function parseSizing(raw, side) {
+ // Buys spend SOL; sells dispose tokens (raw base units) or a % of the holding.
+ if (side === 'buy') {
+ const size_sol = posNum(raw.size_sol);
+ if (!size_sol) return err('invalid_size', 'a positive size_sol (SOL to spend per fill) is required for a buy');
+ return { ok: true, sizing: { size_sol, size_tokens: null, sell_pct: null } };
+ }
+ const sell_pct = num(raw.sell_pct);
+ const size_tokens = posNum(raw.size_tokens);
+ if (sell_pct != null) {
+ if (sell_pct <= 0 || sell_pct > 100) return err('invalid_size', 'sell_pct must be between 0 and 100');
+ return { ok: true, sizing: { size_sol: null, size_tokens: null, sell_pct } };
+ }
+ if (size_tokens) return { ok: true, sizing: { size_sol: null, size_tokens, sell_pct: null } };
+ return err('invalid_size', 'a sell needs size_tokens (base units) or sell_pct (0–100)');
+}
+
+function parseSchedule(raw, { minInterval, minSlices }) {
+ const s = raw && typeof raw === 'object' ? raw : {};
+ const interval_seconds = Math.round(num(s.interval_seconds) ?? 0);
+ const slices = Math.round(num(s.slices) ?? 0);
+ if (!(interval_seconds >= minInterval)) return err('invalid_schedule', `interval_seconds must be at least ${minInterval}`);
+ if (!(slices >= minSlices)) return err('invalid_schedule', `slices must be at least ${minSlices}`);
+ if (slices > 1000) return err('invalid_schedule', 'slices may be at most 1000');
+ return { ok: true, schedule: { interval_seconds, slices, filled_slices: 0 } };
+}
+
+function parseExpiry(raw) {
+ if (raw == null || raw === '') return null;
+ const d = new Date(raw);
+ if (Number.isNaN(d.getTime())) return undefined; // signals invalid
+ return d.toISOString();
+}
+
+/**
+ * Coerce + validate a raw order body into a clean, bounded order spec ready to
+ * persist. Returns { ok, order } or { ok:false, error, message }. Does NOT touch
+ * the DB or the chain — it only decides validity + shape.
+ */
+export function normalizeOrder(raw) {
+ if (!raw || typeof raw !== 'object') return err('invalid_order', 'an order object is required');
+
+ const type = String(raw.type || '');
+ if (!ORDER_TYPES.includes(type)) return err('invalid_type', `type must be one of ${ORDER_TYPES.join(', ')}`);
+ const side = String(raw.side || '');
+ if (!ORDER_SIDES.includes(side)) return err('invalid_side', 'side must be "buy" or "sell"');
+
+ const mintCheck = validateSolanaAddress(raw.mint);
+ if (!mintCheck.valid) return err('invalid_mint', `mint is not a valid Solana address (${mintCheck.reason})`);
+
+ const slippage_bps = Math.max(1, Math.min(5000, Math.round(num(raw.slippage_bps) ?? 500)));
+ const max_price_impact_pct = (() => { const n = num(raw.max_price_impact_pct); return n != null && n > 0 ? Math.min(100, n) : null; })();
+
+ const expires_at = parseExpiry(raw.expires_at);
+ if (expires_at === undefined) return err('invalid_expiry', 'expires_at must be a valid date/time');
+
+ const trigger_metric = TRIGGER_METRICS.includes(raw.trigger_metric) ? raw.trigger_metric : 'mcap_usd';
+
+ const out = {
+ type, side, mint: mintCheck.base58, symbol: typeof raw.symbol === 'string' ? raw.symbol.slice(0, 32) : null,
+ network: raw.network === 'devnet' ? 'devnet' : 'mainnet',
+ slippage_bps, max_price_impact_pct, expires_at: expires_at || null,
+ trigger_metric,
+ limit_price: null, stop_price: null, trail_pct: null,
+ schedule: null, condition: null,
+ size_sol: null, size_tokens: null, sell_pct: null,
+ };
+
+ // sizing (shared by all single-fill types and per-slice for dca; twap derives below)
+ if (type !== 'twap') {
+ const sz = parseSizing(raw, side);
+ if (!sz.ok) return sz;
+ Object.assign(out, sz.sizing);
+ }
+
+ if (type === 'limit') {
+ const v = posNum(raw.limit_price);
+ if (!v) return err('invalid_price', 'limit_price must be a positive number');
+ out.limit_price = v;
+ } else if (type === 'stop') {
+ const v = posNum(raw.stop_price);
+ if (!v) return err('invalid_price', 'stop_price must be a positive number');
+ out.stop_price = v;
+ } else if (type === 'trailing') {
+ const v = num(raw.trail_pct);
+ if (v == null || v <= 0 || v >= 100) return err('invalid_trail', 'trail_pct must be between 0 and 100');
+ out.trail_pct = v;
+ } else if (type === 'dca') {
+ const sch = parseSchedule(raw.schedule, { minInterval: 60, minSlices: 1 });
+ if (!sch.ok) return sch;
+ out.schedule = sch.schedule;
+ } else if (type === 'twap') {
+ const sch = parseSchedule(raw.schedule, { minInterval: 30, minSlices: 2 });
+ if (!sch.ok) return sch;
+ out.schedule = sch.schedule;
+ // TWAP slices ONE total order; derive per-slice size from the total.
+ if (side === 'buy') {
+ const total = posNum(raw.total_sol ?? raw.size_sol);
+ if (!total) return err('invalid_size', 'a positive total_sol is required for a TWAP buy');
+ out.size_sol = round8(total / sch.schedule.slices);
+ out.schedule.total_sol = total;
+ } else {
+ const pct = num(raw.sell_pct);
+ const totalTokens = posNum(raw.total_tokens ?? raw.size_tokens);
+ if (pct != null) {
+ if (pct <= 0 || pct > 100) return err('invalid_size', 'sell_pct must be between 0 and 100');
+ out.sell_pct = round8(pct / sch.schedule.slices);
+ out.schedule.total_pct = pct;
+ } else if (totalTokens) {
+ out.size_tokens = round8(totalTokens / sch.schedule.slices);
+ out.schedule.total_tokens = totalTokens;
+ } else {
+ return err('invalid_size', 'a TWAP sell needs total_tokens (base units) or sell_pct (0–100)');
+ }
+ }
+ } else if (type === 'conditional') {
+ const cond = validateCondition(raw.condition);
+ if (!cond.ok) return cond;
+ out.condition = cond.spec;
+ }
+
+ return { ok: true, order: out };
+}
+
+function round8(n) {
+ return Math.round(n * 1e8) / 1e8;
+}
+
+// ── human-readable description ────────────────────────────────────────────────
+
+function metricLabel(metric, value) {
+ if (value == null) return '—';
+ if (metric === 'mcap_usd') return `$${fmt(value)} mcap`;
+ if (metric === 'mcap_sol') return `${fmt(value)} SOL mcap`;
+ return `${value} SOL/token`;
+}
+
+function fmt(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return String(n);
+ if (v >= 1000) return v.toLocaleString('en-US', { maximumFractionDigits: 0 });
+ if (v >= 1) return v.toLocaleString('en-US', { maximumFractionDigits: 2 });
+ return String(v);
+}
+
+function sizeLabel(o) {
+ if (o.side === 'buy') return `${o.size_sol} SOL`;
+ if (o.sell_pct != null) return `${o.sell_pct}% of the holding`;
+ return `${o.size_tokens} tokens`;
+}
+
+/** A plain-language readback of an order — what it does, in one line. */
+export function describeOrder(o) {
+ const sym = o.symbol ? `$${o.symbol}` : `${String(o.mint).slice(0, 4)}…`;
+ const verb = o.side === 'buy' ? 'Buy' : 'Sell';
+ switch (o.type) {
+ case 'limit':
+ return `${verb} ${sizeLabel(o)} of ${sym} when it reaches ${metricLabel(o.trigger_metric, o.limit_price)} (limit ${o.side}).`;
+ case 'stop':
+ return o.side === 'sell'
+ ? `Stop-loss: sell ${sizeLabel(o)} of ${sym} if it falls to ${metricLabel(o.trigger_metric, o.stop_price)}.`
+ : `Breakout: buy ${sizeLabel(o)} of ${sym} once it breaks ${metricLabel(o.trigger_metric, o.stop_price)}.`;
+ case 'trailing':
+ return o.side === 'sell'
+ ? `Trailing stop: sell ${sizeLabel(o)} of ${sym} after a ${o.trail_pct}% drop from its high.`
+ : `Trailing entry: buy ${sizeLabel(o)} of ${sym} after a ${o.trail_pct}% bounce from its low.`;
+ case 'dca': {
+ const every = humanInterval(o.schedule?.interval_seconds);
+ return `DCA: ${verb.toLowerCase()} ${sizeLabel(o)} of ${sym} every ${every}, ${o.schedule?.slices}× total.`;
+ }
+ case 'twap': {
+ const every = humanInterval(o.schedule?.interval_seconds);
+ const total = o.side === 'buy' ? `${o.schedule?.total_sol} SOL` : (o.schedule?.total_pct != null ? `${o.schedule.total_pct}%` : `${o.schedule?.total_tokens} tokens`);
+ return `TWAP: ${verb.toLowerCase()} ${total} of ${sym} sliced over ${o.schedule?.slices} fills, one every ${every}.`;
+ }
+ case 'conditional':
+ return `${verb} ${sizeLabel(o)} of ${sym} when ${describeCondition(o.condition)}.`;
+ default:
+ return `${verb} ${sym}.`;
+ }
+}
+
+export function describeCondition(spec) {
+ if (!spec) return 'a condition is met';
+ const mode = 'all' in spec ? 'all' : 'any';
+ const join = mode === 'all' ? ' and ' : ' or ';
+ return (spec[mode] || []).map((l) => {
+ const def = CONDITION_SIGNALS[l.signal];
+ if (def?.kind === 'bool') return `${def.label.toLowerCase()} ${l.op === 'is_true' ? 'is true' : 'is false'}`;
+ return `${def?.label || l.signal} ${OP_LABEL[l.op] || l.op} ${fmt(l.value)}`;
+ }).join(join);
+}
+
+function humanInterval(seconds) {
+ const s = Number(seconds) || 0;
+ if (s % 86400 === 0 && s >= 86400) return `${s / 86400} day${s === 86400 ? '' : 's'}`;
+ if (s % 3600 === 0 && s >= 3600) return `${s / 3600} hour${s === 3600 ? '' : 's'}`;
+ if (s % 60 === 0 && s >= 60) return `${s / 60} min`;
+ return `${s}s`;
+}
+
+// ── persistence (CRUD) ────────────────────────────────────────────────────────
+
+/** Shape a DB row for the API: numeric strings → numbers, attach a readback. */
+export function shapeOrder(row) {
+ if (!row) return null;
+ const o = {
+ id: row.id, agent_id: row.agent_id, network: row.network, mint: row.mint, symbol: row.symbol,
+ type: row.type, side: row.side,
+ size_sol: numOrNull(row.size_sol), size_tokens: numOrNull(row.size_tokens), sell_pct: numOrNull(row.sell_pct),
+ trigger_metric: row.trigger_metric,
+ limit_price: numOrNull(row.limit_price), stop_price: numOrNull(row.stop_price),
+ trail_pct: numOrNull(row.trail_pct), peak_price: numOrNull(row.peak_price),
+ reference_price: numOrNull(row.reference_price),
+ schedule: row.schedule || null, next_fire_at: row.next_fire_at, condition: row.condition || null,
+ slippage_bps: row.slippage_bps, max_price_impact_pct: numOrNull(row.max_price_impact_pct),
+ expires_at: row.expires_at, status: row.status,
+ filled_sol: numOrNull(row.filled_sol) || 0, filled_tokens: numOrNull(row.filled_tokens) || 0,
+ fill_count: row.fill_count || 0,
+ last_eval_at: row.last_eval_at, last_price: numOrNull(row.last_price), last_error: row.last_error,
+ created_at: row.created_at, updated_at: row.updated_at, cancelled_at: row.cancelled_at,
+ };
+ o.readback = describeOrder(o);
+ return o;
+}
+
+function numOrNull(v) {
+ if (v == null) return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+/** List an agent's orders (newest first), optionally filtered by status set. */
+export async function listOrders(agentId, { network = null, statuses = null, limit = 100 } = {}) {
+ const lim = Math.min(200, Math.max(1, Number(limit) || 100));
+ const rows = await sql`
+ SELECT * FROM orders
+ WHERE agent_id = ${agentId}
+ AND (${network}::text IS NULL OR network = ${network})
+ AND (${statuses}::text[] IS NULL OR status = ANY(${statuses}::text[]))
+ ORDER BY created_at DESC
+ LIMIT ${lim}
+ `;
+ return rows.map(shapeOrder);
+}
+
+/** A single order (owner-scoped). */
+export async function getOrder(agentId, orderId) {
+ if (!UUID_RE.test(orderId)) return null;
+ const [row] = await sql`SELECT * FROM orders WHERE id = ${orderId} AND agent_id = ${agentId}`;
+ return shapeOrder(row);
+}
+
+/** Recent fills for an order. */
+export async function listFills(orderId, { limit = 50 } = {}) {
+ const lim = Math.min(200, Math.max(1, Number(limit) || 50));
+ const rows = await sql`
+ SELECT id, slice_index, side, trigger_reason, trigger_price, sol_amount, token_amount,
+ price_impact_pct, venue, signature, custody_event_id, status, detail, created_at
+ FROM order_fills WHERE order_id = ${orderId}
+ ORDER BY created_at DESC LIMIT ${lim}
+ `;
+ return rows.map((r) => ({
+ ...r,
+ trigger_price: numOrNull(r.trigger_price),
+ sol_amount: numOrNull(r.sol_amount),
+ token_amount: numOrNull(r.token_amount),
+ price_impact_pct: numOrNull(r.price_impact_pct),
+ }));
+}
+
+/**
+ * Persist a validated order. `normalized` is the output of normalizeOrder.order.
+ * Schedule-driven orders (dca/twap) get next_fire_at = now so the first slice
+ * fires on the next sweep. Returns the shaped row.
+ */
+export async function createOrder(agentId, userId, normalized) {
+ const o = normalized;
+ const scheduled = o.type === 'dca' || o.type === 'twap';
+ const [row] = await sql`
+ INSERT INTO orders
+ (agent_id, user_id, network, mint, symbol, type, side, size_sol, size_tokens,
+ sell_pct, trigger_metric, limit_price, stop_price, trail_pct, schedule,
+ next_fire_at, condition, slippage_bps, max_price_impact_pct, expires_at, status)
+ VALUES (
+ ${agentId}, ${userId}, ${o.network}, ${o.mint}, ${o.symbol}, ${o.type}, ${o.side},
+ ${o.size_sol}, ${o.size_tokens}, ${o.sell_pct}, ${o.trigger_metric},
+ ${o.limit_price}, ${o.stop_price}, ${o.trail_pct},
+ ${o.schedule ? JSON.stringify(o.schedule) : null}::jsonb,
+ ${scheduled ? sql`now()` : null},
+ ${o.condition ? JSON.stringify(o.condition) : null}::jsonb,
+ ${o.slippage_bps}, ${o.max_price_impact_pct}, ${o.expires_at}, 'active')
+ RETURNING *
+ `;
+ return shapeOrder(row);
+}
+
+/**
+ * Owner edit: pause/resume (status active↔paused via cancel is separate), or
+ * patch trigger params on an order that hasn't filled. Only a bounded set of
+ * fields can change; type/side/mint are immutable (delete + recreate instead).
+ */
+export async function updateOrder(agentId, orderId, patch) {
+ const current = await getOrder(agentId, orderId);
+ if (!current) return null;
+ if (['filled', 'cancelled', 'expired'].includes(current.status)) {
+ return { error: 'immutable', message: `a ${current.status} order can’t be edited` };
+ }
+
+ const sets = [];
+ if ('limit_price' in patch && current.type === 'limit') {
+ const v = posNum(patch.limit_price);
+ if (!v) return { error: 'invalid_price', message: 'limit_price must be positive' };
+ sets.push(sql`limit_price = ${v}`);
+ }
+ if ('stop_price' in patch && current.type === 'stop') {
+ const v = posNum(patch.stop_price);
+ if (!v) return { error: 'invalid_price', message: 'stop_price must be positive' };
+ sets.push(sql`stop_price = ${v}`);
+ }
+ if ('trail_pct' in patch && current.type === 'trailing') {
+ const v = num(patch.trail_pct);
+ if (v == null || v <= 0 || v >= 100) return { error: 'invalid_trail', message: 'trail_pct must be 0–100' };
+ sets.push(sql`trail_pct = ${v}`);
+ }
+ if ('slippage_bps' in patch) {
+ sets.push(sql`slippage_bps = ${Math.max(1, Math.min(5000, Math.round(num(patch.slippage_bps) ?? current.slippage_bps)))}`);
+ }
+ if ('expires_at' in patch) {
+ const e = parseExpiry(patch.expires_at);
+ if (e === undefined) return { error: 'invalid_expiry', message: 'expires_at must be a valid date/time' };
+ sets.push(sql`expires_at = ${e}`);
+ }
+ if ('paused' in patch) {
+ // Pause parks the order in a non-evaluated 'paused' state without losing fill
+ // progress; resume returns it to 'partial' (if it has fills) or 'active'.
+ if (patch.paused === true) {
+ sets.push(sql`status = 'paused'`);
+ } else {
+ sets.push(sql`status = ${current.fill_count > 0 ? 'partial' : 'active'}`);
+ }
+ }
+ if (!sets.length) return current;
+
+ let setClause = sets[0];
+ for (let i = 1; i < sets.length; i++) setClause = sql`${setClause}, ${sets[i]}`;
+ const [row] = await sql`
+ UPDATE orders SET ${setClause}, updated_at = now()
+ WHERE id = ${orderId} AND agent_id = ${agentId}
+ RETURNING *
+ `;
+ return shapeOrder(row);
+}
+
+/** Cancel an order instantly. Idempotent; a filled order can't be cancelled. */
+export async function cancelOrder(agentId, orderId) {
+ const [row] = await sql`
+ UPDATE orders SET status = 'cancelled', cancelled_at = now(), updated_at = now()
+ WHERE id = ${orderId} AND agent_id = ${agentId}
+ AND status NOT IN ('filled', 'cancelled', 'expired')
+ RETURNING *
+ `;
+ if (row) return shapeOrder(row);
+ // Already terminal (or not found) — return current state so cancel is idempotent.
+ return getOrder(agentId, orderId);
+}
+
+/** Cancel every active/partial order for an agent (kill switch). Returns count. */
+export async function cancelAllOrders(agentId, network = null) {
+ const rows = await sql`
+ UPDATE orders SET status = 'cancelled', cancelled_at = now(), updated_at = now()
+ WHERE agent_id = ${agentId}
+ AND (${network}::text IS NULL OR network = ${network})
+ AND status IN ('active', 'partial', 'firing', 'paused')
+ RETURNING id
+ `;
+ return rows.length;
+}
+
+/** Owner-facing summary across an agent's orders. */
+export async function ordersSummary(agentId, network) {
+ const [agg] = await sql`
+ SELECT
+ COUNT(*)::int AS total,
+ COUNT(*) FILTER (WHERE status IN ('active','partial','firing'))::int AS active,
+ COUNT(*) FILTER (WHERE status = 'filled')::int AS filled,
+ COALESCE(SUM(fill_count), 0)::int AS fills,
+ COALESCE(SUM(filled_sol), 0)::float8 AS filled_sol
+ FROM orders
+ WHERE agent_id = ${agentId} AND (${network}::text IS NULL OR network = ${network})
+ `;
+ return {
+ total: agg?.total || 0,
+ active: agg?.active || 0,
+ filled: agg?.filled || 0,
+ lifetime_fills: agg?.fills || 0,
+ lifetime_filled_sol: Number(agg?.filled_sol || 0),
+ };
+}
diff --git a/api/_lib/portfolio.js b/api/_lib/portfolio.js
new file mode 100644
index 000000000..3fde8cea8
--- /dev/null
+++ b/api/_lib/portfolio.js
@@ -0,0 +1,582 @@
+/**
+ * Portfolio Command — unified, honest valuation + PnL attribution + risk for one
+ * agent's custodial Solana wallet.
+ *
+ * This is the truth layer behind the wallet hub's Portfolio tab and
+ * `/api/agents/:id/portfolio`. It fuses three real sources — never a mock, never
+ * a fabricated price:
+ *
+ * 1. Live on-chain holdings + USD valuation → api/_lib/balances.js (Helius DAS
+ * + Jupiter + pump.fun bonding curve; the same path the holder gate trusts).
+ * 2. The sniper position ledger → agent_sniper_positions, via the
+ * pure computeTraderMetrics in trader-stats.js (on-chain-proven realized P&L).
+ * 3. The custody/spend ledger → agent_custody_events (category
+ * trade / snipe / x402 / withdraw), the record of every outbound action.
+ *
+ * Two layers, mirroring trader-stats.js:
+ * - PURE functions (buildLots, computeRisk, attributionFromLots, riskFlags) —
+ * no DB, no network, deterministic over their inputs. The tests pin these.
+ * - getPortfolio — fetches the three sources, then defers all arithmetic to the
+ * pure layer so the API and the SSE stream can never disagree.
+ *
+ * Honesty rules (inherited from trader-stats.js + CLAUDE.md):
+ * - SOL amounts are exact (from chain / ledger). USD degrades to null if the
+ * price feed is down — we never invent a dollar figure.
+ * - Cost basis uses FIFO lots in RAW token base units, so it needs no decimals
+ * and never drifts. A holding with no recorded acquisition (deposited /
+ * airdropped in) gets a null basis — honestly "unknown", never guessed.
+ * - Unpriceable / dead holdings are flagged `priceable:false` with usd null —
+ * they count toward concentration honestly but never fabricate a value.
+ * - Discretionary realized P&L is FIFO-derived from the recorded trade quotes
+ * (the only proceeds figure the custody row captures); the sniper track is
+ * on-chain actuals. The response labels which is which (`basis`).
+ */
+
+import { sql } from './db.js';
+import { getBalances } from './balances.js';
+import { solUsdPrice } from './avatar-wallet.js';
+import { computeTraderMetrics, fetchTraderPositions } from './trader-stats.js';
+import { solanaConnection, solanaPublicConnection } from './agent-pumpfun.js';
+import { PublicKey } from '@solana/web3.js';
+
+const LAMPORTS_PER_SOL = 1e9;
+const SOL_MINT = 'So11111111111111111111111111111111111111112';
+
+// USDC is the payment-rail asset (1:1 USD), not a coin we promote. $THREE is the
+// platform coin. Both are treated as low-"tape-beta" (they don't move with the
+// pump.fun memecoin tape the way a fresh launch does), so the risk model can
+// honestly separate "at-risk memecoin exposure" from stable / SOL holdings.
+const USDC_MINTS = new Set([
+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // mainnet
+ '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', // devnet
+]);
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+const big = (v) => {
+ try { return Number(BigInt(v)); } catch { return Number(v) || 0; }
+};
+const round = (n, dp = 6) => (n == null || !Number.isFinite(n) ? null : Number(n.toFixed(dp)));
+
+function stddev(values) {
+ if (values.length < 2) return 0;
+ const mean = values.reduce((a, v) => a + v, 0) / values.length;
+ const variance = values.reduce((a, v) => a + (v - mean) ** 2, 0) / (values.length - 1);
+ return Math.sqrt(variance);
+}
+
+// --- Source labelling ---------------------------------------------------------
+// A custody/position row maps to one attribution bucket. Sniper strategies are
+// split out by id+name; everything from the discretionary HTTP path lands in
+// "discretionary"; strategy-object fills carry their own bucket.
+
+const SOURCE_LABELS = {
+ sniper: 'Sniper',
+ discretionary: 'Discretionary',
+ strategy: 'Strategy object',
+ x402: 'x402 payments',
+ withdraw: 'Withdrawals',
+};
+
+/**
+ * FIFO lot engine. Consumes time-ordered acquisitions + disposals per mint in
+ * RAW token base units, attributing realized P&L (lamports) to the SOURCE of the
+ * lot that was sold, and leaving the remaining lots (current cost basis) tagged
+ * by source so unrealized P&L can be attributed too.
+ *
+ * @param {Array<{mint,source,strategyId?,kind:'buy'|'sell',qtyRaw:bigint,
+ * lamports:bigint,at:number}>} events buy = acquisition (lamports = SOL cost),
+ * sell = disposal (lamports = SOL proceeds). qtyRaw is the token amount moved.
+ * @returns {{ realizedBySource: Map, remainingByMint: Map }}
+ * realizedBySource: source → { realizedLamports, sells }
+ * remainingByMint: mint → Array<{ source, strategyId, qtyRaw, costLamports }>
+ */
+export function buildLots(events) {
+ const byMint = new Map();
+ for (const e of events) {
+ if (!e.mint) continue;
+ if (!byMint.get(e.mint)) byMint.set(e.mint, []);
+ byMint.get(e.mint).push(e);
+ }
+
+ const realizedBySource = new Map();
+ const remainingByMint = new Map();
+ const addRealized = (source, lamports) => {
+ const r = realizedBySource.get(source) || { realizedLamports: 0n, sells: 0 };
+ r.realizedLamports += lamports;
+ r.sells += 1;
+ realizedBySource.set(source, r);
+ };
+
+ for (const [mint, list] of byMint) {
+ list.sort((a, b) => a.at - b.at);
+ /** @type {Array<{source,strategyId,qtyRaw:bigint,costLamports:bigint}>} */
+ const lots = [];
+ for (const e of list) {
+ if (e.kind === 'buy') {
+ if (e.qtyRaw > 0n) lots.push({ source: e.source, strategyId: e.strategyId || null, qtyRaw: e.qtyRaw, costLamports: e.lamports });
+ continue;
+ }
+ // sell: consume oldest lots first, attributing realized P&L to each
+ // consumed lot's source (the proceeds are split across lots pro-rata
+ // by the quantity each lot contributes).
+ let remainingToSell = e.qtyRaw;
+ const proceeds = e.lamports; // total SOL out for this disposal
+ const totalSellQty = e.qtyRaw > 0n ? e.qtyRaw : 1n;
+ while (remainingToSell > 0n && lots.length) {
+ const lot = lots[0];
+ const take = lot.qtyRaw <= remainingToSell ? lot.qtyRaw : remainingToSell;
+ // proceeds attributable to this slice (pro-rata of the sell qty)
+ const sliceProceeds = (proceeds * take) / totalSellQty;
+ const sliceCost = (lot.costLamports * take) / (lot.qtyRaw > 0n ? lot.qtyRaw : 1n);
+ addRealized(lot.source, sliceProceeds - sliceCost);
+ lot.qtyRaw -= take;
+ lot.costLamports -= sliceCost;
+ remainingToSell -= take;
+ if (lot.qtyRaw <= 0n) lots.shift();
+ }
+ // A sell with no matching lots (token deposited in, not bought here)
+ // has an unknown basis — attribute the full proceeds as realized to the
+ // disposal's own source rather than inventing a cost.
+ if (remainingToSell > 0n && proceeds > 0n) {
+ const sliceProceeds = (proceeds * remainingToSell) / totalSellQty;
+ addRealized(e.source, sliceProceeds);
+ }
+ }
+ if (lots.length) remainingByMint.set(mint, lots);
+ }
+
+ return { realizedBySource, remainingByMint };
+}
+
+/**
+ * Portfolio risk metrics from valued holdings + the sniper metric set. Pure.
+ *
+ * @param {Array<{usd:number|null, mint:string|null, isNative:boolean, stable:boolean}>} holdings
+ * @param {number} netWorthUsd
+ * @param {object} metrics computeTraderMetrics output (drawdown, etc.)
+ * @param {number[]} closedPnlPcts per-closed-trade realized % (for realized vol)
+ */
+export function computeRisk(holdings, netWorthUsd, metrics, closedPnlPcts) {
+ const valued = holdings.filter((h) => Number.isFinite(h.usd) && h.usd > 0);
+ const totalValued = valued.reduce((s, h) => s + h.usd, 0) || 0;
+
+ // Concentration over everything with a real value (Herfindahl-Hirschman index
+ // of portfolio weights, 0..1; 1 = a single position).
+ let hhi = 0;
+ let topShare = 0;
+ let topHolding = null;
+ for (const h of valued) {
+ const w = totalValued > 0 ? h.usd / totalValued : 0;
+ hhi += w * w;
+ if (w > topShare) { topShare = w; topHolding = h; }
+ }
+
+ // At-risk exposure: share of net worth in volatile memecoins (not SOL, not a
+ // stablecoin). This is the honest "tape beta" proxy — the slice that moves
+ // with the broad pump.fun tape, vs SOL/USDC that don't.
+ const volatileUsd = valued
+ .filter((h) => !h.isNative && !h.stable)
+ .reduce((s, h) => s + h.usd, 0);
+ const exposurePct = netWorthUsd > 0 ? (volatileUsd / netWorthUsd) * 100 : 0;
+ const tapeBeta = netWorthUsd > 0 ? volatileUsd / netWorthUsd : 0;
+
+ return {
+ net_worth_usd: round(netWorthUsd, 2),
+ concentration_hhi: round(hhi, 4),
+ top_position_pct: round(topShare * 100, 2),
+ top_position_mint: topHolding?.mint || (topHolding?.isNative ? 'SOL' : null),
+ volatile_exposure_usd: round(volatileUsd, 2),
+ exposure_pct: round(exposurePct, 2),
+ tape_beta: round(tapeBeta, 3),
+ max_drawdown_pct: metrics?.max_drawdown_pct ?? null,
+ max_drawdown_sol: metrics?.max_drawdown_sol ?? null,
+ realized_volatility_pct: round(stddev(closedPnlPcts), 2),
+ holdings_count: holdings.length,
+ valued_count: valued.length,
+ unpriceable_count: holdings.filter((h) => !Number.isFinite(h.usd) && !h.isNative).length,
+ };
+}
+
+/**
+ * Plain-language risk flags from the metric set + the top holding's liquidity.
+ * Each flag is { level: 'info'|'warn'|'danger', text }. Pure + deterministic.
+ */
+export function riskFlags(risk, topHoldingPriceable) {
+ const flags = [];
+ const top = risk.top_position_pct;
+ if (top != null && top >= 60) {
+ const liq = topHoldingPriceable === false ? ' illiquid' : '';
+ flags.push({
+ level: top >= 80 ? 'danger' : 'warn',
+ text: `${top}% of valued holdings sit in one${liq} position — concentration risk.`,
+ });
+ }
+ if (risk.exposure_pct != null && risk.exposure_pct >= 75) {
+ flags.push({
+ level: risk.exposure_pct >= 90 ? 'danger' : 'warn',
+ text: `${risk.exposure_pct}% of net worth is in volatile memecoins — high tape exposure.`,
+ });
+ }
+ if (risk.max_drawdown_pct != null && risk.max_drawdown_pct >= 35) {
+ flags.push({
+ level: risk.max_drawdown_pct >= 60 ? 'danger' : 'warn',
+ text: `Realized drawdown has reached ${risk.max_drawdown_pct}% from peak.`,
+ });
+ }
+ if (risk.unpriceable_count > 0) {
+ flags.push({
+ level: 'info',
+ text: `${risk.unpriceable_count} holding${risk.unpriceable_count === 1 ? '' : 's'} could not be priced — shown as unvalued, never guessed.`,
+ });
+ }
+ if (!flags.length && risk.net_worth_usd != null) {
+ flags.push({ level: 'info', text: 'No elevated concentration, exposure, or drawdown risk detected.' });
+ }
+ return flags;
+}
+
+// --- Live holdings valuation --------------------------------------------------
+// mainnet: the rich Helius-DAS path (metadata + prices, cached). devnet: a direct
+// RPC enumeration (devnet tokens have no market, so SPL is honestly unpriceable;
+// only SOL is valued). Both normalize to the same holding shape.
+
+function normalizeHolding({ mint, symbol, name, amount, decimals, price, usd, logo, isNative }) {
+ const priceable = Number.isFinite(usd) && usd != null;
+ const stable = mint ? USDC_MINTS.has(mint) : false;
+ return {
+ mint: isNative ? null : mint,
+ symbol: symbol || (isNative ? 'SOL' : (mint ? mint.slice(0, 6) : '?')),
+ name: name || symbol || (isNative ? 'Solana' : null),
+ amount: amount ?? null,
+ decimals: decimals ?? (isNative ? 9 : null),
+ price: Number.isFinite(price) ? price : null,
+ usd: priceable ? Number(usd) : null,
+ logo: logo || null,
+ isNative: !!isNative,
+ stable,
+ is_three: mint === THREE_MINT,
+ priceable,
+ };
+}
+
+async function valuateMainnet(address) {
+ const bal = await getBalances({ chain: 'solana', address });
+ const holdings = [];
+ holdings.push(normalizeHolding({
+ isNative: true, symbol: 'SOL', name: 'Solana',
+ amount: bal?.native?.amount ?? 0, decimals: 9,
+ price: bal?.native?.price ?? null, usd: bal?.native?.usd ?? null,
+ }));
+ for (const t of bal?.tokens || []) {
+ holdings.push(normalizeHolding({
+ mint: t.mint, symbol: t.symbol, name: t.name, amount: t.amount,
+ decimals: t.decimals, price: t.price, usd: t.usd, logo: t.logo,
+ }));
+ }
+ return { holdings, solUsd: bal?.native?.price ?? null };
+}
+
+async function valuateDevnet(address) {
+ // Devnet has no price oracle for SPL; value SOL only, mark SPL unpriceable.
+ const conn = solanaConnection('devnet');
+ const fallback = solanaPublicConnection('devnet');
+ const owner = new PublicKey(address);
+ const readBalance = async (c) => c.getBalance(owner, 'confirmed');
+ let lamports = 0;
+ try { lamports = await readBalance(conn); }
+ catch { try { lamports = await readBalance(fallback); } catch { lamports = 0; } }
+
+ let solUsd = null;
+ try { solUsd = await solUsdPrice(); } catch { solUsd = null; }
+ const sol = lamports / LAMPORTS_PER_SOL;
+ const holdings = [normalizeHolding({
+ isNative: true, symbol: 'SOL', name: 'Solana', amount: sol, decimals: 9,
+ price: solUsd, usd: solUsd != null ? sol * solUsd : null,
+ })];
+
+ try {
+ const { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } = await import('@solana/spl-token');
+ for (const programId of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) {
+ let resp;
+ try { resp = await conn.getParsedTokenAccountsByOwner(owner, { programId }); } catch { continue; }
+ for (const { account } of resp.value) {
+ const info = account.data?.parsed?.info;
+ const amt = info?.tokenAmount;
+ if (!info || !amt || !(Number(amt.uiAmount) > 0)) continue;
+ holdings.push(normalizeHolding({
+ mint: info.mint, amount: Number(amt.uiAmount), decimals: amt.decimals,
+ price: null, usd: null, // devnet SPL: honestly unpriceable
+ }));
+ }
+ }
+ } catch { /* SPL enumeration best-effort */ }
+
+ return { holdings, solUsd };
+}
+
+/** Live holdings + SOL price for a wallet on a network. */
+export async function valuateHoldings({ network, address }) {
+ if (!address) return { holdings: [], solUsd: null };
+ return network === 'devnet' ? valuateDevnet(address) : valuateMainnet(address);
+}
+
+// --- Ledger → FIFO events -----------------------------------------------------
+
+/** Sniper positions → buy/sell FIFO events tagged by strategy. */
+function sniperEvents(positions) {
+ const events = [];
+ for (const p of positions) {
+ if (!p.mint) continue;
+ const source = `sniper:${p.strategy_id || 'default'}`;
+ const opened = new Date(p.opened_at).getTime();
+ const qty = p.base_amount != null ? BigInt(p.base_amount) : 0n;
+ if (qty > 0n) {
+ events.push({
+ mint: p.mint, source: 'sniper', strategyId: p.strategy_id || null, kind: 'buy',
+ qtyRaw: qty, lamports: p.entry_quote_lamports != null ? BigInt(p.entry_quote_lamports) : 0n,
+ at: opened,
+ });
+ }
+ if (p.status === 'closed' && qty > 0n) {
+ events.push({
+ mint: p.mint, source: 'sniper', strategyId: p.strategy_id || null, kind: 'sell',
+ qtyRaw: qty, lamports: p.exit_quote_lamports != null ? BigInt(p.exit_quote_lamports) : 0n,
+ at: new Date(p.closed_at || p.opened_at).getTime(),
+ });
+ }
+ }
+ return events;
+}
+
+/** Custody 'trade' events → buy/sell FIFO events (discretionary + strategy). */
+function custodyTradeEvents(rows) {
+ const events = [];
+ for (const e of rows) {
+ const m = e.meta && typeof e.meta === 'object' ? e.meta : {};
+ const mint = m.mint || (e.asset && e.asset !== 'SOL' ? e.asset : null);
+ if (!mint) continue;
+ const side = m.side || (e.asset === 'SOL' ? 'buy' : 'sell');
+ const source = m.source === 'strategy' ? 'strategy' : 'discretionary';
+ const at = new Date(e.created_at).getTime();
+ if (side === 'buy') {
+ // buy: SOL spent = amount_lamports; tokens received ≈ meta.expected_out (raw)
+ events.push({
+ mint, source, strategyId: m.strategy_id || null, kind: 'buy',
+ qtyRaw: m.expected_out ? safeBig(m.expected_out) : 0n,
+ lamports: e.amount_lamports != null ? BigInt(e.amount_lamports) : 0n,
+ at,
+ });
+ } else {
+ // sell: tokens out = amount_raw; SOL proceeds ≈ meta.expected_out (raw lamports)
+ events.push({
+ mint, source, strategyId: m.strategy_id || null, kind: 'sell',
+ qtyRaw: e.amount_raw != null ? safeBig(e.amount_raw) : 0n,
+ lamports: m.expected_out ? safeBig(m.expected_out) : 0n,
+ at,
+ });
+ }
+ }
+ return events;
+}
+
+function safeBig(v) {
+ try { return BigInt(String(v).split('.')[0]); } catch { return 0n; }
+}
+
+// --- Main assembly ------------------------------------------------------------
+
+let _solCache = { usd: null, at: 0 };
+async function cachedSolUsd(fallback) {
+ if (fallback != null) { _solCache = { usd: fallback, at: Date.now() }; return fallback; }
+ if (_solCache.usd != null && Date.now() - _solCache.at < 60_000) return _solCache.usd;
+ try { const usd = await solUsdPrice(); _solCache = { usd, at: Date.now() }; return usd; }
+ catch { return _solCache.usd; }
+}
+
+/**
+ * The full portfolio for one agent wallet on one network: live valuation,
+ * holdings with FIFO cost basis + unrealized P&L, PnL attribution by source,
+ * risk metrics, and plain-language risk flags. Returns null if the agent doesn't
+ * exist; an honest empty-wallet shape if it has no holdings/history.
+ *
+ * @param {{ agentId:string, network?:string, now?:number }} opts
+ */
+export async function getPortfolio({ agentId, network = 'mainnet', now = Date.now() }) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+
+ const [idRows, positions, custodyRows] = await Promise.all([
+ sql`select id, name, profile_image_url, avatar_url, meta from agent_identities where id = ${agentId} and deleted_at is null limit 1`,
+ fetchTraderPositions({ agentId, network: net, window: 'all', now }).catch(() => []),
+ sql`
+ select id, event_type, category, asset, amount_lamports, amount_raw, usd, status, created_at, meta
+ from agent_custody_events
+ where agent_id = ${agentId} and network = ${net}
+ order by id asc
+ `.catch(() => []),
+ ]);
+ const identity = idRows[0];
+ if (!identity) return null;
+ const address = identity.meta?.solana_address || null;
+
+ const { holdings, solUsd: valSolUsd } = await valuateHoldings({ network: net, address });
+ const solUsd = await cachedSolUsd(valSolUsd);
+
+ const metrics = computeTraderMetrics(positions, { solUsd });
+ const closedPnlPcts = positions
+ .filter((p) => p.status === 'closed' && p.realized_pnl_pct != null && Number.isFinite(Number(p.realized_pnl_pct)))
+ .map((p) => Number(p.realized_pnl_pct));
+
+ // FIFO over the unified trade ledger (sniper + custody trades).
+ const tradeRows = custodyRows.filter((e) => e.category === 'trade' && e.event_type === 'spend' && e.status !== 'failed');
+ const events = [...sniperEvents(positions), ...custodyTradeEvents(tradeRows)];
+ const { realizedBySource, remainingByMint } = buildLots(events);
+
+ // Per-mint live price in lamports-per-raw-unit (for unrealized on held lots).
+ const priceByMint = new Map();
+ for (const h of holdings) {
+ if (!h.mint || !h.priceable || h.price == null || solUsd == null || h.decimals == null) continue;
+ // usd/uiToken → SOL/uiToken → lamports/rawUnit
+ const lamportsPerRaw = (h.price / solUsd) * LAMPORTS_PER_SOL / Math.pow(10, h.decimals);
+ priceByMint.set(h.mint, lamportsPerRaw);
+ }
+
+ // Cost basis per current holding + unrealized P&L by source.
+ const unrealizedBySource = new Map();
+ const basisByMint = new Map();
+ for (const [mint, lots] of remainingByMint) {
+ const lamportsPerRaw = priceByMint.get(mint);
+ let costLamports = 0n;
+ let liveLamports = 0n;
+ let priced = lamportsPerRaw != null;
+ for (const lot of lots) {
+ costLamports += lot.costLamports;
+ const lotLive = priced ? BigInt(Math.round(Number(lot.qtyRaw) * lamportsPerRaw)) : 0n;
+ liveLamports += lotLive;
+ if (priced) {
+ const u = unrealizedBySource.get(lot.source) || 0n;
+ unrealizedBySource.set(lot.source, u + (lotLive - lot.costLamports));
+ }
+ }
+ basisByMint.set(mint, {
+ cost_sol: round(big(costLamports.toString()) / LAMPORTS_PER_SOL),
+ live_sol: priced ? round(big(liveLamports.toString()) / LAMPORTS_PER_SOL) : null,
+ unrealized_sol: priced ? round((big(liveLamports.toString()) - big(costLamports.toString())) / LAMPORTS_PER_SOL) : null,
+ });
+ }
+
+ // Attach cost basis to each holding.
+ const holdingsOut = holdings.map((h) => {
+ const basis = h.mint ? basisByMint.get(h.mint) : null;
+ const unrealizedPct = basis && basis.cost_sol > 0 && basis.unrealized_sol != null
+ ? round((basis.unrealized_sol / basis.cost_sol) * 100, 2)
+ : null;
+ return {
+ ...h,
+ usd_value: h.usd ?? null,
+ cost_basis_sol: basis?.cost_sol ?? null,
+ unrealized_sol: basis?.unrealized_sol ?? null,
+ unrealized_pct: unrealizedPct,
+ liquidity_warning: !h.isNative && !h.priceable ? 'unpriceable' : null,
+ };
+ }).sort((a, b) => (b.usd_value ?? -1) - (a.usd_value ?? -1));
+
+ // Net worth.
+ const netWorthSol = holdings.reduce((s, h) => {
+ if (h.isNative) return s + (h.amount || 0);
+ if (h.priceable && solUsd) return s + (h.usd / solUsd);
+ return s;
+ }, 0);
+ const netWorthUsd = holdings.reduce((s, h) => s + (Number.isFinite(h.usd) ? h.usd : 0), 0);
+
+ // Attribution buckets.
+ const attribution = buildAttribution({
+ realizedBySource, unrealizedBySource, custodyRows, solUsd,
+ });
+
+ const risk = computeRisk(holdingsOut, netWorthUsd, metrics, closedPnlPcts);
+ const top = holdingsOut.find((h) => (h.mint || (h.isNative ? 'SOL' : null)) === risk.top_position_mint);
+ const flags = riskFlags(risk, top ? top.priceable : null);
+
+ return {
+ agent: {
+ id: identity.id,
+ name: identity.name,
+ image: identity.profile_image_url || identity.avatar_url || null,
+ wallet: address,
+ },
+ network: net,
+ sol_usd: solUsd,
+ t: now,
+ net_worth: {
+ sol: round(netWorthSol),
+ usd: round(netWorthUsd, 2),
+ realized_pnl_sol: metrics.realized_pnl_sol,
+ realized_pnl_usd: metrics.realized_pnl_usd,
+ unrealized_pnl_sol: round(sumUnrealizedSol(unrealizedBySource)),
+ },
+ holdings: holdingsOut,
+ attribution,
+ risk,
+ risk_flags: flags,
+ metrics,
+ basis_note: 'Sniper P&L is on-chain actuals; discretionary P&L is FIFO-derived from recorded trade quotes.',
+ };
+}
+
+function sumUnrealizedSol(unrealizedBySource) {
+ let total = 0n;
+ for (const v of unrealizedBySource.values()) total += v;
+ return big(total.toString()) / LAMPORTS_PER_SOL;
+}
+
+/**
+ * Assemble the attribution table. Realized + unrealized from the FIFO engine,
+ * plus pure-outflow buckets (x402 payments, withdrawals) summed from the custody
+ * ledger. Pure given its inputs (exported for tests).
+ */
+export function buildAttribution({ realizedBySource, unrealizedBySource, custodyRows, solUsd }) {
+ const usd = (sol) => (solUsd != null && sol != null ? round(sol * solUsd, 2) : null);
+ const buckets = new Map();
+ const bucket = (key, label) => {
+ if (!buckets.get(key)) buckets.set(key, { source: key, label, realized_sol: 0, unrealized_sol: 0, sells: 0, spent_sol: 0 });
+ return buckets.get(key);
+ };
+
+ for (const [source, r] of realizedBySource) {
+ const key = source.startsWith('sniper') ? 'sniper' : source;
+ const b = bucket(key, SOURCE_LABELS[key] || key);
+ b.realized_sol += big(r.realizedLamports.toString()) / LAMPORTS_PER_SOL;
+ b.sells += r.sells;
+ }
+ for (const [source, lamports] of unrealizedBySource) {
+ const key = source.startsWith('sniper') ? 'sniper' : source;
+ const b = bucket(key, SOURCE_LABELS[key] || key);
+ b.unrealized_sol += big(lamports.toString()) / LAMPORTS_PER_SOL;
+ }
+
+ // Pure-outflow categories (no round-trip P&L): x402 + withdraw.
+ const outflow = { x402: 0, withdraw: 0 };
+ for (const e of custodyRows) {
+ if (e.status === 'failed') continue;
+ if (e.category === 'x402') outflow.x402 += e.amount_lamports != null ? big(e.amount_lamports) / LAMPORTS_PER_SOL : 0;
+ else if (e.category === 'withdraw') outflow.withdraw += e.amount_lamports != null ? big(e.amount_lamports) / LAMPORTS_PER_SOL : 0;
+ }
+ if (outflow.x402 > 0) bucket('x402', SOURCE_LABELS.x402).spent_sol = outflow.x402;
+ if (outflow.withdraw > 0) bucket('withdraw', SOURCE_LABELS.withdraw).spent_sol = outflow.withdraw;
+
+ return [...buckets.values()]
+ .map((b) => ({
+ source: b.source,
+ label: b.label,
+ realized_sol: round(b.realized_sol),
+ realized_usd: usd(b.realized_sol),
+ unrealized_sol: round(b.unrealized_sol),
+ unrealized_usd: usd(b.unrealized_sol),
+ total_sol: round(b.realized_sol + b.unrealized_sol),
+ spent_sol: b.spent_sol > 0 ? round(b.spent_sol) : null,
+ spent_usd: b.spent_sol > 0 ? usd(b.spent_sol) : null,
+ sells: b.sells,
+ is_outflow: b.source === 'x402' || b.source === 'withdraw',
+ }))
+ .sort((a, b) => (b.total_sol ?? 0) - (a.total_sol ?? 0));
+}
diff --git a/api/_lib/signal-engine.js b/api/_lib/signal-engine.js
new file mode 100644
index 000000000..07bde97d6
--- /dev/null
+++ b/api/_lib/signal-engine.js
@@ -0,0 +1,654 @@
+// Signal marketplace engine — the truth layer for reputation-gated, x402-metered
+// copy-trading. Two halves, mirroring api/_lib/trader-stats.js's design so the
+// numbers can never disagree with the leaderboard:
+//
+// PURE (no DB, no network): outcome classification, conviction + sizing math,
+// and the confidence-regressed feed-edge score the marketplace ranks on. These
+// are what the tests pin to fixtures.
+//
+// DB layer: generate emissions from the publisher's REAL agent_sniper_positions
+// (entry on open, exit on close, realized outcome backfilled), deliver each
+// paid emission to a subscriber (x402 USDC payment + guarded auto-mirror), and
+// roll up per-feed accountability stats for the directory.
+//
+// Honesty rules baked in (same spirit as trader-stats):
+// - Every emission binds to a real on-chain fill (buy_sig / sell_sig). Sellers
+// cannot hand-author signals; the source is the same position ledger the
+// verification badge is computed from.
+// - A feed's rank is its PROVEN realized edge, regressed toward neutral (and the
+// publisher's own track-record score) until enough signals have closed — a
+// thin feed with one lucky call can never top a deep, consistent one.
+// - Realized outcomes count losers; nothing is hidden.
+
+import { sql } from './db.js';
+import { PublicKey } from '@solana/web3.js';
+import { fetchTraderPositions, computeTraderMetrics } from './trader-stats.js';
+import { runFollowerTrade, loadFollower } from './agent-mirror.js';
+import { transferUsdcGuarded } from './agent-usdc-transfer.js';
+import { solanaConnection } from './agent-pumpfun.js';
+import { WSOL_MINT } from './pump-trade-args.js';
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+const lamToSol = (l) => (l == null ? 0 : Number(BigInt(l)) / LAMPORTS_PER_SOL);
+const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));
+const DEFAULT_MIRROR_SLIPPAGE_BPS = 300;
+
+// --- Edge-score tuning. Transparent, named, tunable (cf. trader-stats). --------
+const EDGE_WEIGHTS = { hitRate: 0.55, roi: 0.45 };
+const EDGE_CONFIDENCE_FULL_AT = 10; // closed signals for full statistical confidence
+const EDGE_NEUTRAL = 0.45; // unproven feeds regress toward this (slightly below mid)
+const ROI_TANH_PCT = 50; // ~+50% avg realized ≈ a strongly positive ROI sub-score
+const FLAT_OUTCOME_PCT = 1; // |realized| ≤ this counts as flat, not win/loss
+const DUST_ORDER_SOL = 0.002; // mirror orders below this are skipped as dust
+
+// ── PURE ──────────────────────────────────────────────────────────────────────
+
+/** Realized P&L pct → win / loss / flat. A near-zero result is flat, not a win. */
+export function classifyOutcome(realizedPnlPct) {
+ if (realizedPnlPct == null || !Number.isFinite(Number(realizedPnlPct))) return null;
+ const pct = Number(realizedPnlPct);
+ if (pct > FLAT_OUTCOME_PCT) return 'win';
+ if (pct < -FLAT_OUTCOME_PCT) return 'loss';
+ return 'flat';
+}
+
+/** This entry's size relative to the publisher's typical (median) entry. 1.0 = typical. */
+export function computeSizeMultiple(entrySol, referenceEntrySol) {
+ const ref = Number(referenceEntrySol);
+ const entry = Number(entrySol);
+ if (!(ref > 0) || !(entry > 0)) return 1;
+ return Number((entry / ref).toFixed(4));
+}
+
+/**
+ * Conviction (0..1) from how large a bet this is vs the trader's norm. A trader
+ * sizing 3× their typical entry is maximally convicted; their typical entry sits
+ * near 0.33. Documented heuristic — bound to real sizing data, never declared.
+ */
+export function computeConviction(sizeMultiple) {
+ const m = Number(sizeMultiple);
+ if (!(m > 0)) return 0;
+ return Number(clamp(m / 3, 0, 1).toFixed(3));
+}
+
+/**
+ * The subscriber's mirrored order size (SOL) for an entry:
+ * base_sol × size_multiple × size_scaling, hard-capped at max_per_trade_sol.
+ * Returns 0 when the sized order is dust (the caller skips it).
+ */
+export function subscriberOrderSol({ baseSol, sizeMultiple, sizeScaling = 1, maxPerTradeSol }) {
+ const sized = Number(baseSol) * Number(sizeMultiple || 1) * Number(sizeScaling || 1);
+ const capped = clamp(sized, 0, Number(maxPerTradeSol) || sized);
+ return capped < DUST_ORDER_SOL ? 0 : Number(capped.toFixed(6));
+}
+
+/**
+ * A feed's proven realized edge (0–100), confidence-regressed. Until a feed has
+ * EDGE_CONFIDENCE_FULL_AT closed signals, its score is pulled toward a neutral
+ * blended with the publisher's own verified track-record score — so a strong
+ * trader's new feed isn't punished to neutral, but still must PROVE per-feed edge
+ * before it can top the board.
+ */
+export function feedEdgeScore({ closedSignals, winningSignals, avgRealizedPct, publisherScore = 50 }) {
+ const closed = Number(closedSignals) || 0;
+ const hitRate = closed > 0 ? clamp((Number(winningSignals) || 0) / closed, 0, 1) : 0;
+ const roiComponent = 0.5 + 0.5 * Math.tanh((Number(avgRealizedPct) || 0) / ROI_TANH_PCT);
+ const raw = clamp(EDGE_WEIGHTS.hitRate * hitRate + EDGE_WEIGHTS.roi * roiComponent, 0, 1);
+ const confidence = clamp(closed / EDGE_CONFIDENCE_FULL_AT, 0, 1);
+ const prior = clamp((Number(publisherScore) || 50) / 100, 0, 1);
+ const neutral = (EDGE_NEUTRAL + prior) / 2;
+ const effective = raw * confidence + neutral * (1 - confidence);
+ return Math.round(100 * clamp(effective, 0, 1));
+}
+
+export const FEED_SORTS = new Set(['edge', 'roi', 'hitrate', 'subscribers', 'newest']);
+
+const FEED_COMPARATORS = {
+ edge: (a, b) => b.edge_score - a.edge_score || b.closed_signals - a.closed_signals,
+ roi: (a, b) => (b.avg_realized_pct ?? -1e9) - (a.avg_realized_pct ?? -1e9) || b.edge_score - a.edge_score,
+ hitrate: (a, b) => (b.hit_rate ?? -1) - (a.hit_rate ?? -1) || b.closed_signals - a.closed_signals,
+ subscribers: (a, b) => b.subscribers - a.subscribers || b.edge_score - a.edge_score,
+ newest: (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
+};
+
+/** Sort an already-scored feed list by the chosen key. Pure. */
+export function rankFeeds(feeds, sort = 'edge') {
+ const cmp = FEED_COMPARATORS[sort] || FEED_COMPARATORS.edge;
+ return [...feeds].sort(cmp).map((f, i) => ({ rank: i + 1, ...f }));
+}
+
+/** Median of a numeric array (0 for empty). */
+function median(values) {
+ if (!values.length) return 0;
+ const s = [...values].sort((a, b) => a - b);
+ const mid = Math.floor(s.length / 2);
+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
+}
+
+// ── DB: publisher reference + verification ─────────────────────────────────────
+
+/** The publisher's typical entry size (median, SOL) — the conviction reference. */
+async function referenceEntrySol(publisherAgentId, network) {
+ const rows = await sql`
+ select entry_quote_lamports from agent_sniper_positions
+ where agent_id = ${publisherAgentId} and network = ${network}
+ and entry_quote_lamports is not null
+ order by coalesce(closed_at, opened_at) desc limit 200
+ `.catch(() => []);
+ const entries = rows.map((r) => lamToSol(r.entry_quote_lamports)).filter((v) => v > 0);
+ return median(entries);
+}
+
+/**
+ * The publisher's live trader metrics (verified badge + composite score), from the
+ * SAME pure computeTraderMetrics the leaderboard + profile use. USD is irrelevant
+ * to verification/score, so we price at null (SOL stays exact, no feed dependency).
+ */
+export async function publisherMetrics(publisherAgentId, network) {
+ const positions = await fetchTraderPositions({ agentId: publisherAgentId, network, window: 'all' }).catch(() => []);
+ return computeTraderMetrics(positions, { solUsd: null });
+}
+
+// ── DB: emission generation from real position lifecycle ───────────────────────
+
+/**
+ * Generate this feed's emissions from the publisher's REAL positions since the
+ * feed's cursors: an `entry` when a position opens, an `exit` (+ outcome backfill
+ * onto the entry) when it closes. Idempotent via the (feed, position, side) unique
+ * index — a re-run never double-emits. Returns a small summary. Never throws.
+ */
+export async function syncFeedEmissions(feed) {
+ const network = feed.network === 'devnet' ? 'devnet' : 'mainnet';
+ const out = { entries: 0, exits: 0, closed: 0 };
+
+ const refEntrySol = await referenceEntrySol(feed.publisher_agent_id, network);
+
+ // --- ENTRIES: positions opened since the entry cursor. ---
+ if (feed.emit_entries) {
+ const opened = await sql`
+ select id, mint, symbol, name, entry_quote_lamports, entry_price_lamports_per_token, buy_sig, opened_at
+ from agent_sniper_positions
+ where agent_id = ${feed.publisher_agent_id} and network = ${network}
+ and opened_at > ${feed.entry_cursor}
+ and entry_quote_lamports is not null
+ order by opened_at asc limit 100
+ `.catch(() => []);
+ let maxOpened = null;
+ for (const p of opened) {
+ const entrySol = lamToSol(p.entry_quote_lamports);
+ const sizeMultiple = computeSizeMultiple(entrySol, refEntrySol);
+ const conviction = computeConviction(sizeMultiple);
+ maxOpened = p.opened_at;
+ if (conviction < Number(feed.min_conviction || 0)) continue; // below the feed's floor
+ const ins = await sql`
+ insert into signal_emissions
+ (feed_id, publisher_agent_id, network, source_position_id, mint, symbol, name,
+ side, size_multiple, conviction, entry_sol, ref_price_lpt, status, source_buy_sig, emitted_at)
+ values (${feed.id}, ${feed.publisher_agent_id}, ${network}, ${p.id}, ${p.mint}, ${p.symbol}, ${p.name},
+ 'entry', ${feed.reveal_sizing ? sizeMultiple : null}, ${conviction},
+ ${feed.reveal_sizing ? Number(entrySol.toFixed(6)) : null}, ${p.entry_price_lamports_per_token ?? null},
+ 'open', ${p.buy_sig ?? null}, ${p.opened_at})
+ on conflict (feed_id, source_position_id, side) do nothing
+ returning id
+ `.catch(() => []);
+ if (ins.length) out.entries += 1;
+ }
+ if (maxOpened) {
+ await sql`update signal_feeds set entry_cursor = ${maxOpened}, updated_at = now() where id = ${feed.id}`.catch(() => {});
+ }
+ }
+
+ // --- EXITS + outcome backfill: positions closed since the exit cursor. ---
+ const closed = await sql`
+ select id, mint, symbol, name, realized_pnl_lamports, realized_pnl_pct, sell_sig, closed_at
+ from agent_sniper_positions
+ where agent_id = ${feed.publisher_agent_id} and network = ${network}
+ and status = 'closed' and closed_at is not null and closed_at > ${feed.exit_cursor}
+ order by closed_at asc limit 100
+ `.catch(() => []);
+ let maxClosed = null;
+ for (const p of closed) {
+ maxClosed = p.closed_at;
+ const realizedPct = p.realized_pnl_pct != null ? Number(p.realized_pnl_pct) : null;
+ const realizedSol = lamToSol(p.realized_pnl_lamports);
+ const outcome = classifyOutcome(realizedPct);
+
+ // Backfill the entry signal's realized outcome (proof of edge).
+ const updated = await sql`
+ update signal_emissions set
+ status = 'closed', realized_pnl_pct = ${realizedPct}, realized_pnl_sol = ${Number(realizedSol.toFixed(6))},
+ outcome = ${outcome}, source_sell_sig = ${p.sell_sig ?? null}, closed_at = ${p.closed_at}
+ where feed_id = ${feed.id} and source_position_id = ${p.id} and side = 'entry' and status = 'open'
+ returning id
+ `.catch(() => []);
+ if (updated.length) {
+ out.closed += 1;
+ // Propagate the proven outcome to every delivery of that entry (follower-ROI rollup).
+ await sql`update signal_deliveries set signal_realized_pct = ${realizedPct}, updated_at = now() where emission_id = ${updated[0].id}`.catch(() => {});
+ }
+
+ // Emit a distinct exit signal only when the feed publishes exits AND we
+ // actually emitted the matching entry (never an exit for an unentered coin).
+ if (feed.emit_exits && updated.length) {
+ const ins = await sql`
+ insert into signal_emissions
+ (feed_id, publisher_agent_id, network, source_position_id, mint, symbol, name,
+ side, conviction, status, realized_pnl_pct, realized_pnl_sol, outcome, source_sell_sig, emitted_at, closed_at)
+ values (${feed.id}, ${feed.publisher_agent_id}, ${network}, ${p.id}, ${p.mint}, ${p.symbol}, ${p.name},
+ 'exit', 1, 'closed', ${realizedPct}, ${Number(realizedSol.toFixed(6))}, ${outcome},
+ ${p.sell_sig ?? null}, ${p.closed_at}, ${p.closed_at})
+ on conflict (feed_id, source_position_id, side) do nothing
+ returning id
+ `.catch(() => []);
+ if (ins.length) out.exits += 1;
+ }
+ }
+ if (maxClosed) {
+ await sql`update signal_feeds set exit_cursor = ${maxClosed}, updated_at = now() where id = ${feed.id}`.catch(() => {});
+ }
+ return out;
+}
+
+// ── DB: paid delivery + auto-mirror to a subscriber ────────────────────────────
+
+/** The subscriber's full token balance for a mint (sizes the mirrored exit). */
+async function readTokenBalanceRaw(conn, ownerPk, mintPk) {
+ try {
+ const res = await conn.getParsedTokenAccountsByOwner(ownerPk, { mint: mintPk });
+ let raw = 0n;
+ for (const acc of res?.value || []) {
+ const amt = acc.account?.data?.parsed?.info?.tokenAmount?.amount;
+ if (amt) raw += BigInt(amt);
+ }
+ return raw;
+ } catch { return 0n; }
+}
+
+/** Resolve the USDC price the subscriber owes for one emission under its billing. */
+function priceForDelivery({ feed, subscription, emission, now }) {
+ if (subscription.mode === 'simulate') return { usdc: 0, charge: false };
+ if (subscription.billing === 'per_epoch') {
+ const paidUntil = subscription.epoch_paid_until ? new Date(subscription.epoch_paid_until).getTime() : 0;
+ if (now <= paidUntil) return { usdc: 0, charge: false }; // inside a paid epoch
+ const usdc = Number(feed.price_per_epoch_usdc) || 0;
+ return usdc > 0 ? { usdc, charge: true, epoch: true } : { usdc: 0, charge: false };
+ }
+ // per_signal — only entries are billable; exits ride free once the entry is paid.
+ if (emission.side !== 'entry') return { usdc: 0, charge: false };
+ const usdc = Number(feed.price_per_signal_usdc) || 0;
+ return usdc > 0 ? { usdc, charge: true } : { usdc: 0, charge: false };
+}
+
+/**
+ * Deliver one emission to one subscription: claim the idempotent delivery row,
+ * settle the x402 payment (live only), then auto-mirror through the shared guarded
+ * trade path. Returns the delivery summary. Never throws past the boundary.
+ */
+export async function deliverOne({ subscription, feed, emission, follower, now = Date.now() }) {
+ const network = subscription.network === 'devnet' ? 'devnet' : 'mainnet';
+
+ // Idempotency: one delivery per (subscription, emission). A retry no-ops.
+ const [claimed] = await sql`
+ insert into signal_deliveries
+ (subscription_id, emission_id, feed_id, subscriber_agent_id, publisher_agent_id, network, mode, side, mirror_status)
+ values (${subscription.id}, ${emission.id}, ${feed.id}, ${subscription.subscriber_agent_id},
+ ${feed.publisher_agent_id}, ${network}, ${subscription.mode}, ${emission.side}, 'pending')
+ on conflict (subscription_id, emission_id) do nothing
+ returning id
+ `.catch(() => []);
+ if (!claimed) return { status: 'duplicate' };
+ const deliveryId = Number(claimed.id);
+
+ const finalize = async (patch) => {
+ await sql`
+ update signal_deliveries set
+ payment_status = ${patch.payment_status ?? 'none'},
+ payment_custody_event_id = ${patch.payment_custody_event_id ?? null},
+ payment_signature = ${patch.payment_signature ?? null},
+ payment_usdc = ${patch.payment_usdc ?? null},
+ mirror_status = ${patch.mirror_status ?? 'skipped'},
+ mirror_skip_reason = ${patch.mirror_skip_reason ?? null},
+ mirror_custody_event_id = ${patch.mirror_custody_event_id ?? null},
+ mirror_signature = ${patch.mirror_signature ?? null},
+ order_sol = ${patch.order_sol ?? null},
+ price_impact_pct = ${patch.price_impact_pct ?? null},
+ emit_to_fill_ms = ${patch.emit_to_fill_ms ?? null},
+ signal_realized_pct = ${emission.realized_pnl_pct ?? null},
+ updated_at = now()
+ where id = ${deliveryId}
+ `.catch(() => {});
+ return { deliveryId, ...patch };
+ };
+
+ const emittedAt = new Date(emission.emitted_at).getTime();
+ const latencyMs = Math.max(0, now - emittedAt);
+
+ // Exits the subscriber opted out of — record and move on.
+ if (emission.side === 'exit' && !subscription.copy_exits) {
+ return finalize({ mirror_status: 'skipped', mirror_skip_reason: 'exits_disabled', emit_to_fill_ms: latencyMs });
+ }
+
+ // 1. Payment leg (x402 USDC, live only).
+ const price = priceForDelivery({ feed, subscription, emission, now });
+ let payment = { payment_status: 'none', payment_usdc: null, payment_custody_event_id: null, payment_signature: null };
+ if (price.charge) {
+ const idem = `signal:${subscription.id}:${price.epoch ? `epoch:${Math.floor(now / 1000)}` : `emit:${emission.id}`}`;
+ const pay = await transferUsdcGuarded({
+ fromAgentId: subscription.subscriber_agent_id, fromUserId: subscription.owner_user_id,
+ fromMeta: follower.meta, toAddress: feed.payout_address, usdc: price.usdc,
+ network, category: 'signal', idempotencyKey: idem,
+ rowMeta: { feed_id: feed.id, emission_id: emission.id, billing: subscription.billing, publisher_agent_id: feed.publisher_agent_id },
+ });
+ if (pay.status === 'paid' || pay.status === 'replayed') {
+ payment = { payment_status: 'paid', payment_usdc: price.usdc, payment_custody_event_id: pay.custodyEventId ?? null, payment_signature: pay.signature ?? null };
+ if (price.epoch) {
+ const until = new Date(now + Number(feed.epoch_seconds || 86400) * 1000).toISOString();
+ await sql`update signal_subscriptions set epoch_paid_until = ${until}, updated_at = now() where id = ${subscription.id}`.catch(() => {});
+ }
+ } else {
+ // Payment blocked (cap/frozen) or failed — never trade unpaid alpha.
+ return finalize({
+ payment_status: 'failed', payment_usdc: price.usdc, mirror_status: 'skipped',
+ mirror_skip_reason: `unpaid_${pay.code || pay.status}`, emit_to_fill_ms: latencyMs,
+ });
+ }
+ }
+
+ // 2. Mirror leg.
+ // Simulate mode: size the order, label it, spend nothing.
+ if (subscription.mode === 'simulate') {
+ let orderSol = null;
+ if (emission.side === 'entry') {
+ orderSol = subscriberOrderSol({
+ baseSol: subscription.base_sol, sizeMultiple: emission.size_multiple ?? 1,
+ sizeScaling: subscription.size_scaling, maxPerTradeSol: subscription.max_per_trade_sol,
+ });
+ }
+ return finalize({ ...payment, mirror_status: 'simulated', order_sol: orderSol, emit_to_fill_ms: latencyMs });
+ }
+
+ if (emission.mint === WSOL_MINT) {
+ return finalize({ ...payment, mirror_status: 'skipped', mirror_skip_reason: 'wsol', emit_to_fill_ms: latencyMs });
+ }
+
+ const slippageBps = clamp(Number(subscription.slippage_bps) || DEFAULT_MIRROR_SLIPPAGE_BPS, 0, 5000);
+ const leaderRef = {
+ leader_agent_id: feed.publisher_agent_id, leader_name: feed.publisher_name || null,
+ feed_id: feed.id, emission_id: emission.id, source: 'signal',
+ };
+
+ if (emission.side === 'entry') {
+ const orderSol = subscriberOrderSol({
+ baseSol: subscription.base_sol, sizeMultiple: emission.size_multiple ?? 1,
+ sizeScaling: subscription.size_scaling, maxPerTradeSol: subscription.max_per_trade_sol,
+ });
+ if (!orderSol) return finalize({ ...payment, mirror_status: 'skipped', mirror_skip_reason: 'dust_order', order_sol: 0, emit_to_fill_ms: latencyMs });
+ const result = await runFollowerTrade({
+ follower, side: 'buy', mint: emission.mint, network,
+ solAmount: orderSol, tokenAmountRaw: null, slippageBps,
+ idempotencyKey: `signal:${subscription.id}:${emission.id}:buy`, leaderRef,
+ firewallLevel: subscription.firewall_level === 'warn' ? 'warn' : 'block',
+ });
+ return finalize({
+ ...payment,
+ mirror_status: mirrorStatusOf(result),
+ mirror_skip_reason: result.status === 'executed' ? null : (result.code || null),
+ mirror_custody_event_id: result.custodyEventId ?? null,
+ mirror_signature: result.signature ?? null,
+ order_sol: orderSol, price_impact_pct: result.priceImpact ?? null, emit_to_fill_ms: latencyMs,
+ });
+ }
+
+ // EXIT — sell the subscriber's full holding of the mint.
+ let ownerPk;
+ try { ownerPk = new PublicKey(follower.address); } catch { return finalize({ ...payment, mirror_status: 'skipped', mirror_skip_reason: 'wallet_preparing', emit_to_fill_ms: latencyMs }); }
+ const conn = solanaConnection(network);
+ const raw = await readTokenBalanceRaw(conn, ownerPk, new PublicKey(emission.mint));
+ if (raw <= 0n) return finalize({ ...payment, mirror_status: 'skipped', mirror_skip_reason: 'no_holding', emit_to_fill_ms: latencyMs });
+ const result = await runFollowerTrade({
+ follower, side: 'sell', mint: emission.mint, network,
+ solAmount: null, tokenAmountRaw: raw.toString(), slippageBps,
+ idempotencyKey: `signal:${subscription.id}:${emission.id}:sell`, leaderRef,
+ });
+ return finalize({
+ ...payment,
+ mirror_status: mirrorStatusOf(result),
+ mirror_skip_reason: result.status === 'executed' ? null : (result.code || null),
+ mirror_custody_event_id: result.custodyEventId ?? null,
+ mirror_signature: result.signature ?? null,
+ price_impact_pct: result.priceImpact ?? null, emit_to_fill_ms: latencyMs,
+ });
+}
+
+function mirrorStatusOf(result) {
+ if (result.status === 'executed') return 'executed';
+ if (result.status === 'unconfirmed') return 'unconfirmed';
+ if (result.status === 'skipped') return 'skipped';
+ return 'failed';
+}
+
+/**
+ * Deliver every undelivered emission for one active subscription, advancing the
+ * subscription cursor. Used by the cron fanout and the owner's "Sync now". Halts
+ * instantly on kill / non-active status. Never throws.
+ */
+export async function deliverSubscription(subscription, { maxEvents = 20 } = {}) {
+ if (subscription.killed || subscription.status !== 'active') return { delivered: 0, results: [] };
+
+ const [feed] = await sql`
+ select f.*, a.name as publisher_name
+ from signal_feeds f join agent_identities a on a.id = f.publisher_agent_id
+ where f.id = ${subscription.feed_id} limit 1
+ `.catch(() => []);
+ if (!feed || feed.status !== 'active') return { delivered: 0, results: [] };
+
+ const network = subscription.network === 'devnet' ? 'devnet' : 'mainnet';
+ const emissions = await sql`
+ select id, side, mint, symbol, name, size_multiple, conviction, realized_pnl_pct, emitted_at
+ from signal_emissions
+ where feed_id = ${feed.id} and network = ${network} and id > ${subscription.last_emission_id}
+ order by id asc limit ${maxEvents}
+ `.catch(() => []);
+ if (!emissions.length) return { delivered: 0, results: [] };
+
+ const follower = await loadFollower(subscription.subscriber_agent_id);
+ if (!follower) return { delivered: 0, results: [] };
+
+ const results = [];
+ let cursor = Number(subscription.last_emission_id || 0);
+ // Re-read the subscription's epoch state between deliveries (a payment may extend it).
+ let sub = { ...subscription };
+ for (const em of emissions) {
+ try {
+ const r = await deliverOne({ subscription: sub, feed, emission: em, follower });
+ results.push({ emissionId: em.id, side: em.side, ...r });
+ } catch (e) {
+ results.push({ emissionId: em.id, side: em.side, status: 'failed', error: (e?.message || 'error').slice(0, 120) });
+ }
+ cursor = Math.max(cursor, Number(em.id));
+ // Refresh epoch_paid_until so subsequent same-epoch deliveries don't re-charge.
+ if (sub.billing === 'per_epoch') {
+ const [row] = await sql`select epoch_paid_until from signal_subscriptions where id = ${sub.id}`.catch(() => []);
+ if (row) sub = { ...sub, epoch_paid_until: row.epoch_paid_until };
+ }
+ }
+ if (cursor > Number(subscription.last_emission_id || 0)) {
+ await sql`update signal_subscriptions set last_emission_id = ${cursor}, updated_at = now() where id = ${subscription.id}`.catch(() => {});
+ }
+ return { delivered: results.length, results };
+}
+
+// ── DB: marketplace directory + feed detail (read) ─────────────────────────────
+
+/** Per-feed accountability rollup keyed by feed id. */
+async function feedRollups(feedIds) {
+ if (!feedIds.length) return new Map();
+ const rows = await sql`
+ select e.feed_id,
+ count(*) filter (where e.side = 'entry') as total_entries,
+ count(*) filter (where e.side = 'entry' and e.status = 'closed') as closed_signals,
+ count(*) filter (where e.side = 'entry' and e.outcome = 'win') as winning_signals,
+ avg(e.realized_pnl_pct) filter (where e.side = 'entry' and e.status = 'closed') as avg_realized_pct,
+ max(e.emitted_at) as last_emitted_at
+ from signal_emissions e
+ where e.feed_id = any(${feedIds})
+ group by e.feed_id
+ `.catch(() => []);
+ const m = new Map();
+ for (const r of rows) m.set(Number(r.feed_id), r);
+ return m;
+}
+
+/** Active-subscriber count keyed by feed id. */
+async function feedSubscriberCounts(feedIds) {
+ if (!feedIds.length) return new Map();
+ const rows = await sql`
+ select feed_id, count(*)::int as subscribers from signal_subscriptions
+ where feed_id = any(${feedIds}) and status = 'active' and killed = false
+ group by feed_id
+ `.catch(() => []);
+ return new Map(rows.map((r) => [Number(r.feed_id), Number(r.subscribers) || 0]));
+}
+
+/** Latency + follower-ROI rollup from real deliveries, keyed by feed id. */
+async function feedDeliveryRollups(feedIds) {
+ if (!feedIds.length) return new Map();
+ const rows = await sql`
+ select feed_id,
+ count(*) filter (where mirror_status = 'executed') as executed_fills,
+ avg(emit_to_fill_ms) filter (where emit_to_fill_ms is not null) as avg_latency_ms,
+ avg(signal_realized_pct) filter (where signal_realized_pct is not null and side = 'entry') as avg_follower_roi
+ from signal_deliveries where feed_id = any(${feedIds})
+ group by feed_id
+ `.catch(() => []);
+ const m = new Map();
+ for (const r of rows) m.set(Number(r.feed_id), r);
+ return m;
+}
+
+/** Shape + score one feed row against its rollups + the publisher's track record. */
+function shapeFeed(feed, rollup, subscribers, deliveryRollup, metrics) {
+ const closedSignals = Number(rollup?.closed_signals) || 0;
+ const winningSignals = Number(rollup?.winning_signals) || 0;
+ const avgRealizedPct = rollup?.avg_realized_pct != null ? Number(Number(rollup.avg_realized_pct).toFixed(2)) : null;
+ const hitRate = closedSignals > 0 ? Number((winningSignals / closedSignals).toFixed(4)) : null;
+ const publisherScore = metrics?.score ?? 50;
+ return {
+ id: Number(feed.id),
+ slug: feed.slug,
+ title: feed.title,
+ description: feed.description || null,
+ network: feed.network,
+ visibility: feed.visibility,
+ status: feed.status,
+ publisher: {
+ agent_id: feed.publisher_agent_id,
+ name: feed.publisher_name || feed.publisher_agent_id,
+ image: feed.publisher_image || feed.publisher_avatar || null,
+ verified: !!metrics?.verified,
+ score: publisherScore,
+ closed_trades: metrics?.closed_count ?? null,
+ realized_pnl_sol: metrics?.realized_pnl_sol ?? null,
+ win_rate: metrics?.win_rate ?? null,
+ },
+ pricing: {
+ per_signal_usdc: Number(feed.price_per_signal_usdc) || 0,
+ per_epoch_usdc: Number(feed.price_per_epoch_usdc) || 0,
+ epoch_seconds: Number(feed.epoch_seconds) || 86400,
+ },
+ emit: { entries: feed.emit_entries, exits: feed.emit_exits, sizing: feed.reveal_sizing, min_conviction: Number(feed.min_conviction) || 0 },
+ stats: {
+ total_entries: Number(rollup?.total_entries) || 0,
+ closed_signals: closedSignals,
+ winning_signals: winningSignals,
+ hit_rate: hitRate,
+ avg_realized_pct: avgRealizedPct,
+ subscribers,
+ executed_fills: Number(deliveryRollup?.executed_fills) || 0,
+ avg_latency_ms: deliveryRollup?.avg_latency_ms != null ? Math.round(Number(deliveryRollup.avg_latency_ms)) : null,
+ avg_follower_roi_pct: deliveryRollup?.avg_follower_roi != null ? Number(Number(deliveryRollup.avg_follower_roi).toFixed(2)) : null,
+ last_emitted_at: rollup?.last_emitted_at || null,
+ },
+ edge_score: feedEdgeScore({ closedSignals, winningSignals, avgRealizedPct: avgRealizedPct || 0, publisherScore }),
+ closed_signals: closedSignals,
+ avg_realized_pct: avgRealizedPct,
+ hit_rate: hitRate,
+ subscribers,
+ created_at: feed.created_at,
+ };
+}
+
+/**
+ * The public marketplace directory: every active, public feed scored by proven
+ * realized edge (confidence-regressed) and ranked. Thin feeds can't top the board.
+ */
+export async function getMarketplace({ network = 'mainnet', limit = 60, sort = 'edge' } = {}) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const feeds = await sql`
+ select f.*, a.name as publisher_name, a.avatar_url as publisher_avatar, a.profile_image_url as publisher_image
+ from signal_feeds f join agent_identities a on a.id = f.publisher_agent_id
+ where f.network = ${net} and f.status = 'active' and f.visibility = 'public' and a.is_public is not false
+ order by f.created_at desc limit 200
+ `.catch(() => []);
+ if (!feeds.length) return { network: net, sort, feeds: [], t: Date.now() };
+
+ const feedIds = feeds.map((f) => Number(f.id));
+ const [rollups, subCounts, deliveryRollups] = await Promise.all([
+ feedRollups(feedIds), feedSubscriberCounts(feedIds), feedDeliveryRollups(feedIds),
+ ]);
+ // Publisher metrics in parallel (curated, small set).
+ const metricsList = await Promise.all(feeds.map((f) => publisherMetrics(f.publisher_agent_id, net).catch(() => null)));
+
+ const shaped = feeds.map((f, i) => shapeFeed(
+ f, rollups.get(Number(f.id)), subCounts.get(Number(f.id)) || 0, deliveryRollups.get(Number(f.id)), metricsList[i],
+ ));
+ const ranked = rankFeeds(shaped, FEED_SORTS.has(sort) ? sort : 'edge').slice(0, limit);
+ return { network: net, sort: FEED_SORTS.has(sort) ? sort : 'edge', feeds: ranked, t: Date.now() };
+}
+
+/** A single feed's detail: full stats + recent emissions (with realized outcomes). */
+export async function getFeedDetail({ slug, network = 'mainnet', emissionLimit = 40 }) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const [feed] = await sql`
+ select f.*, a.name as publisher_name, a.avatar_url as publisher_avatar, a.profile_image_url as publisher_image, a.is_public
+ from signal_feeds f join agent_identities a on a.id = f.publisher_agent_id
+ where f.slug = ${slug} limit 1
+ `.catch(() => []);
+ if (!feed || feed.is_public === false) return null;
+
+ const feedIds = [Number(feed.id)];
+ const [rollups, subCounts, deliveryRollups, metrics, emissions] = await Promise.all([
+ feedRollups(feedIds), feedSubscriberCounts(feedIds), feedDeliveryRollups(feedIds),
+ publisherMetrics(feed.publisher_agent_id, net).catch(() => null),
+ sql`
+ select id, side, mint, symbol, name, size_multiple, conviction, entry_sol, status,
+ realized_pnl_pct, realized_pnl_sol, outcome, source_buy_sig, source_sell_sig, emitted_at, closed_at
+ from signal_emissions where feed_id = ${feed.id}
+ order by id desc limit ${emissionLimit}
+ `.catch(() => []),
+ ]);
+
+ const shaped = shapeFeed(feed, rollups.get(Number(feed.id)), subCounts.get(Number(feed.id)) || 0, deliveryRollups.get(Number(feed.id)), metrics);
+ const solscan = (sig) => (sig && sig !== 'SIMULATED' ? (net === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`) : null);
+ return {
+ ...shaped,
+ emissions: emissions.map((e) => ({
+ id: Number(e.id),
+ side: e.side,
+ mint: e.mint,
+ symbol: e.symbol,
+ name: e.name,
+ size_multiple: e.size_multiple != null ? Number(e.size_multiple) : null,
+ conviction: e.conviction != null ? Number(e.conviction) : null,
+ entry_sol: e.entry_sol != null ? Number(e.entry_sol) : null,
+ status: e.status,
+ realized_pnl_pct: e.realized_pnl_pct != null ? Number(e.realized_pnl_pct) : null,
+ realized_pnl_sol: e.realized_pnl_sol != null ? Number(e.realized_pnl_sol) : null,
+ outcome: e.outcome,
+ buy_url: solscan(e.source_buy_sig),
+ sell_url: solscan(e.source_sell_sig),
+ emitted_at: e.emitted_at,
+ closed_at: e.closed_at,
+ })),
+ };
+}
diff --git a/api/_lib/solana-transfer.js b/api/_lib/solana-transfer.js
index ef70225a9..4e200b150 100644
--- a/api/_lib/solana-transfer.js
+++ b/api/_lib/solana-transfer.js
@@ -1,4 +1,4 @@
-import { PublicKey, Keypair } from '@solana/web3.js';
+import { PublicKey, Keypair, SystemProgram } from '@solana/web3.js';
import { solanaConnection } from './solana/connection.js';
import { submitProtected } from './execution-engine.js';
import {
@@ -47,3 +47,40 @@ export async function transferSolanaUSDC({ fromWallet, toAddress, amount, mint }
});
return signature;
}
+
+/**
+ * Transfer native SOL from a signing keypair to a recipient address. Used by the
+ * trading-swarm treasury to pay pro-rata profit distributions and exit
+ * redemptions on-chain. Same protected-send path as the SPL transfer above:
+ * data-driven priority fee + CU, rebroadcast with blockhash refresh until it
+ * lands, and a hard throw on an on-chain revert.
+ *
+ * @param {object} opts
+ * @param {import('@solana/web3.js').Keypair} opts.fromKeypair the funded sender (treasury)
+ * @param {string} opts.toAddress recipient Solana address
+ * @param {bigint|number} opts.lamports amount in lamports (must be > 0)
+ * @param {'mainnet'|'devnet'} [opts.network='mainnet']
+ * @returns {Promise<string>} transaction signature
+ */
+export async function transferNativeSol({ fromKeypair, toAddress, lamports, network = 'mainnet' }) {
+ const amount = BigInt(lamports);
+ if (amount <= 0n) throw new Error('transferNativeSol: lamports must be > 0');
+ const recipient = new PublicKey(toAddress);
+ const connection = solanaConnection({ network, commitment: 'confirmed' });
+
+ const instructions = [
+ SystemProgram.transfer({
+ fromPubkey: fromKeypair.publicKey,
+ toPubkey: recipient,
+ lamports: amount,
+ }),
+ ];
+
+ const { signature } = await submitProtected({
+ network,
+ connection,
+ payer: fromKeypair,
+ instructions,
+ });
+ return signature;
+}
diff --git a/api/_lib/swarms.js b/api/_lib/swarms.js
new file mode 100644
index 000000000..769a30ff7
--- /dev/null
+++ b/api/_lib/swarms.js
@@ -0,0 +1,875 @@
+// Agent Trading Swarms — pooled custodial treasury, reputation-weighted consensus,
+// and pro-rata on-chain profit settlement.
+//
+// A swarm is itself an agent-owned custodial wallet (the "treasury agent"),
+// provisioned through the normal agent-wallet path. It carries a dedicated
+// agent_sniper_strategies row that holds its trade policy (budget, per-trade cap,
+// stop-loss/take-profit), so the existing sniper position sweep manages and exits
+// its positions for free. The consensus engine (workers/agent-sniper/swarm.js)
+// fires buys from the treasury only when reputation-weighted member agreement
+// clears the swarm threshold; realized profit distributes pro-rata to members via
+// real SOL transfers from the treasury, and a member can exit and redeem their
+// share of current treasury value at any time.
+//
+// Every lamport moves on-chain and is reconciled to the treasury's live balance —
+// there are no internal virtual balances. Contributions, distributions, and exits
+// are all real transfers, spend-guarded and audited in agent_custody_events
+// (category 'swarm_payout') plus the purpose-built swarm_payouts ledger.
+
+import { sql } from './db.js';
+import { ensureAgentWallet, getOrCreateAgentSolanaWallet, recoverSolanaAgentKeypair } from './agent-wallet.js';
+import { transferNativeSol } from './solana-transfer.js';
+import { solanaConnection } from './solana/connection.js';
+import { recordCustodyEvent } from './agent-trade-guards.js';
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+
+// Keep a small SOL buffer in the treasury for transaction fees so distributions
+// and exits can never strand the wallet below the cost of its own next trade/payout.
+export const GAS_RESERVE_LAMPORTS = 15_000_000n; // 0.015 SOL
+
+// Funding floor — a contribution below this isn't worth an on-chain tx + the fee.
+export const MIN_CONTRIBUTION_LAMPORTS = 5_000_000n; // 0.005 SOL
+
+// Floor weight so a member with no track record still counts a little, while
+// verified reputable members dominate the vote.
+const MIN_VOTE_WEIGHT = 5;
+
+const BPS = 10000;
+
+// ── policy ───────────────────────────────────────────────────────────────────
+
+const num = (v) => (v == null || v === '' || Number.isNaN(Number(v)) ? null : Number(v));
+const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
+
+/**
+ * Validate + normalize a swarm policy. Throws SwarmError on an out-of-range value
+ * so a malformed policy never reaches the treasury strategy.
+ */
+export function normalizeSwarmPolicy(input = {}) {
+ const p = input && typeof input === 'object' ? input : {};
+
+ const minConsensus = clamp(num(p.min_consensus) ?? 0.6, 0.05, 1);
+ const maxPerTrade = BigInt(Math.max(1_000_000, Math.round(num(p.max_per_trade_lamports) ?? 50_000_000)));
+ const dailyBudget = BigInt(Math.max(Number(maxPerTrade), Math.round(num(p.daily_budget_lamports) ?? 500_000_000)));
+ const creatorFeeBps = Math.round(clamp(num(p.creator_fee_bps) ?? 0, 0, 2000)); // ≤ 20%
+ const maxMemberShareBps = Math.round(clamp(num(p.max_member_share_bps) ?? 5000, 1000, 10000)); // 10%..100%
+ const stopLoss = clamp(num(p.stop_loss_pct) ?? 35, 1, 95);
+ const takeProfit = num(p.take_profit_pct) != null ? clamp(num(p.take_profit_pct), 5, 100000) : 80;
+ const trailing = num(p.trailing_stop_pct) != null ? clamp(num(p.trailing_stop_pct), 1, 95) : 25;
+ const maxHold = Math.round(clamp(num(p.max_hold_seconds) ?? 3600, 60, 86400));
+ const slippageBps = Math.round(clamp(num(p.slippage_bps) ?? 500, 50, 5000));
+ const firewallLevel = ['block', 'warn', 'off'].includes(p.firewall_level) ? p.firewall_level : 'block';
+ const requireSmartMoney = p.require_smart_money === true;
+ const minSmartMoney = clamp(num(p.min_smart_money_score) ?? 0, 0, 100);
+ const joinOpen = p.join_open !== false; // default open
+ const killThresholdBps = Math.round(clamp(num(p.kill_threshold_bps) ?? 3000, 0, 10000)); // members holding ≥30% can kill
+ const exitPolicy = p.exit_policy === 'wait_to_close' ? 'wait_to_close' : 'settle_at_mark';
+
+ return {
+ min_consensus: minConsensus,
+ max_per_trade_lamports: maxPerTrade.toString(),
+ daily_budget_lamports: dailyBudget.toString(),
+ creator_fee_bps: creatorFeeBps,
+ max_member_share_bps: maxMemberShareBps,
+ require_smart_money: requireSmartMoney,
+ min_smart_money_score: minSmartMoney,
+ stop_loss_pct: stopLoss,
+ take_profit_pct: takeProfit,
+ trailing_stop_pct: trailing,
+ max_hold_seconds: maxHold,
+ slippage_bps: slippageBps,
+ firewall_level: firewallLevel,
+ join_open: joinOpen,
+ kill_threshold_bps: killThresholdBps,
+ exit_policy: exitPolicy,
+ };
+}
+
+export class SwarmError extends Error {
+ constructor(status, code, message) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+// ── on-chain treasury balance ─────────────────────────────────────────────────
+
+/** Live treasury SOL balance in lamports (bigint). The single source of truth. */
+export async function treasuryBalanceLamports(address, network = 'mainnet') {
+ const { PublicKey } = await import('@solana/web3.js');
+ const conn = solanaConnection({ network, commitment: 'confirmed' });
+ const lamports = await conn.getBalance(new PublicKey(address), 'confirmed');
+ return BigInt(lamports);
+}
+
+// ── ownership + loading ────────────────────────────────────────────────────────
+
+/** Assert the user owns the agent; returns the agent row. */
+async function requireOwnedAgent(userId, agentId) {
+ const [agent] = await sql`
+ select id, user_id, name, meta from agent_identities
+ where id = ${agentId} and deleted_at is null limit 1
+ `;
+ if (!agent) throw new SwarmError(404, 'agent_not_found', 'agent not found');
+ if (agent.user_id !== userId) throw new SwarmError(403, 'forbidden', 'not your agent');
+ return agent;
+}
+
+export async function getSwarm(swarmId) {
+ const [row] = await sql`select * from swarms where id = ${swarmId} limit 1`;
+ return row || null;
+}
+
+async function loadTreasuryStrategy(swarm) {
+ const [strat] = await sql`
+ select * from agent_sniper_strategies where id = ${swarm.strategy_id} limit 1
+ `;
+ return strat || null;
+}
+
+// ── create ─────────────────────────────────────────────────────────────────────
+
+/**
+ * Create a swarm: provision a dedicated custodial treasury agent + its sniper
+ * strategy (the trade policy), persist the swarm, and enroll the creator as the
+ * first member. The treasury strategy is created disabled — the consensus engine,
+ * not the new-mint feed, decides when it trades.
+ */
+export async function createSwarm({ userId, ownerAgentId, name, description = null, network = 'mainnet', policy = {} }) {
+ if (!userId) throw new SwarmError(401, 'unauthorized', 'sign in required');
+ const cleanName = String(name || '').trim();
+ if (!cleanName || cleanName.length > 80) throw new SwarmError(400, 'bad_name', 'name must be 1–80 chars');
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const pol = normalizeSwarmPolicy(policy);
+
+ const owner = await requireOwnedAgent(userId, ownerAgentId);
+ await ensureAgentWallet(owner.id, userId, { reason: 'swarm_owner' });
+
+ // Provision the treasury as its own agent (its own custodial Solana wallet).
+ const [treasury] = await sql`
+ insert into agent_identities (user_id, name, description, skills, meta)
+ values (
+ ${userId}, ${`Swarm Treasury · ${cleanName}`.slice(0, 120)},
+ ${`Pooled trading treasury for the “${cleanName}” swarm.`.slice(0, 500)},
+ ${['trade']}, ${JSON.stringify({ swarm_treasury: true })}::jsonb
+ )
+ returning id
+ `;
+ const treasuryWallet = await getOrCreateAgentSolanaWallet(treasury.id);
+
+ // The treasury's sniper strategy: disabled (so the new-mint feed ignores it),
+ // kill_switch off, with the swarm's budget + exit policy. The consensus engine
+ // loads it explicitly and fires buys; the position sweep manages exits.
+ const [strat] = await sql`
+ insert into agent_sniper_strategies
+ (agent_id, user_id, network, enabled, kill_switch, trigger,
+ daily_budget_lamports, per_trade_lamports, max_concurrent_positions,
+ slippage_bps, max_price_impact_pct, mev_tip_mode, firewall_level,
+ require_sol_quote, take_profit_pct, stop_loss_pct, trailing_stop_pct,
+ max_hold_seconds, min_smart_money_score, require_smart_money, updated_at)
+ values
+ (${treasury.id}, ${userId}, ${net}, false, false, 'new_mint',
+ ${pol.daily_budget_lamports}, ${pol.max_per_trade_lamports}, ${8},
+ ${pol.slippage_bps}, ${15}, 'economy', ${pol.firewall_level},
+ true, ${pol.take_profit_pct}, ${pol.stop_loss_pct}, ${pol.trailing_stop_pct},
+ ${pol.max_hold_seconds}, ${pol.min_smart_money_score}, ${pol.require_smart_money}, now())
+ on conflict (agent_id, network) do update set updated_at = now()
+ returning id
+ `;
+
+ const [swarm] = await sql`
+ insert into swarms
+ (owner_user_id, owner_agent_id, treasury_agent_id, strategy_id, name, description, network, status, policy)
+ values
+ (${userId}, ${owner.id}, ${treasury.id}, ${strat.id}, ${cleanName},
+ ${description ? String(description).slice(0, 1000) : null}, ${net}, 'open', ${JSON.stringify(pol)}::jsonb)
+ returning *
+ `;
+
+ // Creator is the first member (zero contribution until they fund).
+ await sql`
+ insert into swarm_members (swarm_id, agent_id, user_id, is_creator, status)
+ values (${swarm.id}, ${owner.id}, ${userId}, true, 'active')
+ on conflict (swarm_id, agent_id) do nothing
+ `;
+
+ await recordCustodyEvent({
+ agentId: treasury.id, userId, eventType: 'limit_change', category: 'swarm_payout',
+ network: net, reason: 'swarm_created',
+ meta: { swarm_id: swarm.id, name: cleanName, treasury: treasuryWallet.address, policy: pol },
+ }).catch(() => {});
+
+ return { ...swarm, treasury_address: treasuryWallet.address };
+}
+
+// ── join ─────────────────────────────────────────────────────────────────────
+
+export async function joinSwarm({ userId, swarmId, agentId }) {
+ const swarm = await getSwarm(swarmId);
+ if (!swarm) throw new SwarmError(404, 'not_found', 'swarm not found');
+ if (['killed', 'closed'].includes(swarm.status)) throw new SwarmError(409, 'closed', 'swarm is closed');
+ const pol = normalizeSwarmPolicy(swarm.policy);
+ if (!pol.join_open && swarm.owner_user_id !== userId) {
+ throw new SwarmError(403, 'invite_only', 'this swarm is invite-only');
+ }
+ const agent = await requireOwnedAgent(userId, agentId);
+ await ensureAgentWallet(agent.id, userId, { reason: 'swarm_join' });
+
+ const [member] = await sql`
+ insert into swarm_members (swarm_id, agent_id, user_id, status)
+ values (${swarm.id}, ${agent.id}, ${userId}, 'active')
+ on conflict (swarm_id, agent_id) do update set
+ status = 'active', exited_at = null, updated_at = now()
+ returning *
+ `;
+ return member;
+}
+
+// ── contribute (real SOL transfer member → treasury) ──────────────────────────
+
+/**
+ * Fund the treasury with real SOL from the member's custodial wallet. Verifies the
+ * member can afford it (keeping a fee buffer), enforces the per-member share cap
+ * BEFORE moving funds, transfers on-chain, then records the net contribution and
+ * recomputes every member's share. Returns the signature + updated member.
+ */
+export async function contributeToSwarm({ userId, swarmId, agentId, lamports }) {
+ const swarm = await getSwarm(swarmId);
+ if (!swarm) throw new SwarmError(404, 'not_found', 'swarm not found');
+ if (['killed', 'closed'].includes(swarm.status)) throw new SwarmError(409, 'closed', 'swarm is closed');
+ const amount = BigInt(lamports || 0);
+ if (amount < MIN_CONTRIBUTION_LAMPORTS) {
+ throw new SwarmError(400, 'too_small', `minimum contribution is ${Number(MIN_CONTRIBUTION_LAMPORTS) / LAMPORTS_PER_SOL} SOL`);
+ }
+
+ const agent = await requireOwnedAgent(userId, agentId);
+ const wallet = await ensureAgentWallet(agent.id, userId, { reason: 'swarm_contribute' });
+
+ // Member must be enrolled (auto-join if open).
+ let [member] = await sql`select * from swarm_members where swarm_id = ${swarm.id} and agent_id = ${agent.id} limit 1`;
+ if (!member || member.status !== 'active') {
+ member = await joinSwarm({ userId, swarmId: swarm.id, agentId: agent.id });
+ }
+
+ const pol = normalizeSwarmPolicy(swarm.policy);
+
+ // Anti-abuse: reject a contribution that would push this member past the cap.
+ const members = await sql`select id, agent_id, contribution_lamports, withdrawn_lamports, status from swarm_members where swarm_id = ${swarm.id} and status = 'active'`;
+ let totalNet = 0n;
+ let memberNet = 0n;
+ for (const m of members) {
+ const net = BigInt(m.contribution_lamports) - BigInt(m.withdrawn_lamports);
+ totalNet += net > 0n ? net : 0n;
+ if (m.agent_id === agent.id) memberNet = net > 0n ? net : 0n;
+ }
+ const prospectiveMember = memberNet + amount;
+ const prospectiveTotal = totalNet + amount;
+ const prospectiveBps = Number((prospectiveMember * BigInt(BPS)) / prospectiveTotal);
+ if (prospectiveBps > pol.max_member_share_bps && members.length > 1) {
+ throw new SwarmError(409, 'share_cap', `that contribution would exceed the per-member cap of ${(pol.max_member_share_bps / 100).toFixed(0)}%`);
+ }
+
+ // Verify on-chain funds (amount + a fee buffer) before signing.
+ const bal = await treasuryBalanceLamports(wallet.address, swarm.network);
+ if (bal < amount + GAS_RESERVE_LAMPORTS) {
+ throw new SwarmError(402, 'insufficient_funds', 'wallet balance too low to fund this contribution');
+ }
+
+ const treasury = await getSwarmTreasuryAddress(swarm);
+ const keypair = await recoverSolanaAgentKeypair(agent.meta?.encrypted_solana_secret, {
+ agentId: agent.id, userId, reason: 'swarm_contribute', meta: { swarm_id: swarm.id },
+ });
+
+ const signature = await transferNativeSol({
+ fromKeypair: keypair, toAddress: treasury, lamports: amount, network: swarm.network,
+ });
+
+ const [updated] = await sql`
+ update swarm_members
+ set contribution_lamports = contribution_lamports + ${amount.toString()},
+ last_fund_sig = ${signature}, updated_at = now()
+ where id = ${member.id}
+ returning *
+ `;
+ await recordCustodyEvent({
+ agentId: agent.id, userId, eventType: 'spend', category: 'swarm_payout',
+ network: swarm.network, asset: 'SOL', amountLamports: amount, destination: treasury,
+ signature, reason: 'swarm_contribution', status: 'confirmed',
+ idempotencyKey: `swarm_contrib:${member.id}:${signature}`,
+ meta: { swarm_id: swarm.id },
+ }).catch(() => {});
+
+ const shares = await recomputeShares(swarm.id);
+ // First real money in flips an 'open' swarm to 'active'.
+ if (swarm.status === 'open') {
+ await sql`update swarms set status = 'active', updated_at = now() where id = ${swarm.id} and status = 'open'`;
+ }
+ return { signature, member: updated, shares };
+}
+
+async function getSwarmTreasuryAddress(swarm) {
+ const wallet = await getOrCreateAgentSolanaWallet(swarm.treasury_agent_id);
+ return wallet.address;
+}
+
+// ── shares ─────────────────────────────────────────────────────────────────────
+
+/**
+ * Recompute every active member's share_bps from net contributions. Caps each
+ * member at the policy's max_member_share_bps and redistributes the overflow
+ * proportionally across the others, so no member can capture the treasury.
+ */
+export async function recomputeShares(swarmId) {
+ const swarm = await getSwarm(swarmId);
+ if (!swarm) return [];
+ const pol = normalizeSwarmPolicy(swarm.policy);
+ const members = await sql`
+ select id, agent_id, contribution_lamports, withdrawn_lamports
+ from swarm_members where swarm_id = ${swarmId} and status = 'active'
+ `;
+ const nets = members.map((m) => {
+ const net = BigInt(m.contribution_lamports) - BigInt(m.withdrawn_lamports);
+ return { id: m.id, net: net > 0n ? Number(net) : 0 };
+ });
+ const total = nets.reduce((a, b) => a + b.net, 0);
+ let bps = {};
+ if (total <= 0) {
+ for (const m of nets) bps[m.id] = 0;
+ } else {
+ // Initial proportional split.
+ for (const m of nets) bps[m.id] = Math.round((m.net / total) * BPS);
+ // Enforce the cap with proportional redistribution of overflow.
+ const cap = pol.max_member_share_bps;
+ const capped = new Set();
+ for (let iter = 0; iter < 8; iter++) {
+ const over = nets.filter((m) => !capped.has(m.id) && bps[m.id] > cap);
+ if (!over.length) break;
+ let overflow = 0;
+ for (const m of over) { overflow += bps[m.id] - cap; bps[m.id] = cap; capped.add(m.id); }
+ const free = nets.filter((m) => !capped.has(m.id));
+ const freeTotal = free.reduce((a, b) => a + bps[b.id], 0);
+ if (freeTotal <= 0) break;
+ for (const m of free) bps[m.id] += Math.round((bps[m.id] / freeTotal) * overflow);
+ }
+ }
+ // Persist.
+ for (const m of nets) {
+ await sql`update swarm_members set share_bps = ${bps[m.id] || 0}, updated_at = now() where id = ${m.id}`;
+ }
+ return members.map((m) => ({ member_id: m.id, agent_id: m.agent_id, share_bps: bps[m.id] || 0 }));
+}
+
+// ── reputation (vote weights) ─────────────────────────────────────────────────
+
+/**
+ * Refresh each active member's cached verified-trader reputation (0..100). This is
+ * the consensus vote weight. Best-effort per member — a member with no track record
+ * keeps a null/zero reputation and votes at the floor weight.
+ */
+export async function refreshMemberReputations(swarmId, network) {
+ const { fetchTraderPositions, computeTraderMetrics } = await import('./trader-stats.js');
+ const members = await sql`select id, agent_id from swarm_members where swarm_id = ${swarmId} and status = 'active'`;
+ const out = [];
+ for (const m of members) {
+ let score = 0;
+ try {
+ const positions = await fetchTraderPositions({ agentId: m.agent_id, network, window: 'all' });
+ score = computeTraderMetrics(positions, { solUsd: null }).score || 0;
+ } catch { /* no track record yet */ }
+ await sql`update swarm_members set reputation = ${score}, reputation_at = now() where id = ${m.id}`;
+ out.push({ member_id: m.id, agent_id: m.agent_id, reputation: score });
+ }
+ return out;
+}
+
+// ── consensus tally (pure) ─────────────────────────────────────────────────────
+
+/**
+ * Reputation-weighted consensus over a candidate mint. `members` is the active
+ * member set (each with agent_id + reputation); `longAgentIds` is the set of
+ * members currently holding a real position in the mint (their on-chain "yes"
+ * vote). Returns the weighted agreement, the conviction used to size the trade,
+ * and a per-member breakdown for the audit log.
+ */
+export function computeConsensus({ members, longAgentIds, smartMoneyScore = 0, policy }) {
+ const longSet = longAgentIds instanceof Set ? longAgentIds : new Set(longAgentIds || []);
+ const weightOf = (rep) => Math.max(MIN_VOTE_WEIGHT, Number(rep) || 0);
+ let totalWeight = 0;
+ let longWeight = 0;
+ const breakdown = [];
+ for (const m of members) {
+ const w = weightOf(m.reputation);
+ const long = longSet.has(m.agent_id);
+ totalWeight += w;
+ if (long) longWeight += w;
+ breakdown.push({ agent_id: m.agent_id, name: m.name || null, reputation: Number(m.reputation) || 0, long, weight: w });
+ }
+ const consensus = totalWeight > 0 ? longWeight / totalWeight : 0;
+ // Smart-money confirmation lifts conviction (0..0.25 bonus) but cannot manufacture
+ // agreement on its own — it scales what the members already voted.
+ const smBonus = clamp((Number(smartMoneyScore) || 0) / 100, 0, 1) * 0.25;
+ const conviction = clamp(consensus * (1 + smBonus), 0, 1);
+ return {
+ consensus,
+ conviction,
+ members_long: breakdown.filter((b) => b.long).length,
+ members_total: members.length,
+ total_weight: totalWeight,
+ long_weight: longWeight,
+ breakdown,
+ };
+}
+
+// ── kill switch ────────────────────────────────────────────────────────────────
+
+/**
+ * Trigger the swarm kill switch. The creator can always kill; any member (or set
+ * of members) holding ≥ policy.kill_threshold_bps of the treasury can too. Halts
+ * new consensus buys and flips kill_switch on the treasury strategy + every open
+ * position so the sweep liquidates them.
+ */
+export async function killSwarm({ userId, swarmId, reason = null }) {
+ const swarm = await getSwarm(swarmId);
+ if (!swarm) throw new SwarmError(404, 'not_found', 'swarm not found');
+ if (swarm.status === 'killed') return swarm;
+ const pol = normalizeSwarmPolicy(swarm.policy);
+
+ const isCreator = swarm.owner_user_id === userId;
+ if (!isCreator) {
+ const rows = await sql`
+ select coalesce(sum(share_bps),0)::int as bps from swarm_members
+ where swarm_id = ${swarm.id} and user_id = ${userId} and status = 'active'
+ `;
+ const callerBps = rows[0]?.bps || 0;
+ if (callerBps < pol.kill_threshold_bps) {
+ throw new SwarmError(403, 'below_threshold', `you hold ${(callerBps / 100).toFixed(1)}% — need ${(pol.kill_threshold_bps / 100).toFixed(0)}% to kill`);
+ }
+ }
+
+ await sql`
+ update swarms set status = 'killed', killed_at = now(), killed_by_user_id = ${userId},
+ kill_reason = ${reason ? String(reason).slice(0, 280) : null}, updated_at = now()
+ where id = ${swarm.id}
+ `;
+ if (swarm.strategy_id) {
+ // Flipping the strategy kill_switch forces every open treasury position to
+ // liquidate on the next sweep: getOpenPositions joins s.kill_switch onto each
+ // position, and positions.js exits any position whose kill_switch is set.
+ await sql`update agent_sniper_strategies set kill_switch = true, enabled = false, updated_at = now() where id = ${swarm.strategy_id}`;
+ }
+
+ await recordCustodyEvent({
+ agentId: swarm.treasury_agent_id, userId, eventType: 'limit_change', category: 'swarm_payout',
+ network: swarm.network, reason: 'swarm_killed', meta: { swarm_id: swarm.id, by: isCreator ? 'creator' : 'member', note: reason || null },
+ }).catch(() => {});
+
+ return await getSwarm(swarm.id);
+}
+
+// ── pause / resume ─────────────────────────────────────────────────────────────
+
+export async function setSwarmPaused({ userId, swarmId, paused }) {
+ const swarm = await getSwarm(swarmId);
+ if (!swarm) throw new SwarmError(404, 'not_found', 'swarm not found');
+ if (swarm.owner_user_id !== userId) throw new SwarmError(403, 'forbidden', 'only the creator can pause');
+ if (swarm.status === 'killed') throw new SwarmError(409, 'killed', 'swarm is killed');
+ const next = paused ? 'paused' : 'active';
+ await sql`update swarms set status = ${next}, updated_at = now() where id = ${swarm.id}`;
+ return await getSwarm(swarm.id);
+}
+
+// ── exit + redeem ──────────────────────────────────────────────────────────────
+
+/**
+ * Net asset value of the treasury in lamports: liquid SOL + the marked value of
+ * its open positions (last quoted value). The basis for settle_at_mark exits.
+ */
+export async function treasuryNavLamports(swarm) {
+ const treasury = await getSwarmTreasuryAddress(swarm);
+ const liquid = await treasuryBalanceLamports(treasury, swarm.network);
+ const [row] = await sql`
+ select coalesce(sum(coalesce(last_value_lamports, entry_quote_lamports, 0)),0)::numeric as marked
+ from agent_sniper_positions
+ where agent_id = ${swarm.treasury_agent_id} and network = ${swarm.network} and status in ('open','opening','closing')
+ `;
+ const marked = BigInt(row?.marked ? String(row.marked).split('.')[0] : '0');
+ return { liquid, marked, nav: liquid + marked, treasury };
+}
+
+/**
+ * Exit a member and redeem their share to their own wallet via a real SOL transfer.
+ *
+ * Open-position policy (explicit):
+ * - settle_at_mark (default): redeem share_bps × treasury NAV (liquid SOL + marked
+ * open-position value), PAID from liquid SOL. If liquid can't cover the marked
+ * portion, the payout is capped to available liquid (minus the fee reserve) and
+ * flagged `capped` — the member is told plainly.
+ * - wait_to_close: exit is refused while the treasury holds open positions; the
+ * member kills or waits for positions to close, then redeems pure liquid SOL.
+ */
+export async function exitSwarm({ userId, swarmId, agentId }) {
+ const swarm = await getSwarm(swarmId);
+ if (!swarm) throw new SwarmError(404, 'not_found', 'swarm not found');
+ const agent = await requireOwnedAgent(userId, agentId);
+ const [member] = await sql`select * from swarm_members where swarm_id = ${swarm.id} and agent_id = ${agent.id} and status = 'active' limit 1`;
+ if (!member) throw new SwarmError(404, 'not_member', 'not an active member of this swarm');
+
+ const pol = normalizeSwarmPolicy(swarm.policy);
+ const dest = await ensureAgentWallet(agent.id, userId, { reason: 'swarm_exit' });
+
+ const openCount = (await sql`
+ select count(*)::int as n from agent_sniper_positions
+ where agent_id = ${swarm.treasury_agent_id} and network = ${swarm.network} and status in ('open','opening','closing')
+ `)[0]?.n || 0;
+
+ if (pol.exit_policy === 'wait_to_close' && openCount > 0 && swarm.status !== 'killed') {
+ throw new SwarmError(409, 'positions_open', 'this swarm settles exits only when no positions are open — wait for them to close or trigger the kill switch');
+ }
+
+ const { liquid, nav, treasury } = await treasuryNavLamports(swarm);
+ const shareBps = BigInt(member.share_bps || 0);
+ const spendable = liquid > GAS_RESERVE_LAMPORTS ? liquid - GAS_RESERVE_LAMPORTS : 0n;
+
+ // Entitlement: share of NAV (settle_at_mark) or share of liquid (wait_to_close).
+ const basis = pol.exit_policy === 'wait_to_close' ? liquid : nav;
+ let redeem = (basis * shareBps) / BigInt(BPS);
+ let capped = false;
+ if (redeem > spendable) { redeem = spendable; capped = true; }
+
+ let signature = null;
+ if (redeem > 0n) {
+ const keypair = await recoverSolanaAgentKeypair(
+ (await sql`select meta from agent_identities where id = ${swarm.treasury_agent_id} limit 1`)[0]?.meta?.encrypted_solana_secret,
+ { agentId: swarm.treasury_agent_id, userId, reason: 'swarm_exit_redeem', meta: { swarm_id: swarm.id, member_id: member.id } },
+ );
+ signature = await transferNativeSol({ fromKeypair: keypair, toAddress: dest.address, lamports: redeem, network: swarm.network });
+
+ await sql`
+ insert into swarm_payouts (swarm_id, member_id, agent_id, kind, amount_lamports, share_bps, destination, signature, status, idempotency_key, meta)
+ values (${swarm.id}, ${member.id}, ${agent.id}, 'exit', ${redeem.toString()}, ${member.share_bps || 0}, ${dest.address}, ${signature}, 'confirmed',
+ ${`swarm_exit:${member.id}`}, ${JSON.stringify({ capped, exit_policy: pol.exit_policy })}::jsonb)
+ on conflict (idempotency_key) do nothing
+ `;
+ await recordCustodyEvent({
+ agentId: swarm.treasury_agent_id, userId, eventType: 'withdraw', category: 'swarm_payout',
+ network: swarm.network, asset: 'SOL', amountLamports: redeem, destination: dest.address,
+ signature, reason: 'swarm_exit_redeem', status: 'confirmed',
+ idempotencyKey: `swarm_exit:${member.id}:${signature}`, meta: { swarm_id: swarm.id, member_id: member.id, capped },
+ }).catch(() => {});
+ }
+
+ await sql`
+ update swarm_members
+ set status = 'exited', exited_at = now(), withdrawn_lamports = withdrawn_lamports + ${redeem.toString()}, share_bps = 0, updated_at = now()
+ where id = ${member.id}
+ `;
+ await recomputeShares(swarm.id);
+
+ return { redeemed_lamports: redeem.toString(), redeemed_sol: Number(redeem) / LAMPORTS_PER_SOL, signature, capped, exit_policy: pol.exit_policy };
+}
+
+// ── settlement: distribute realized profit on closed positions ─────────────────
+
+/**
+ * For one swarm, distribute the realized profit of any newly-closed treasury
+ * positions pro-rata to members by share, minus the creator fee. Principal stays
+ * in the treasury so it keeps trading; only positive realized PnL is paid out.
+ * Idempotent: a position that has any 'profit' payout row is never re-scanned.
+ * Losing/break-even closes write a single zero-amount marker row so they settle
+ * once and don't re-scan forever.
+ *
+ * Returns the number of positions settled and total lamports distributed. Pass a
+ * `transfer` override for tests; defaults to a real on-chain SOL transfer.
+ */
+export async function settleSwarm(swarmId, { transfer = transferNativeSol } = {}) {
+ const swarm = await getSwarm(swarmId);
+ if (!swarm) return { settled: 0, distributed: '0' };
+
+ const pending = await sql`
+ select p.id, p.mint, p.symbol, p.realized_pnl_lamports, p.exit_quote_lamports, p.entry_quote_lamports
+ from agent_sniper_positions p
+ where p.agent_id = ${swarm.treasury_agent_id} and p.network = ${swarm.network}
+ and p.status = 'closed' and p.realized_pnl_lamports is not null
+ and not exists (select 1 from swarm_payouts sp where sp.position_id = p.id and sp.kind = 'profit')
+ order by p.closed_at asc
+ limit 25
+ `;
+ if (!pending.length) return { settled: 0, distributed: '0' };
+
+ const pol = normalizeSwarmPolicy(swarm.policy);
+ let settled = 0;
+ let distributedTotal = 0n;
+ let treasuryKeypair = null;
+
+ for (const pos of pending) {
+ const profit = BigInt(pos.realized_pnl_lamports);
+ // Loss / break-even — record a settled marker (no transfer) and move on.
+ if (profit <= 0n) {
+ await sql`
+ insert into swarm_payouts (swarm_id, position_id, kind, amount_lamports, status, idempotency_key, meta)
+ values (${swarm.id}, ${pos.id}, 'profit', 0, 'confirmed', ${`swarm_profit:${pos.id}:noop`},
+ ${JSON.stringify({ realized_pnl_lamports: pos.realized_pnl_lamports, loss: true, mint: pos.mint })}::jsonb)
+ on conflict (idempotency_key) do nothing
+ `;
+ settled++;
+ continue;
+ }
+
+ // Snapshot member shares at settlement time.
+ const members = await sql`
+ select id, agent_id, user_id, share_bps from swarm_members
+ where swarm_id = ${swarm.id} and status = 'active' and share_bps > 0
+ `;
+ if (!members.length) {
+ await sql`
+ insert into swarm_payouts (swarm_id, position_id, kind, amount_lamports, status, idempotency_key, meta)
+ values (${swarm.id}, ${pos.id}, 'profit', 0, 'confirmed', ${`swarm_profit:${pos.id}:noop`},
+ ${JSON.stringify({ note: 'no_active_members', profit: profit.toString() })}::jsonb)
+ on conflict (idempotency_key) do nothing
+ `;
+ settled++;
+ continue;
+ }
+
+ // Bound distribution to liquid SOL minus the fee reserve.
+ const treasuryAddr = await getSwarmTreasuryAddress(swarm);
+ const liquid = await treasuryBalanceLamports(treasuryAddr, swarm.network);
+ const spendable = liquid > GAS_RESERVE_LAMPORTS ? liquid - GAS_RESERVE_LAMPORTS : 0n;
+ if (spendable <= 0n) break; // nothing to pay with right now — retry next sweep
+
+ let distributable = profit > spendable ? spendable : profit;
+ const fee = (distributable * BigInt(pol.creator_fee_bps)) / BigInt(BPS);
+ const netDistributable = distributable - fee;
+
+ if (!treasuryKeypair) {
+ const meta = (await sql`select meta from agent_identities where id = ${swarm.treasury_agent_id} limit 1`)[0]?.meta;
+ treasuryKeypair = await recoverSolanaAgentKeypair(meta?.encrypted_solana_secret, {
+ agentId: swarm.treasury_agent_id, userId: swarm.owner_user_id, reason: 'swarm_profit_settle', meta: { swarm_id: swarm.id },
+ });
+ }
+
+ // Pro-rata member payouts.
+ for (const m of members) {
+ const amount = (netDistributable * BigInt(m.share_bps)) / BigInt(BPS);
+ if (amount <= 0n) continue;
+ await payoutMember({
+ swarm, position: pos, member: m, amount, kind: 'profit',
+ keypair: treasuryKeypair, transfer,
+ idempotencyKey: `swarm_profit:${pos.id}:${m.id}`,
+ });
+ distributedTotal += amount;
+ }
+
+ // Creator fee → owner agent wallet.
+ if (fee > 0n) {
+ const ownerWallet = await ensureAgentWallet(swarm.owner_agent_id, swarm.owner_user_id, { reason: 'swarm_fee' });
+ await payoutFee({ swarm, position: pos, amount: fee, destination: ownerWallet.address, keypair: treasuryKeypair, transfer });
+ }
+ settled++;
+ }
+
+ return { settled, distributed: distributedTotal.toString() };
+}
+
+async function payoutMember({ swarm, position, member, amount, keypair, transfer, idempotencyKey }) {
+ // Reserve the row first (pending) so a crash mid-transfer is recoverable +
+ // never double-pays (idempotency_key is unique).
+ const inserted = await sql`
+ insert into swarm_payouts (swarm_id, member_id, agent_id, position_id, kind, amount_lamports, share_bps, status, idempotency_key, meta)
+ values (${swarm.id}, ${member.id}, ${member.agent_id}, ${position.id}, 'profit', ${amount.toString()}, ${member.share_bps},
+ 'pending', ${idempotencyKey}, ${JSON.stringify({ mint: position.mint, symbol: position.symbol })}::jsonb)
+ on conflict (idempotency_key) do nothing
+ returning id
+ `;
+ if (!inserted.length) return; // already paid
+
+ const dest = (await sql`select meta from agent_identities where id = ${member.agent_id} limit 1`)[0]?.meta?.solana_address;
+ if (!dest) {
+ await sql`update swarm_payouts set status = 'failed', meta = meta || ${JSON.stringify({ error: 'member_no_wallet' })}::jsonb, updated_at = now() where id = ${inserted[0].id}`;
+ return;
+ }
+ try {
+ const signature = await transfer({ fromKeypair: keypair, toAddress: dest, lamports: amount, network: swarm.network });
+ await sql`update swarm_payouts set status = 'confirmed', signature = ${signature}, destination = ${dest}, updated_at = now() where id = ${inserted[0].id}`;
+ await recordCustodyEvent({
+ agentId: swarm.treasury_agent_id, userId: member.user_id, eventType: 'spend', category: 'swarm_payout',
+ network: swarm.network, asset: 'SOL', amountLamports: amount, destination: dest, signature,
+ reason: 'swarm_profit_payout', status: 'confirmed', idempotencyKey: `${idempotencyKey}:${signature}`,
+ meta: { swarm_id: swarm.id, position_id: position.id, mint: position.mint },
+ }).catch(() => {});
+ } catch (e) {
+ await sql`update swarm_payouts set status = 'failed', meta = meta || ${JSON.stringify({ error: String(e?.message || e).slice(0, 200) })}::jsonb, updated_at = now() where id = ${inserted[0].id}`;
+ }
+}
+
+async function payoutFee({ swarm, position, amount, destination, keypair, transfer }) {
+ const inserted = await sql`
+ insert into swarm_payouts (swarm_id, agent_id, position_id, kind, amount_lamports, status, idempotency_key, destination, meta)
+ values (${swarm.id}, ${swarm.owner_agent_id}, ${position.id}, 'fee', ${amount.toString()}, 'pending', ${`swarm_fee:${position.id}`}, ${destination},
+ ${JSON.stringify({ mint: position.mint })}::jsonb)
+ on conflict (idempotency_key) do nothing
+ returning id
+ `;
+ if (!inserted.length) return;
+ try {
+ const signature = await transfer({ fromKeypair: keypair, toAddress: destination, lamports: amount, network: swarm.network });
+ await sql`update swarm_payouts set status = 'confirmed', signature = ${signature}, updated_at = now() where id = ${inserted[0].id}`;
+ await recordCustodyEvent({
+ agentId: swarm.treasury_agent_id, userId: swarm.owner_user_id, eventType: 'spend', category: 'swarm_payout',
+ network: swarm.network, asset: 'SOL', amountLamports: amount, destination, signature,
+ reason: 'swarm_creator_fee', status: 'confirmed', idempotencyKey: `swarm_fee:${position.id}:${signature}`,
+ meta: { swarm_id: swarm.id, position_id: position.id },
+ }).catch(() => {});
+ } catch (e) {
+ await sql`update swarm_payouts set status = 'failed', meta = meta || ${JSON.stringify({ error: String(e?.message || e).slice(0, 200) })}::jsonb, updated_at = now() where id = ${inserted[0].id}`;
+ }
+}
+
+// ── reads (directory + dashboard) ──────────────────────────────────────────────
+
+/** Directory of open/active swarms with aggregate stats. */
+export async function listSwarms({ network = 'mainnet', status = null, limit = 30, offset = 0 } = {}) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const rows = status
+ ? await sql`
+ select s.*, ${net} as _n from swarms s
+ where s.network = ${net} and s.status = ${status}
+ order by s.created_at desc limit ${limit} offset ${offset}`
+ : await sql`
+ select s.* from swarms s
+ where s.network = ${net} and s.status in ('open','active','paused')
+ order by (s.status = 'active') desc, s.created_at desc limit ${limit} offset ${offset}`;
+ const out = [];
+ for (const s of rows) out.push(await summarizeSwarm(s));
+ return out;
+}
+
+/** Every swarm the user owns or is (or was) a member of, any status — for "My swarms". */
+export async function listSwarmsForUser(userId) {
+ const rows = await sql`
+ select distinct s.* from swarms s
+ left join swarm_members m on m.swarm_id = s.id and m.user_id = ${userId}
+ where s.owner_user_id = ${userId} or m.id is not null
+ order by s.created_at desc
+ limit 100
+ `;
+ const out = [];
+ for (const s of rows) out.push(await summarizeSwarm(s));
+ return out;
+}
+
+async function summarizeSwarm(swarm) {
+ const [agg] = await sql`
+ select count(*) filter (where status = 'active')::int as members,
+ coalesce(sum(contribution_lamports) filter (where status = 'active'),0)::numeric as contributed,
+ coalesce(sum(withdrawn_lamports),0)::numeric as withdrawn
+ from swarm_members where swarm_id = ${swarm.id}
+ `;
+ const [trades] = await sql`
+ select count(*)::int as closed,
+ coalesce(sum(realized_pnl_lamports),0)::numeric as pnl,
+ count(*) filter (where realized_pnl_lamports > 0)::int as wins,
+ count(*) filter (where status in ('open','opening','closing'))::int as open
+ from agent_sniper_positions where agent_id = ${swarm.treasury_agent_id} and network = ${swarm.network}
+ `;
+ const lamports = (v) => (v == null ? 0 : Number(String(v).split('.')[0]) / LAMPORTS_PER_SOL);
+ const closed = Number(trades?.closed || 0);
+ return {
+ id: swarm.id,
+ name: swarm.name,
+ description: swarm.description,
+ network: swarm.network,
+ status: swarm.status,
+ policy: normalizeSwarmPolicy(swarm.policy),
+ members: Number(agg?.members || 0),
+ contributed_sol: lamports(agg?.contributed),
+ closed_trades: closed,
+ open_positions: Number(trades?.open || 0),
+ wins: Number(trades?.wins || 0),
+ win_rate: closed > 0 ? Number(trades.wins) / closed : null,
+ realized_pnl_sol: lamports(trades?.pnl),
+ created_at: swarm.created_at,
+ };
+}
+
+/** Full dashboard state for one swarm: treasury (on-chain), members, positions, votes, payouts. */
+export async function getSwarmState(swarmId, { viewerUserId = null } = {}) {
+ const swarm = await getSwarm(swarmId);
+ if (!swarm) return null;
+ const pol = normalizeSwarmPolicy(swarm.policy);
+ const treasury = await getSwarmTreasuryAddress(swarm);
+
+ const [balance, members, positions, votes, payouts] = await Promise.all([
+ treasuryBalanceLamports(treasury, swarm.network).catch(() => null),
+ sql`
+ select sm.id, sm.agent_id, sm.user_id, sm.contribution_lamports, sm.withdrawn_lamports, sm.share_bps,
+ sm.reputation, sm.status, sm.is_creator, sm.joined_at, ai.name as agent_name, ai.profile_image_url, ai.avatar_url
+ from swarm_members sm join agent_identities ai on ai.id = sm.agent_id
+ where sm.swarm_id = ${swarmId} order by sm.share_bps desc, sm.joined_at asc`,
+ sql`
+ select id, mint, symbol, name, status, exit_reason, entry_quote_lamports, last_value_lamports,
+ realized_pnl_lamports, realized_pnl_pct, opened_at, closed_at, buy_sig, sell_sig
+ from agent_sniper_positions where agent_id = ${swarm.treasury_agent_id} and network = ${swarm.network}
+ order by coalesce(closed_at, opened_at) desc limit 50`,
+ sql`select id, mint, decision, consensus, min_consensus, conviction, size_lamports, members_long, members_total, smart_money_score, breakdown, position_id, reason, created_at
+ from swarm_votes where swarm_id = ${swarmId} order by created_at desc limit 40`,
+ sql`select id, member_id, agent_id, position_id, kind, amount_lamports, share_bps, destination, signature, status, created_at
+ from swarm_payouts where swarm_id = ${swarmId} order by created_at desc limit 60`,
+ ]);
+
+ const sol = (v) => (v == null ? null : Number(String(v).split('.')[0]) / LAMPORTS_PER_SOL);
+ const balLamports = balance == null ? null : balance;
+ const contributed = members.filter((m) => m.status === 'active').reduce((a, m) => a + (Number(m.contribution_lamports) - Number(m.withdrawn_lamports)), 0);
+ const closed = positions.filter((p) => p.status === 'closed');
+ const wins = closed.filter((p) => Number(p.realized_pnl_lamports) > 0).length;
+ const realizedPnl = closed.reduce((a, p) => a + Number(p.realized_pnl_lamports || 0), 0);
+
+ const solscan = (sig) => (!sig || sig === 'SIMULATED' ? null : swarm.network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`);
+
+ return {
+ swarm: {
+ id: swarm.id, name: swarm.name, description: swarm.description, network: swarm.network, status: swarm.status,
+ owner_user_id: swarm.owner_user_id, owner_agent_id: swarm.owner_agent_id, created_at: swarm.created_at,
+ kill_reason: swarm.kill_reason,
+ },
+ policy: pol,
+ is_owner: viewerUserId != null && viewerUserId === swarm.owner_user_id,
+ viewer_member: viewerUserId == null ? null : members.find((m) => m.user_id === viewerUserId && m.status === 'active') || null,
+ treasury: {
+ address: treasury,
+ balance_lamports: balLamports == null ? null : balLamports.toString(),
+ balance_sol: balLamports == null ? null : Number(balLamports) / LAMPORTS_PER_SOL,
+ net_contributed_sol: contributed / LAMPORTS_PER_SOL,
+ explorer: swarm.network === 'devnet' ? `https://solscan.io/account/${treasury}?cluster=devnet` : `https://solscan.io/account/${treasury}`,
+ },
+ track_record: {
+ closed_trades: closed.length, wins, win_rate: closed.length ? wins / closed.length : null,
+ realized_pnl_sol: realizedPnl / LAMPORTS_PER_SOL,
+ open_positions: positions.filter((p) => ['open', 'opening', 'closing'].includes(p.status)).length,
+ },
+ members: members.map((m) => ({
+ id: m.id, agent_id: m.agent_id, name: m.agent_name,
+ image: m.profile_image_url || m.avatar_url || null,
+ contribution_sol: (Number(m.contribution_lamports) - Number(m.withdrawn_lamports)) / LAMPORTS_PER_SOL,
+ share_bps: m.share_bps, reputation: m.reputation == null ? null : Number(m.reputation),
+ status: m.status, is_creator: m.is_creator, joined_at: m.joined_at,
+ })),
+ positions: positions.map((p) => ({
+ id: p.id, mint: p.mint, symbol: p.symbol, name: p.name, status: p.status, exit_reason: p.exit_reason,
+ entry_sol: sol(p.entry_quote_lamports), current_sol: sol(p.last_value_lamports),
+ pnl_sol: p.realized_pnl_lamports == null ? null : sol(p.realized_pnl_lamports), pnl_pct: p.realized_pnl_pct == null ? null : Number(p.realized_pnl_pct),
+ opened_at: p.opened_at, closed_at: p.closed_at, buy_url: solscan(p.buy_sig), sell_url: solscan(p.sell_sig),
+ })),
+ votes: votes.map((v) => ({
+ id: v.id, mint: v.mint, decision: v.decision, consensus: v.consensus, min_consensus: v.min_consensus,
+ conviction: v.conviction, size_sol: sol(v.size_lamports), members_long: v.members_long, members_total: v.members_total,
+ smart_money_score: v.smart_money_score, breakdown: v.breakdown, reason: v.reason, created_at: v.created_at,
+ })),
+ payouts: payouts.map((p) => ({
+ id: p.id, kind: p.kind, amount_sol: sol(p.amount_lamports), share_bps: p.share_bps, status: p.status,
+ agent_id: p.agent_id, destination: p.destination, tx_url: solscan(p.signature), created_at: p.created_at,
+ })),
+ };
+}
diff --git a/api/_lib/tournament-attest.js b/api/_lib/tournament-attest.js
new file mode 100644
index 000000000..1dacb1212
--- /dev/null
+++ b/api/_lib/tournament-attest.js
@@ -0,0 +1,172 @@
+/**
+ * On-chain tournament-standings attestor (server-side).
+ *
+ * At close, the Arena commits the FINAL standings to Solana as a single SPL-Memo
+ * attestation signed by the platform attester, mirrored into `solana_attestations`
+ * (kind `threews.tournament.v1`). Anyone can then verify "these standings were
+ * published by three.ws at this slot" without trusting our database — and each
+ * entrant's underlying PnL is independently re-derivable from the on-chain buy/sell
+ * signatures the standings reference.
+ *
+ * Same best-effort contract as trader-score-attest.js:
+ * - No attester key (ATTEST_AGENT_SECRET_KEY) → throws `attester_key_not_configured`;
+ * the close path catches it and reports the attestation as unavailable rather
+ * than failing the whole close. No fake proof link is ever produced.
+ * - Idempotent per tournament: a second close returns the existing signature
+ * instead of broadcasting a duplicate.
+ */
+
+import { PublicKey, Transaction, TransactionInstruction, sendAndConfirmTransaction } from '@solana/web3.js';
+
+import { sql } from './db.js';
+import { solanaConnection } from './solana/connection.js';
+import { RPC } from './solana-attestations.js';
+import { loadAttesterKeypair } from './attest-event.js';
+
+const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
+export const TOURNAMENT_KIND = 'threews.tournament.v1';
+const TX_TIMEOUT_MS = 15_000;
+// Keep the memo well under Solana's ~1232-byte tx size ceiling: attest the podium
+// (top finishers) on-chain; the full board stays in the DB + is recomputable from
+// the same on-chain trades.
+const MAX_ATTESTED_RANKS = 10;
+
+class TournamentAttestError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.name = 'TournamentAttestError';
+ this.code = code;
+ }
+}
+
+function withTimeout(promise, ms) {
+ let timer;
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(
+ () => reject(Object.assign(new Error(`rpc timeout after ${ms}ms`), { code: 'RPC_TIMEOUT' })),
+ ms,
+ );
+ });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
+
+function isValidPubkey(addr) {
+ try {
+ new PublicKey(addr);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Attest a tournament's final standings on-chain.
+ *
+ * @param {object} p
+ * @param {object} p.tournament the tournament row (id, name, network, scoring, window).
+ * @param {Array} p.standings computeStandings output rows (ranked, with wallet/score).
+ * @param {number} [p.now]
+ * @returns {Promise<{ status:'minted'|'deduped', signature:string, kind:string, subject:string }>}
+ */
+export async function attestTournamentStandings({ tournament, standings, now = Date.now() }) {
+ const network = tournament.network;
+ if (network !== 'mainnet' && network !== 'devnet') {
+ throw new TournamentAttestError('unsupported_network', `unsupported network ${network}`);
+ }
+
+ let attester;
+ try {
+ attester = loadAttesterKeypair();
+ } catch {
+ throw new TournamentAttestError('attester_key_not_configured', 'ATTEST_AGENT_SECRET_KEY is not set.');
+ }
+ const validator = attester.publicKey.toBase58();
+
+ // Idempotency: one attestation per tournament id.
+ const [existing] = await sql`
+ select signature from solana_attestations
+ where kind = ${TOURNAMENT_KIND} and network = ${network}
+ and payload->>'tournament_id' = ${tournament.id}
+ limit 1
+ `;
+ if (existing) {
+ return { status: 'deduped', signature: existing.signature, kind: TOURNAMENT_KIND, subject: validator };
+ }
+
+ const podium = standings
+ .filter((s) => s.rank != null)
+ .slice(0, MAX_ATTESTED_RANKS)
+ .map((s) => ({
+ rank: s.rank,
+ agent_id: s.agent_id,
+ wallet: s.wallet || null,
+ score: s.score_value,
+ realized_pnl_sol: s.metrics?.realized_pnl_sol ?? null,
+ closed: s.in_window_trades,
+ eligible: !!s.eligible,
+ }));
+
+ // Subject (attestation referent): the champion's wallet if it's a valid pubkey,
+ // else the attester itself — the memo still carries the full podium either way.
+ const champ = podium.find((p) => p.wallet && isValidPubkey(p.wallet));
+ const subject = champ ? champ.wallet : validator;
+
+ const payload = {
+ v: 1,
+ kind: TOURNAMENT_KIND,
+ tournament_id: tournament.id,
+ name: tournament.name,
+ network,
+ scoring: tournament.scoring,
+ bracket: tournament.bracket,
+ starts_at: tournament.starts_at,
+ ends_at: tournament.ends_at,
+ ts: Math.floor(now / 1000),
+ entrants: standings.length,
+ podium,
+ source: 'threews.arena',
+ };
+
+ const conn = solanaConnection({ url: RPC[network] || RPC.devnet, commitment: 'confirmed' });
+ const ix = new TransactionInstruction({
+ programId: MEMO_PROGRAM_ID,
+ keys: [
+ { pubkey: attester.publicKey, isSigner: true, isWritable: false },
+ { pubkey: new PublicKey(subject), isSigner: false, isWritable: false },
+ ],
+ data: Buffer.from(JSON.stringify(payload), 'utf8'),
+ });
+
+ let signature;
+ try {
+ signature = await withTimeout(
+ sendAndConfirmTransaction(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),
+ TX_TIMEOUT_MS,
+ );
+ } catch (err) {
+ throw new TournamentAttestError('record_failed', `tournament memo failed: ${err.message}`);
+ }
+
+ try {
+ await sql`
+ insert into solana_attestations (
+ signature, network, slot, block_time, agent_asset, attester, kind, payload, verified
+ ) values (
+ ${signature}, ${network}, null, now(), ${subject}, ${validator},
+ ${TOURNAMENT_KIND}, ${JSON.stringify(payload)}::jsonb, true
+ )
+ on conflict (signature) do nothing
+ `;
+ } catch (err) {
+ if (err?.code !== '23505') throw err;
+ }
+
+ return { status: 'minted', signature, kind: TOURNAMENT_KIND, subject };
+}
+
+export function attestationUrl(sig, network) {
+ if (!sig) return null;
+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;
+}
+
+export { TournamentAttestError };
diff --git a/api/_lib/tournament-engine.js b/api/_lib/tournament-engine.js
new file mode 100644
index 000000000..4271ff823
--- /dev/null
+++ b/api/_lib/tournament-engine.js
@@ -0,0 +1,232 @@
+/**
+ * Tournament engine — the orchestration seam between storage (tournament-store),
+ * the pure scoring layer (tournament-scoring), on-chain attestation, and prize
+ * settlement. The API handlers call into here; nothing here knows about HTTP.
+ *
+ * Responsibilities:
+ * - loadStandings() — fetch entrants + their in-window positions, compute the
+ * live ranked board, and project prize allocation.
+ * - finalizeTournament() — at/after close, freeze the final standings, persist
+ * rank/score/prize per entry, attest the result on-chain,
+ * and flip status to 'closed'. Idempotent and money-free.
+ * - settleNow() — pay the frozen prizes in real $THREE (or report BLOCKED).
+ */
+
+import { sql } from './db.js';
+import { env } from './env.js';
+import { solUsdPrice } from './avatar-wallet.js';
+import {
+ getTournament,
+ listEntries,
+ setTournamentStatus,
+ persistFinalStanding,
+ derivedStatus,
+} from './tournament-store.js';
+import { computeStandings, allocatePrizes } from './tournament-scoring.js';
+import { attestTournamentStandings, attestationUrl, TournamentAttestError } from './tournament-attest.js';
+import { settleTournament, settlementBlockReason } from './tournament-settlement.js';
+
+/** Fetch every entrant's positions opened inside the window, in one query. */
+async function fetchEntrantPositions({ agentIds, network, startIso, endIso }) {
+ if (!agentIds.length) return new Map();
+ const rows = await sql`
+ select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status,
+ p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,
+ p.opened_at, p.closed_at
+ from agent_sniper_positions p
+ where p.network = ${network}
+ and p.agent_id = any(${agentIds}::uuid[])
+ and p.opened_at >= ${startIso} and p.opened_at <= ${endIso}
+ `;
+ const byAgent = new Map(agentIds.map((id) => [id, []]));
+ for (const r of rows) {
+ const arr = byAgent.get(r.agent_id);
+ if (arr) arr.push(r);
+ }
+ return byAgent;
+}
+
+let _solCache = { usd: null, at: 0 };
+async function cachedSolUsd() {
+ const now = Date.now();
+ if (_solCache.usd != null && now - _solCache.at < 60_000) return _solCache.usd;
+ try {
+ const usd = await solUsdPrice();
+ _solCache = { usd, at: now };
+ return usd;
+ } catch {
+ return _solCache.usd;
+ }
+}
+
+/**
+ * Compute the live (or final, if already closed) standings view for a tournament,
+ * including projected prize allocation. Pure-ish: reads DB, never writes.
+ */
+export async function loadStandings(tournament, { now = Date.now() } = {}) {
+ const entries = await listEntries(tournament.id);
+ const agentIds = entries.map((e) => e.agent_id);
+ const startIso = tournament.starts_at;
+ const endIso = new Date(Math.min(now, new Date(tournament.ends_at).getTime())).toISOString();
+ const [positionsByAgent, solUsd] = await Promise.all([
+ fetchEntrantPositions({ agentIds, network: tournament.network, startIso, endIso }),
+ cachedSolUsd(),
+ ]);
+
+ const pairs = entries.map((entry) => ({ entry, positions: positionsByAgent.get(entry.agent_id) || [] }));
+ const computed = computeStandings(tournament, pairs, { solUsd, now });
+
+ // Project prize allocation onto the live board so spectators see what's at stake.
+ const pool = BigInt(tournament.prize_pool_three || 0);
+ const alloc = allocatePrizes(pool, tournament.prize_splits || [], computed.standings);
+ const decimals = env.THREE_TOKEN_DECIMALS;
+ computed.standings = computed.standings.map((s) => {
+ const atomics = alloc.get(s.agent_id) || 0n;
+ return {
+ ...s,
+ // Live board carries the persisted prize once frozen, else the projection.
+ projected_prize_three_atomics: atomics.toString(),
+ projected_prize_three: atomicsToThree(atomics, decimals),
+ persisted_prize_three_atomics: persistedPrize(entries, s.agent_id),
+ settlement_status: settlementOf(entries, s.agent_id),
+ settlement_tx: settlementTxOf(entries, s.agent_id),
+ };
+ });
+
+ return {
+ ...computed,
+ sol_usd: solUsd,
+ prize_pool_three_atomics: pool.toString(),
+ prize_pool_three: atomicsToThree(pool, decimals),
+ prize_splits: tournament.prize_splits || [],
+ };
+}
+
+function persistedPrize(entries, agentId) {
+ const e = entries.find((x) => x.agent_id === agentId);
+ return e ? String(e.prize_three || 0) : '0';
+}
+function settlementOf(entries, agentId) {
+ const e = entries.find((x) => x.agent_id === agentId);
+ return e ? e.settlement_status : 'none';
+}
+function settlementTxOf(entries, agentId) {
+ const e = entries.find((x) => x.agent_id === agentId);
+ return e?.settlement_tx || null;
+}
+
+function atomicsToThree(atomics, decimals) {
+ const a = BigInt(atomics);
+ if (a === 0n) return 0;
+ const div = 10n ** BigInt(decimals);
+ const whole = a / div;
+ const frac = a % div;
+ return Number(`${whole}.${frac.toString().padStart(decimals, '0')}`);
+}
+
+/**
+ * Freeze the final standings for a tournament whose window has ended. Persists each
+ * entry's final rank/score/prize, attests the standings on-chain (best-effort), and
+ * flips status to 'closed'. Idempotent: re-finalizing a closed tournament re-attests
+ * only if no attestation exists yet, and re-persists the same frozen numbers.
+ *
+ * Money-free — prize TRANSFERS happen only in settleNow().
+ *
+ * @returns {{ standings, attestation:{status,signature,url,reason}|null, status }}
+ */
+export async function finalizeTournament(tournament, { now = Date.now() } = {}) {
+ const ended = now >= new Date(tournament.ends_at).getTime();
+ if (!ended) {
+ const err = new Error('tournament window has not ended yet');
+ err.status = 409;
+ err.code = 'not_ended';
+ throw err;
+ }
+
+ // Compute final standings as of the END of the window (clamp now to ends_at).
+ const view = await loadStandings(tournament, { now: new Date(tournament.ends_at).getTime() + 1 });
+
+ // Allocate and freeze prizes (prize bracket only).
+ const pool = BigInt(tournament.prize_pool_three || 0);
+ const alloc =
+ tournament.bracket === 'prize' ? allocatePrizes(pool, tournament.prize_splits || [], view.standings) : new Map();
+
+ for (const s of view.standings) {
+ const prize = alloc.get(s.agent_id) || 0n;
+ await persistFinalStanding({
+ tournamentId: tournament.id,
+ agentId: s.agent_id,
+ rank: s.rank,
+ score: s.score_value,
+ prizeThree: prize,
+ status: s.entry_status,
+ });
+ }
+
+ // Attest on-chain — best-effort, honestly reported.
+ let attestation = null;
+ if (tournament.attestation_sig) {
+ attestation = {
+ status: 'deduped',
+ signature: tournament.attestation_sig,
+ url: attestationUrl(tournament.attestation_sig, tournament.network),
+ };
+ } else {
+ try {
+ const r = await attestTournamentStandings({ tournament, standings: view.standings, now });
+ attestation = { status: r.status, signature: r.signature, url: attestationUrl(r.signature, tournament.network) };
+ await setTournamentStatus(tournament.id, 'closed', {
+ attestationSig: r.signature,
+ attestationKind: r.kind,
+ });
+ } catch (err) {
+ const reason = err instanceof TournamentAttestError ? err.code : 'attestation_failed';
+ attestation = { status: 'unavailable', signature: null, url: null, reason, message: err.message };
+ }
+ }
+
+ // Flip to closed even if attestation was unavailable (standings are still frozen).
+ const updated = await setTournamentStatus(tournament.id, 'closed');
+
+ return { standings: view.standings, attestation, status: updated?.status || 'closed', view };
+}
+
+/**
+ * Pay the frozen prizes. Requires the tournament to be finalized (status closed or
+ * settled). Returns the per-entry settlement outcome; BLOCKED entries are honest.
+ */
+export async function settleNow(tournamentId, { now = Date.now() } = {}) {
+ const tournament = await getTournament(tournamentId);
+ if (!tournament) {
+ const err = new Error('tournament not found');
+ err.status = 404;
+ err.code = 'not_found';
+ throw err;
+ }
+ if (!['closed', 'settled'].includes(tournament.status)) {
+ const err = new Error(`tournament is ${tournament.status}, not finalized — close it first`);
+ err.status = 409;
+ err.code = 'not_finalized';
+ throw err;
+ }
+ const entries = await listEntries(tournamentId);
+ const result = await settleTournament(tournament, entries);
+
+ // If every prize is settled (none left pending/blocked among winners), mark the
+ // tournament settled. A blocked environment leaves it 'closed' so a later retry
+ // (once the wallet is funded) can finish the job.
+ const refreshed = await listEntries(tournamentId);
+ const winners = refreshed.filter((e) => BigInt(e.prize_three || 0) > 0n && e.status !== 'withdrawn');
+ const allPaid = winners.length > 0 && winners.every((e) => e.settlement_status === 'settled');
+ if (allPaid) await setTournamentStatus(tournamentId, 'settled');
+
+ return {
+ ...result,
+ block_reason: settlementBlockReason(tournament.network),
+ status: allPaid ? 'settled' : tournament.status,
+ };
+}
+
+/** Expose the time-derived lifecycle for handlers that need it. */
+export { derivedStatus };
diff --git a/api/_lib/tournament-scoring.js b/api/_lib/tournament-scoring.js
new file mode 100644
index 000000000..455fbfb87
--- /dev/null
+++ b/api/_lib/tournament-scoring.js
@@ -0,0 +1,240 @@
+/**
+ * Tournament scoring engine — PURE. No DB, no network.
+ *
+ * Deterministic over an array of {entry, positions} pairs, exactly like
+ * computeTraderMetrics is deterministic over positions. This is what the tests pin
+ * and what guarantees the live board, the SSE stream, and the final attested
+ * standings can never disagree.
+ *
+ * The fairness rules, baked in and honest:
+ * 1. WINDOW SCOPING — only positions OPENED inside [starts_at, min(now, ends_at)]
+ * count. A pre-window winner can't be carried in; a position opened after the
+ * bell can't pad the score.
+ * 2. REAL-TRADE GATE (prize bracket) — simulated/paper positions (no real buy
+ * signature) are excluded from prize scoring. They are the practice bracket's
+ * domain, clearly labelled, and never earn $THREE.
+ * 3. VERIFICATION GATES — the same min-closed / min-unique-coins / max-churn gates
+ * the verification badge uses decide PRIZE ELIGIBILITY. Ineligible entrants are
+ * still ranked and shown; they just can't win a prize.
+ * 4. CHURN HEURISTIC, NAMED AS SUCH — we flag high-churn/single-coin entries as
+ * wash-suspected. We do NOT claim counterparty wash detection we can't do from
+ * one-sided position data (same honesty rule as trader-stats.js); the on-chain
+ * buy/sell signatures are the real integrity guarantee.
+ *
+ * All metric arithmetic defers to computeTraderMetrics so there is one truth layer.
+ */
+
+import { computeTraderMetrics } from './trader-stats.js';
+
+/** Default prize-eligibility gates; a tournament's entry_rules override these. */
+export const DEFAULT_GATES = { min_closed: 3, min_unique_coins: 2, max_churn_pct: 60 };
+
+/** A position is a REAL on-chain trade iff it carries a genuine buy signature. */
+export function isRealTrade(p) {
+ const sig = p.buy_sig;
+ return !!sig && sig !== 'SIMULATED';
+}
+
+/**
+ * Filter a trader's positions to the ones that count for a tournament:
+ * - opened strictly within the window (open time, not close time — fairness rule 1)
+ * - for a 'prize' bracket, real on-chain trades only (fairness rule 2)
+ */
+export function filterWindowPositions(positions, { startIso, endIso, bracket = 'prize' }) {
+ const start = new Date(startIso).getTime();
+ const end = new Date(endIso).getTime();
+ return positions.filter((p) => {
+ const opened = new Date(p.opened_at).getTime();
+ if (!(opened >= start && opened <= end)) return false;
+ if (bracket === 'prize' && !isRealTrade(p)) return false;
+ return true;
+ });
+}
+
+/** Resolve the gates for a tournament, merging its entry_rules over the defaults. */
+export function resolveGates(tournament) {
+ const r = tournament?.entry_rules || {};
+ return {
+ min_closed: numOr(r.min_closed, DEFAULT_GATES.min_closed),
+ min_unique_coins: numOr(r.min_unique_coins, DEFAULT_GATES.min_unique_coins),
+ max_churn_pct: numOr(r.max_churn_pct, DEFAULT_GATES.max_churn_pct),
+ };
+}
+
+function numOr(v, d) {
+ const n = Number(v);
+ return Number.isFinite(n) && n >= 0 ? n : d;
+}
+
+/** Map a metric set to the single number a tournament ranks on. */
+export function scoreValue(metrics, scoring) {
+ switch (scoring) {
+ case 'realized_pnl':
+ return metrics.realized_pnl_sol;
+ case 'roi_pct':
+ return metrics.roi_pct;
+ case 'score':
+ default:
+ return metrics.score;
+ }
+}
+
+/**
+ * Evaluate prize eligibility + anti-cheat flags for one entry's window metrics.
+ * Returns { eligible, reasons:[], wash_suspected }.
+ */
+export function evaluateEligibility({ metrics, gates, bracket, realTrades }) {
+ const reasons = [];
+ if (bracket === 'practice') reasons.push('practice_bracket');
+ if (metrics.closed_count < gates.min_closed) reasons.push(`min_closed_${gates.min_closed}`);
+ if (metrics.unique_coins < gates.min_unique_coins) reasons.push(`min_unique_coins_${gates.min_unique_coins}`);
+ if (metrics.churn_pct > gates.max_churn_pct) reasons.push(`churn_over_${gates.max_churn_pct}`);
+ if (bracket === 'prize' && realTrades === 0) reasons.push('no_real_trades');
+
+ // Churn-based wash heuristic (NOT counterparty wash detection — see header).
+ const wash_suspected =
+ metrics.closed_count >= 4 &&
+ metrics.unique_coins <= 1 &&
+ metrics.churn_pct >= gates.max_churn_pct;
+ if (wash_suspected) reasons.push('wash_suspected');
+
+ const eligible = bracket === 'prize' && reasons.length === 0;
+ return { eligible, reasons, wash_suspected };
+}
+
+/**
+ * Allocate the prize pool across the eligible, ranked standings per prize_splits
+ * (basis points by rank). Returns Map(agentId -> prizeAtomics:bigint). Splits that
+ * land on an ineligible/absent rank go UNALLOCATED — we never reassign a prize the
+ * structure didn't promise.
+ *
+ * @param {bigint} poolAtomics prize pool in $THREE base units
+ * @param {Array} splits [{rank, bps}, …]
+ * @param {Array} ranked standings already sorted, each {agent_id, rank, eligible}
+ */
+export function allocatePrizes(poolAtomics, splits, ranked) {
+ const out = new Map();
+ if (!poolAtomics || poolAtomics <= 0n || !Array.isArray(splits)) return out;
+ const byRank = new Map(ranked.map((s) => [s.rank, s]));
+ for (const split of splits) {
+ const rank = Number(split?.rank);
+ const bps = Number(split?.bps);
+ if (!Number.isInteger(rank) || !Number.isFinite(bps) || bps <= 0) continue;
+ const s = byRank.get(rank);
+ if (!s || !s.eligible) continue; // unallocated — honest, not redistributed
+ const amount = (poolAtomics * BigInt(Math.round(bps))) / 10000n;
+ if (amount > 0n) out.set(s.agent_id, (out.get(s.agent_id) || 0n) + amount);
+ }
+ return out;
+}
+
+/**
+ * Compute the full live standings for a tournament.
+ *
+ * @param {object} tournament tournament row (scoring, bracket, entry_rules, window)
+ * @param {Array} pairs [{ entry, positions }] — entry rows joined to identity,
+ * positions are that agent's raw agent_sniper_positions
+ * @param {object} [opts]
+ * @param {number|null} [opts.solUsd]
+ * @param {number} [opts.now] injectable clock
+ * @returns {{ standings: Array, scoring, bracket, window: {start,end}, computed_at }}
+ */
+export function computeStandings(tournament, pairs, { solUsd = null, now = Date.now() } = {}) {
+ const startIso = tournament.starts_at;
+ const endIso = new Date(Math.min(now, new Date(tournament.ends_at).getTime())).toISOString();
+ const gates = resolveGates(tournament);
+ const bracket = tournament.bracket || 'prize';
+ const scoring = tournament.scoring || 'score';
+
+ const rows = pairs.map(({ entry, positions }) => {
+ const windowPositions = filterWindowPositions(positions, { startIso, endIso, bracket });
+ const realTrades = windowPositions.filter(isRealTrade).length;
+ const metrics = computeTraderMetrics(windowPositions, { solUsd });
+ const elig = evaluateEligibility({ metrics, gates, bracket, realTrades });
+ const value = scoreValue(metrics, scoring);
+ return {
+ agent_id: entry.agent_id,
+ agent_name: entry.agent_name || null,
+ image: entry.profile_image_url || entry.avatar_url || null,
+ glb_url: entry.avatar_url || null,
+ wallet: entry.wallet || null,
+ joined_at: entry.joined_at,
+ entry_status: entry.status,
+ score_value: round(value),
+ metrics: summarize(metrics),
+ eligible: elig.eligible && entry.status === 'active',
+ ineligible_reasons: elig.reasons,
+ wash_suspected: elig.wash_suspected,
+ in_window_trades: metrics.closed_count,
+ open_window_trades: metrics.open_count,
+ sample_trades: sampleTrades(windowPositions, tournament.network),
+ };
+ });
+
+ // Withdrawn entries fall out of the ranking entirely; disqualified sink to the
+ // bottom. Everyone else is ranked by the tournament's score, descending, with a
+ // stable realized-PnL → closed-count tiebreak.
+ const active = rows.filter((r) => r.entry_status !== 'withdrawn');
+ active.sort((a, b) => {
+ const aDq = a.entry_status === 'disqualified' ? 1 : 0;
+ const bDq = b.entry_status === 'disqualified' ? 1 : 0;
+ if (aDq !== bDq) return aDq - bDq;
+ return (
+ b.score_value - a.score_value ||
+ b.metrics.realized_pnl_sol - a.metrics.realized_pnl_sol ||
+ b.in_window_trades - a.in_window_trades
+ );
+ });
+ const standings = active.map((r, i) => ({ rank: r.entry_status === 'disqualified' ? null : i + 1, ...r }));
+
+ return {
+ standings,
+ scoring,
+ bracket,
+ gates,
+ window: { start: startIso, end: tournament.ends_at },
+ computed_at: now,
+ };
+}
+
+function summarize(m) {
+ return {
+ score: m.score,
+ verified: m.verified,
+ realized_pnl_sol: m.realized_pnl_sol,
+ realized_pnl_usd: m.realized_pnl_usd,
+ roi_pct: m.roi_pct,
+ win_rate: m.win_rate,
+ closed_count: m.closed_count,
+ wins: m.wins,
+ losses: m.losses,
+ unique_coins: m.unique_coins,
+ churn_pct: m.churn_pct,
+ max_drawdown_pct: m.max_drawdown_pct,
+ best_pnl_pct: m.best_pnl_pct,
+ };
+}
+
+function sampleTrades(positions, network) {
+ return [...positions]
+ .filter((p) => p.status === 'closed')
+ .sort((a, b) => new Date(b.closed_at || b.opened_at) - new Date(a.closed_at || a.opened_at))
+ .slice(0, 3)
+ .map((p) => ({
+ mint: p.mint,
+ symbol: p.symbol,
+ pnl_sol: p.realized_pnl_lamports != null ? Number(BigInt(p.realized_pnl_lamports)) / 1e9 : null,
+ pnl_pct: p.realized_pnl_pct != null ? Number(p.realized_pnl_pct) : null,
+ closed_at: p.closed_at,
+ tx_url: txUrl(p.sell_sig || p.buy_sig, network),
+ }));
+}
+
+function txUrl(sig, network) {
+ if (!sig || sig === 'SIMULATED') return null;
+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;
+}
+
+function round(n) {
+ return Number.isFinite(n) ? Number(n.toFixed(4)) : 0;
+}
diff --git a/api/_lib/tournament-settlement.js b/api/_lib/tournament-settlement.js
new file mode 100644
index 000000000..446e9e5aa
--- /dev/null
+++ b/api/_lib/tournament-settlement.js
@@ -0,0 +1,142 @@
+/**
+ * $THREE prize settlement for the Arena.
+ *
+ * Prizes are $THREE only (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump). Each
+ * winning entry is paid from the platform prize wallet with a REAL on-chain SPL
+ * transfer (reusing the audited transferSolanaUSDC helper — it's mint-generic), and
+ * the resulting tx is recorded against the entry for idempotency and audit.
+ *
+ * Honest accounting is a hard requirement:
+ * - If the prize wallet isn't configured in this environment, settlement does NOT
+ * fake a payout. It records the entry as BLOCKED(payout_unconfigured) with the
+ * exact unblock step, and the tournament still ran and ranked.
+ * - Settlement is idempotent: an entry already 'settled' is never paid twice (the
+ * store's compare-and-set + the unique settlement_tx index enforce it).
+ * - Devnet tournaments never pay real $THREE — that would be meaningless — so they
+ * report BLOCKED(devnet_no_prizes).
+ */
+
+import bs58 from 'bs58';
+
+import { transferSolanaUSDC } from './solana-transfer.js';
+import { env } from './env.js';
+import { recordSettlement } from './tournament-store.js';
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+/**
+ * Resolve the prize payout wallet as a Base58 64-byte secret, from the dedicated
+ * THREE_PRIZE_PAYOUT_KEY (Base58 or base64) or the existing base64 club treasury
+ * secret. Returns null when nothing is configured.
+ */
+function resolvePrizeKeyBase58() {
+ const dedicated = env.THREE_PRIZE_PAYOUT_KEY;
+ if (dedicated && dedicated.trim()) {
+ const s = dedicated.trim();
+ try {
+ if (bs58.decode(s).length === 64) return s;
+ } catch {
+ /* not Base58 — try base64 below */
+ }
+ try {
+ const raw = Buffer.from(s, 'base64');
+ if (raw.byteLength === 64) return bs58.encode(raw);
+ } catch {
+ /* ignore */
+ }
+ }
+ const clubB64 = process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64;
+ if (clubB64) {
+ try {
+ const raw = Buffer.from(clubB64, 'base64');
+ if (raw.byteLength === 64) return bs58.encode(raw);
+ } catch {
+ /* ignore */
+ }
+ }
+ return null;
+}
+
+/** True when the platform can actually pay $THREE prizes. */
+export function prizeWalletConfigured() {
+ return !!resolvePrizeKeyBase58();
+}
+
+/** Why settlement is blocked in this environment, or null if it can run. */
+export function settlementBlockReason(network) {
+ if (network === 'devnet') return 'devnet_no_prizes';
+ if (!resolvePrizeKeyBase58()) return 'payout_unconfigured';
+ return null;
+}
+
+/**
+ * Settle a tournament's prizes. Pays every entry that has prize_three > 0 and isn't
+ * already settled, recording the outcome per entry. Never throws on an individual
+ * payout failure — it records that entry as blocked with the reason and continues,
+ * so one bad recipient can't strand the rest.
+ *
+ * @param {object} tournament the tournament row (id, network)
+ * @param {Array} entries tournament_entries rows (with prize_three, wallet, settlement_status)
+ * @returns {Promise<{ settled:number, blocked:number, skipped:number, results:Array }>}
+ */
+export async function settleTournament(tournament, entries) {
+ const network = tournament.network;
+ const mint = env.THREE_TOKEN_MINT;
+ const blockAll = settlementBlockReason(network);
+
+ const winners = entries.filter((e) => BigInt(e.prize_three || 0) > 0n && e.status !== 'withdrawn');
+ const results = [];
+ let settled = 0,
+ blocked = 0,
+ skipped = 0;
+
+ const fromWallet = blockAll ? null : resolvePrizeKeyBase58();
+
+ for (const e of winners) {
+ if (e.settlement_status === 'settled' && e.settlement_tx) {
+ skipped += 1;
+ results.push({ agent_id: e.agent_id, status: 'settled', tx: e.settlement_tx, alreadyPaid: true });
+ continue;
+ }
+
+ // Environment-level block (devnet / no wallet) — honest, with the unblock step.
+ if (blockAll) {
+ const note =
+ blockAll === 'payout_unconfigured'
+ ? 'prize wallet unconfigured — set THREE_PRIZE_PAYOUT_KEY (Base58 64-byte secret holding $THREE)'
+ : 'devnet tournaments do not pay real $THREE prizes';
+ await recordSettlement({ tournamentId: tournament.id, agentId: e.agent_id, status: 'blocked', note });
+ blocked += 1;
+ results.push({ agent_id: e.agent_id, status: 'blocked', reason: blockAll, note });
+ continue;
+ }
+
+ // Per-entry guard: a missing/invalid wallet can't be paid — block just this one.
+ if (!BASE58_RE.test(String(e.wallet || ''))) {
+ const note = 'entry has no valid Solana wallet to receive the prize';
+ await recordSettlement({ tournamentId: tournament.id, agentId: e.agent_id, status: 'blocked', note });
+ blocked += 1;
+ results.push({ agent_id: e.agent_id, status: 'blocked', reason: 'invalid_wallet', note });
+ continue;
+ }
+
+ try {
+ const tx = await transferSolanaUSDC({
+ fromWallet,
+ toAddress: e.wallet,
+ amount: BigInt(e.prize_three),
+ mint,
+ });
+ await recordSettlement({ tournamentId: tournament.id, agentId: e.agent_id, status: 'settled', tx });
+ settled += 1;
+ results.push({ agent_id: e.agent_id, status: 'settled', tx, amount_atomics: String(e.prize_three) });
+ } catch (err) {
+ const note = `prize transfer failed: ${err?.message || 'unknown error'}`;
+ await recordSettlement({ tournamentId: tournament.id, agentId: e.agent_id, status: 'blocked', note });
+ blocked += 1;
+ results.push({ agent_id: e.agent_id, status: 'blocked', reason: 'transfer_failed', note });
+ }
+ }
+
+ return { settled, blocked, skipped, results };
+}
diff --git a/api/_lib/tournament-store.js b/api/_lib/tournament-store.js
new file mode 100644
index 000000000..90ffa34c6
--- /dev/null
+++ b/api/_lib/tournament-store.js
@@ -0,0 +1,259 @@
+/**
+ * Tournament store — the persistence layer for the Social Trading Arena.
+ *
+ * Mirrors the lazy-ensure pattern used across the codebase (see diorama-store.js):
+ * the tables are created on first use so the Arena self-heals in any environment,
+ * and the canonical schema also ships as a migration
+ * (migrations/20260623120000_tournaments.sql) for production.
+ *
+ * This module owns ONLY storage + lifecycle state transitions. All scoring lives
+ * in tournament-scoring.js (pure), attestation in tournament-attest.js, and prize
+ * settlement in tournament-settlement.js — so each layer stays independently
+ * testable and the truth math is never duplicated.
+ */
+
+import { sql } from './db.js';
+
+let _ensured = null;
+
+/** Create the tournament tables + indexes once per process. Idempotent. */
+export function ensureTournamentTables() {
+ if (_ensured) return _ensured;
+ _ensured = (async () => {
+ await sql`
+ create table if not exists tournaments (
+ id uuid primary key default gen_random_uuid(),
+ name text not null check (length(name) between 1 and 120),
+ description text,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ scoring text not null default 'score' check (scoring in ('score','realized_pnl','roi_pct')),
+ bracket text not null default 'prize' check (bracket in ('prize','practice')),
+ starts_at timestamptz not null,
+ ends_at timestamptz not null,
+ entry_rules jsonb not null default '{}'::jsonb,
+ prize_pool_three numeric(40, 0) not null default 0,
+ prize_splits jsonb not null default '[]'::jsonb,
+ status text not null default 'upcoming'
+ check (status in ('draft','upcoming','live','closed','settled','cancelled')),
+ attestation_sig text,
+ attestation_kind text,
+ created_by uuid,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint tournaments_window_ordered check (ends_at > starts_at),
+ constraint tournaments_prize_nonneg check (prize_pool_three >= 0)
+ )
+ `;
+ await sql`create index if not exists tournaments_status_start_idx on tournaments (status, starts_at desc)`;
+ await sql`create index if not exists tournaments_network_end_idx on tournaments (network, ends_at desc)`;
+ await sql`
+ create table if not exists tournament_entries (
+ id uuid primary key default gen_random_uuid(),
+ tournament_id uuid not null references tournaments(id) on delete cascade,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ wallet text,
+ joined_at timestamptz not null default now(),
+ starting_snapshot jsonb not null default '{}'::jsonb,
+ status text not null default 'active'
+ check (status in ('active','disqualified','withdrawn')),
+ dq_reason text,
+ final_rank int,
+ final_score numeric,
+ prize_three numeric(40, 0) not null default 0,
+ settlement_status text not null default 'none'
+ check (settlement_status in ('none','pending','settled','blocked')),
+ settlement_tx text,
+ settlement_note text,
+ settled_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (tournament_id, agent_id)
+ )
+ `;
+ await sql`create index if not exists tournament_entries_tid_idx on tournament_entries (tournament_id)`;
+ await sql`create index if not exists tournament_entries_agent_idx on tournament_entries (agent_id)`;
+ await sql`
+ create unique index if not exists tournament_entries_settlement_tx_uniq
+ on tournament_entries (settlement_tx) where settlement_tx is not null
+ `;
+ return true;
+ })().catch((err) => {
+ console.error('[tournament-store] ensureTournamentTables failed:', err?.message);
+ _ensured = null;
+ throw err;
+ });
+ return _ensured;
+}
+
+/**
+ * Derive the lifecycle status a tournament SHOULD be in for a given clock, without
+ * mutating anything. 'closed'/'settled'/'cancelled' are terminal and pass through;
+ * the rest are time-derived so a row never looks 'upcoming' after it has started.
+ */
+export function derivedStatus(row, now = Date.now()) {
+ if (['closed', 'settled', 'cancelled', 'draft'].includes(row.status)) return row.status;
+ const start = new Date(row.starts_at).getTime();
+ const end = new Date(row.ends_at).getTime();
+ if (now >= end) return 'ended'; // past the window but not yet finalized on-chain
+ if (now >= start) return 'live';
+ return 'upcoming';
+}
+
+/** Coarse phase for the UI/filter layer: upcoming | live | finished. */
+export function phaseOf(row, now = Date.now()) {
+ const d = derivedStatus(row, now);
+ if (d === 'upcoming' || d === 'draft') return 'upcoming';
+ if (d === 'live') return 'live';
+ return 'finished'; // ended | closed | settled | cancelled
+}
+
+export async function createTournament(input) {
+ await ensureTournamentTables();
+ const [row] = await sql`
+ insert into tournaments (
+ name, description, network, scoring, bracket,
+ starts_at, ends_at, entry_rules, prize_pool_three, prize_splits, status, created_by
+ ) values (
+ ${input.name}, ${input.description ?? null}, ${input.network}, ${input.scoring}, ${input.bracket},
+ ${input.starts_at}, ${input.ends_at}, ${JSON.stringify(input.entry_rules ?? {})}::jsonb,
+ ${String(input.prize_pool_three ?? 0)}, ${JSON.stringify(input.prize_splits ?? [])}::jsonb,
+ ${input.status ?? 'upcoming'}, ${input.created_by ?? null}
+ )
+ returning *
+ `;
+ return row;
+}
+
+export async function getTournament(id) {
+ await ensureTournamentTables();
+ const [row] = await sql`select * from tournaments where id = ${id} limit 1`;
+ return row || null;
+}
+
+/**
+ * List tournaments, newest window first. The coarse `phase` (upcoming|live|finished)
+ * is derived from `now` in JS after the fetch, so the list never lags the clock the
+ * way a stored status would; `phase` filters that derived value.
+ */
+export async function listTournaments({ network = null, phase = null, limit = 60, now = Date.now() } = {}) {
+ await ensureTournamentTables();
+ const rows = await sql`
+ select t.*,
+ (select count(*)::int from tournament_entries e
+ where e.tournament_id = t.id and e.status <> 'withdrawn') as entrant_count
+ from tournaments t
+ where (${network}::text is null or t.network = ${network})
+ order by t.starts_at desc
+ limit ${Math.min(Math.max(limit, 1), 200)}
+ `;
+ const withPhase = rows.map((r) => ({ ...r, phase: phaseOf(r, now), derived_status: derivedStatus(r, now) }));
+ return phase ? withPhase.filter((r) => r.phase === phase) : withPhase;
+}
+
+/** Entries for a tournament, joined to identity for rendering (name/image/glb/wallet). */
+export async function listEntries(tournamentId) {
+ await ensureTournamentTables();
+ return sql`
+ select e.*,
+ a.name as agent_name,
+ a.profile_image_url, a.avatar_url, a.is_public
+ from tournament_entries e
+ join agent_identities a on a.id = e.agent_id
+ where e.tournament_id = ${tournamentId}
+ order by e.joined_at asc
+ `;
+}
+
+export async function getEntry(tournamentId, agentId) {
+ await ensureTournamentTables();
+ const [row] = await sql`
+ select * from tournament_entries
+ where tournament_id = ${tournamentId} and agent_id = ${agentId} limit 1
+ `;
+ return row || null;
+}
+
+/**
+ * Join a tournament. Idempotent on (tournament_id, agent_id): a re-join returns the
+ * existing row untouched (the original baseline snapshot stands). Stores the
+ * join-time wallet + all-time metrics snapshot so window scoping is auditable.
+ */
+export async function joinTournament({ tournamentId, agentId, wallet, snapshot }) {
+ await ensureTournamentTables();
+ const [row] = await sql`
+ insert into tournament_entries (tournament_id, agent_id, wallet, starting_snapshot)
+ values (${tournamentId}, ${agentId}, ${wallet ?? null}, ${JSON.stringify(snapshot ?? {})}::jsonb)
+ on conflict (tournament_id, agent_id) do nothing
+ returning *
+ `;
+ if (row) return { entry: row, created: true };
+ const existing = await getEntry(tournamentId, agentId);
+ return { entry: existing, created: false };
+}
+
+export async function withdrawEntry(tournamentId, agentId) {
+ await ensureTournamentTables();
+ const [row] = await sql`
+ update tournament_entries
+ set status = 'withdrawn', updated_at = now()
+ where tournament_id = ${tournamentId} and agent_id = ${agentId} and status = 'active'
+ returning *
+ `;
+ return row || null;
+}
+
+/** Mark the tournament status (and optional attestation) atomically. */
+export async function setTournamentStatus(id, status, { attestationSig, attestationKind } = {}) {
+ await ensureTournamentTables();
+ const [row] = await sql`
+ update tournaments
+ set status = ${status},
+ attestation_sig = coalesce(${attestationSig ?? null}, attestation_sig),
+ attestation_kind = coalesce(${attestationKind ?? null}, attestation_kind),
+ updated_at = now()
+ where id = ${id}
+ returning *
+ `;
+ return row || null;
+}
+
+/** Persist a computed final standing for one entry (rank, score, allocated prize). */
+export async function persistFinalStanding({ tournamentId, agentId, rank, score, prizeThree, status, dqReason }) {
+ await ensureTournamentTables();
+ const [row] = await sql`
+ update tournament_entries
+ set final_rank = ${rank ?? null},
+ final_score = ${score ?? null},
+ prize_three = ${String(prizeThree ?? 0)},
+ status = ${status ?? 'active'},
+ dq_reason = ${dqReason ?? null},
+ settlement_status = case
+ when ${String(prizeThree ?? 0)}::numeric > 0 then 'pending'
+ else settlement_status end,
+ updated_at = now()
+ where tournament_id = ${tournamentId} and agent_id = ${agentId}
+ returning *
+ `;
+ return row || null;
+}
+
+/**
+ * Record the outcome of a prize settlement attempt for one entry. `settled` carries
+ * a real tx; `blocked` carries an honest reason (e.g. payout wallet unconfigured) and
+ * never a fake proof. Idempotent: a row already 'settled' is left untouched.
+ */
+export async function recordSettlement({ tournamentId, agentId, status, tx, note }) {
+ await ensureTournamentTables();
+ const [row] = await sql`
+ update tournament_entries
+ set settlement_status = ${status},
+ settlement_tx = coalesce(${tx ?? null}, settlement_tx),
+ settlement_note = ${note ?? null},
+ settled_at = case when ${status} = 'settled' then now() else settled_at end,
+ updated_at = now()
+ where tournament_id = ${tournamentId} and agent_id = ${agentId}
+ and settlement_status <> 'settled'
+ returning *
+ `;
+ return row || null;
+}
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 674fdbd9e..7fef400ad 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -72,6 +72,16 @@ export default wrap(async function handler(req, res) {
return mod.default(req, res, id, action);
}
+ if (sub === 'copilot') {
+ const mod = await import('./copilot.js');
+ return mod.default(req, res, id, action);
+ }
+
+ if (sub === 'portfolio') {
+ const mod = await import('./portfolio.js');
+ return mod.default(req, res, id, action);
+ }
+
if (sub === 'autopilot') {
const mod = await import('./autopilot.js');
return mod.default(req, res, id, action);
@@ -92,6 +102,11 @@ export default wrap(async function handler(req, res) {
return mod.default(req, res, id, action);
}
+ if (sub === 'orders') {
+ const mod = await import('./orders.js');
+ return mod.default(req, res, id, action);
+ }
+
if (sub === 'eth-vanity') {
const mod = await import('./eth-vanity.js');
return mod.default(req, res, id, action);
diff --git a/api/agents/copilot.js b/api/agents/copilot.js
new file mode 100644
index 000000000..cc62d50bf
--- /dev/null
+++ b/api/agents/copilot.js
@@ -0,0 +1,585 @@
+// /api/agents/:id/copilot — the Conversational Trading Copilot.
+//
+// A tool-calling LLM that talks to the agent's owner (text or voice), answers
+// with REAL live market + portfolio data, and PROPOSES trades the owner must
+// confirm. The model never signs and never executes: read-only tools run
+// server-side and feed grounded numbers back to the model; any state-changing
+// intent (buy / sell / risk-limits) is returned to the client as a structured
+// proposal. The client re-quotes it live and, only on the owner's confirmation,
+// calls the existing guarded endpoints (POST /api/agents/:id/solana/trade,
+// PUT /api/agents/:id/trade/limits) — which enforce the spend guards
+// (api/_lib/agent-trade-guards.js), the rug/honeypot firewall
+// (api/_lib/trade-firewall.js), and the custody audit (agent_custody_events).
+// Conversation can never bypass a guard, the kill switch, or a spend cap.
+//
+// POST /api/agents/:id/copilot { messages:[{role,content}], network } → SSE
+//
+// SSE events: `status` (phase), `tool` (a read-only tool ran), `proposal`
+// (a confirm-before-execute trade/limits card), `chunk` (streamed narration
+// tokens), `done` (final reply + proposals + citations), `error`.
+//
+// $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) is the only coin three.ws
+// promotes. The copilot trades whatever mint the owner names at runtime — generic
+// coin-agnostic plumbing — and never names or recommends any other token.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, method, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { env } from '../_lib/env.js';
+import { PublicKey } from '@solana/web3.js';
+import { solanaPublicConnection } from '../_lib/agent-pumpfun.js';
+import { quoteTrade } from './solana-trade.js';
+import { assessTradeSafety } from '../_lib/trade-firewall.js';
+import { getSmartMoneyForMint } from '../_lib/smart-money.js';
+import { getTradeLimits } from '../_lib/agent-trade-guards.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const LAMPORTS_PER_SOL = 1_000_000_000;
+const MAX_ROUNDS = 4; // tool-loop rounds before we force a final answer
+const MAX_MESSAGES = 24; // trailing turns we keep as context
+
+// ── auth / ownership ──────────────────────────────────────────────────────────
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+// ── provider chain (free-first, OpenAI-compatible tool-calling + streaming) ────
+// Mirrors the platform policy in api/_lib/llm.js: free platform keys lead, the
+// paid OpenAI key is appended last as a backstop. Every provider here speaks the
+// OpenAI chat-completions wire format (tools + streamed tool_calls), so one
+// reader handles them all. Anthropic is intentionally omitted from the tool loop
+// — the free OpenAI-compatible lanes are the primary path and OpenAI is the paid
+// tail; nothing here depends on a paid key existing.
+function providerChain() {
+ const chain = [];
+ if (env.GROQ_API_KEY) {
+ chain.push({ name: 'groq', url: 'https://api.groq.com/openai/v1/chat/completions', key: env.GROQ_API_KEY, model: 'llama-3.3-70b-versatile' });
+ }
+ const orKeys = [...new Set([env.OPENROUTER_API_KEY, ...(env.OPENROUTER_FALLBACK_KEYS || [])].filter(Boolean))];
+ orKeys.forEach((key, i) => {
+ chain.push({
+ name: i === 0 ? 'openrouter' : `openrouter#${i + 1}`,
+ url: 'https://openrouter.ai/api/v1/chat/completions',
+ key,
+ model: i === 0 ? 'meta-llama/llama-3.3-70b-instruct' : 'meta-llama/llama-3.3-70b-instruct:free',
+ extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws copilot' },
+ });
+ });
+ if (env.NVIDIA_API_KEY) {
+ chain.push({ name: 'nvidia', url: 'https://integrate.api.nvidia.com/v1/chat/completions', key: env.NVIDIA_API_KEY, model: 'meta/llama-3.3-70b-instruct' });
+ }
+ if (env.OPENAI_API_KEY) {
+ chain.push({ name: 'openai', url: 'https://api.openai.com/v1/chat/completions', key: env.OPENAI_API_KEY, model: 'gpt-4o-mini' });
+ }
+ return chain;
+}
+
+// Stream one chat-completion round. Emits assistant content deltas via
+// onContent; accumulates streamed tool_calls. Resolves { content, toolCalls }.
+// Throws on transport / non-2xx so the caller can fail over to the next provider.
+async function streamRound(provider, { messages, tools, onContent }) {
+ const body = {
+ model: provider.model,
+ max_tokens: 1024,
+ temperature: 0.4,
+ stream: true,
+ messages,
+ };
+ if (Array.isArray(tools) && tools.length) { body.tools = tools; body.tool_choice = 'auto'; }
+ const resp = await fetch(provider.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${provider.key}`, ...(provider.extraHeaders || {}) },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(45_000),
+ });
+ if (!resp.ok || !resp.body) {
+ const detail = await resp.text().catch(() => '');
+ throw Object.assign(new Error(`${provider.name} ${resp.status}: ${detail.slice(0, 180)}`), { status: 502 });
+ }
+ const reader = resp.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let content = '';
+ const toolCalls = []; // index → { id, name, args }
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let nl;
+ while ((nl = buf.indexOf('\n')) >= 0) {
+ const line = buf.slice(0, nl).trim();
+ buf = buf.slice(nl + 1);
+ if (!line.startsWith('data:')) continue;
+ const payload = line.slice(5).trim();
+ if (payload === '[DONE]') { buf = ''; break; }
+ let evt;
+ try { evt = JSON.parse(payload); } catch { continue; }
+ const delta = evt.choices?.[0]?.delta;
+ if (!delta) continue;
+ if (delta.content) { content += delta.content; onContent?.(delta.content); }
+ if (Array.isArray(delta.tool_calls)) {
+ for (const tc of delta.tool_calls) {
+ const idx = tc.index ?? 0;
+ if (!toolCalls[idx]) toolCalls[idx] = { id: tc.id || `call_${idx}`, name: '', args: '' };
+ if (tc.id) toolCalls[idx].id = tc.id;
+ if (tc.function?.name) toolCalls[idx].name = tc.function.name;
+ if (tc.function?.arguments) toolCalls[idx].args += tc.function.arguments;
+ }
+ }
+ }
+ }
+ return { content, toolCalls: toolCalls.filter(Boolean) };
+}
+
+// ── tool schema (OpenAI function-calling format) ───────────────────────────────
+const TOOLS = [
+ {
+ type: 'function',
+ function: {
+ name: 'get_portfolio',
+ description: "Read the agent wallet's live SOL balance, token holdings, and open sniper positions with unrealized PnL. Use to answer 'how's my position?' / 'what do I hold?'.",
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'get_coin_intel',
+ description: 'Live intelligence for one coin mint: quality score, bundle/organic/concentration signals, risk flags, dev-sold, narrative, and graduation/rug outcome. Use before discussing or proposing a buy.',
+ parameters: { type: 'object', properties: { mint: { type: 'string', description: 'base58 token mint address' } }, required: ['mint'], additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'get_smart_money',
+ description: 'Smart-money read for one coin: count of reputable wallets in it, a 0-100 smart-money score, and whether one funder cluster dominates (sybil). Use for "is smart money in this?".',
+ parameters: { type: 'object', properties: { mint: { type: 'string' } }, required: ['mint'], additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'assess_safety',
+ description: 'Run the rug/honeypot firewall on a prospective BUY: returns verdict (allow/warn/block), a 0-100 safety score, and plain-language reasons (mint authority, honeypot round-trip, concentration, price impact). Always run before proposing a buy.',
+ parameters: { type: 'object', properties: { mint: { type: 'string' }, sol_amount: { type: 'number', description: 'SOL the owner would spend' } }, required: ['mint'], additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'get_quote',
+ description: 'Non-binding live quote: expected output and price impact for a buy (sol_amount) or sell (token_amount in UI units). Cite these exact numbers; never invent a quote.',
+ parameters: {
+ type: 'object',
+ properties: {
+ side: { type: 'string', enum: ['buy', 'sell'] },
+ mint: { type: 'string' },
+ sol_amount: { type: 'number', description: 'for buy: SOL to spend' },
+ token_amount: { type: 'number', description: 'for sell: tokens to sell, in UI units' },
+ slippage_bps: { type: 'integer', description: 'default 300 (3%)' },
+ },
+ required: ['side', 'mint'],
+ additionalProperties: false,
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'get_trade_limits',
+ description: "Read the owner's discretionary trade guardrails: per-trade SOL cap, daily budget, max price impact, max slippage, and kill-switch state.",
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'propose_buy',
+ description: 'Surface a BUY proposal for the owner to confirm. Does NOT execute — it returns a confirm card grounded with a fresh quote + firewall verdict. Call this when the owner clearly wants to buy. Never claim a buy happened until the owner confirms it.',
+ parameters: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ sol_amount: { type: 'number', description: 'SOL to spend (> 0)' },
+ slippage_bps: { type: 'integer', description: 'default 300' },
+ rationale: { type: 'string', description: 'one short sentence on why, citing real signals' },
+ },
+ required: ['mint', 'sol_amount'],
+ additionalProperties: false,
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'propose_sell',
+ description: 'Surface a SELL proposal for the owner to confirm. Does NOT execute. Provide either token_pct (1-100 of the held balance) or token_amount (UI units).',
+ parameters: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ token_pct: { type: 'number', description: 'percent of holding to sell, 1-100' },
+ token_amount: { type: 'number', description: 'tokens to sell in UI units (alternative to token_pct)' },
+ slippage_bps: { type: 'integer', description: 'default 300' },
+ rationale: { type: 'string' },
+ },
+ required: ['mint'],
+ additionalProperties: false,
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'propose_set_limits',
+ description: "Surface a risk-control change for the owner to confirm (does NOT apply until confirmed): per-trade SOL cap, daily SOL budget, max price-impact %, or the kill switch (kill_switch:true halts all trading). Use for 'cap my trades at 0.5 SOL', 'pause trading', 'set a daily budget'.",
+ parameters: {
+ type: 'object',
+ properties: {
+ per_trade_sol: { type: 'number' },
+ daily_budget_sol: { type: 'number' },
+ max_price_impact_pct: { type: 'number' },
+ kill_switch: { type: 'boolean' },
+ rationale: { type: 'string' },
+ },
+ additionalProperties: false,
+ },
+ },
+ },
+];
+
+// ── server-side tool execution (read-only) ─────────────────────────────────────
+function num(v) { return v == null || !Number.isFinite(Number(v)) ? null : Number(v); }
+
+async function loadIntel(mint, network) {
+ const [row] = await sql`
+ SELECT i.mint, i.symbol, i.name, i.quality_score, i.bundle_score, i.organic_score,
+ i.snipe_ratio, i.concentration_top10, i.fresh_wallet_ratio, i.risk_flags,
+ i.category, i.narrative, i.dev_sold, i.unique_buyers, i.observation_seconds,
+ o.outcome, o.ath_multiple
+ FROM pump_coin_intel i
+ LEFT JOIN pump_coin_outcomes o ON o.mint = i.mint AND o.network = i.network
+ WHERE i.mint = ${mint} AND i.network = ${network}
+ LIMIT 1`.catch(() => []);
+ if (!row) return { mint, found: false, note: 'No intelligence on this mint yet — the engine only fingerprints pump.fun launches it has observed.' };
+ return {
+ mint, found: true, symbol: row.symbol, name: row.name,
+ quality_score: num(row.quality_score),
+ bundle_score: num(row.bundle_score), organic_score: num(row.organic_score),
+ snipe_ratio: num(row.snipe_ratio), concentration_top10: num(row.concentration_top10),
+ fresh_wallet_ratio: num(row.fresh_wallet_ratio), risk_flags: row.risk_flags || [],
+ category: row.category, narrative: row.narrative, dev_sold: row.dev_sold,
+ unique_buyers: row.unique_buyers, observation_seconds: row.observation_seconds,
+ outcome: row.outcome || null, ath_multiple: num(row.ath_multiple),
+ };
+}
+
+async function loadPortfolio(agentId, address, network) {
+ const out = { network, wallet: address, sol_balance: null, holdings: [], open_positions: [] };
+ if (!address) return out;
+ const conn = solanaPublicConnection(network);
+ const ownerPk = new PublicKey(address);
+ try {
+ const lamports = await conn.getBalance(ownerPk);
+ out.sol_balance = Number(lamports) / LAMPORTS_PER_SOL;
+ } catch { /* RPC hiccup — report null, copilot says balance unavailable */ }
+ try {
+ const TOKEN = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
+ const TOKEN22 = new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
+ const accounts = [];
+ for (const prog of [TOKEN, TOKEN22]) {
+ const r = await conn.getParsedTokenAccountsByOwner(ownerPk, { programId: prog }).catch(() => null);
+ if (r?.value) accounts.push(...r.value);
+ }
+ out.holdings = accounts
+ .map((a) => {
+ const info = a.account.data.parsed?.info;
+ const amt = info?.tokenAmount;
+ return amt && Number(amt.uiAmount) > 0
+ ? { mint: info.mint, ui_amount: Number(amt.uiAmount), decimals: amt.decimals }
+ : null;
+ })
+ .filter(Boolean)
+ .slice(0, 30);
+ } catch { /* token read failed — holdings stay empty */ }
+ try {
+ const rows = await sql`
+ SELECT mint, symbol, status, entry_quote_lamports, last_value_lamports,
+ realized_pnl_lamports, realized_pnl_pct, exit_reason
+ FROM agent_sniper_positions
+ WHERE agent_id = ${agentId} AND network = ${network} AND status = 'open'
+ ORDER BY opened_at DESC LIMIT 20`;
+ out.open_positions = rows.map((p) => ({
+ mint: p.mint, symbol: p.symbol,
+ entry_sol: num(p.entry_quote_lamports) != null ? num(p.entry_quote_lamports) / LAMPORTS_PER_SOL : null,
+ current_sol: num(p.last_value_lamports) != null ? num(p.last_value_lamports) / LAMPORTS_PER_SOL : null,
+ unrealized_pnl_pct: num(p.realized_pnl_pct),
+ }));
+ } catch { /* positions table read failed — leave empty */ }
+ return out;
+}
+
+async function runQuote({ side, mint, solAmount, tokenAmount, slippageBps, network }) {
+ const conn = solanaPublicConnection(network);
+ const mintPk = new PublicKey(mint);
+ let tokenAmountRaw;
+ if (side === 'sell') {
+ // Convert UI tokens → raw using on-chain decimals.
+ let decimals = 6;
+ try {
+ const info = await conn.getParsedAccountInfo(mintPk);
+ const d = info?.value?.data?.parsed?.info?.decimals;
+ if (Number.isInteger(d)) decimals = d;
+ } catch { /* default 6 */ }
+ tokenAmountRaw = BigInt(Math.floor(Number(tokenAmount || 0) * 10 ** decimals)).toString();
+ }
+ const q = await quoteTrade({ conn, side, mintPk, mintStr: mint, network, solAmount, tokenAmountRaw, slippageBps });
+ return {
+ side, mint, venue: q.venue, price_impact_pct: num(q.priceImpactPct),
+ in_asset: q.inAsset, in_amount: num(q.inAmount),
+ out_asset: q.outAsset, expected_out: num(q.outUi),
+ min_received: num(q.minOutUi),
+ };
+}
+
+// Best-effort coin label (symbol/name) for proposal cards.
+async function coinLabel(mint, network) {
+ const intel = await loadIntel(mint, network).catch(() => null);
+ if (intel?.found && (intel.symbol || intel.name)) return { symbol: intel.symbol || null, name: intel.name || null };
+ return { symbol: null, name: null };
+}
+
+// ── system prompt ──────────────────────────────────────────────────────────────
+function buildSystemPrompt({ agentName, persona, network }) {
+ const base = (persona || '').trim();
+ return [
+ base ? `You speak in character as ${agentName}. Persona:\n${base}\n` : `You are ${agentName}, a trading copilot.`,
+ `You are the in-world CONVERSATIONAL TRADING COPILOT for the three.ws agent "${agentName}" and its self-custodied Solana wallet (network: ${network}).`,
+ `Your job: help the owner snipe, trade, and manage risk by talking. You have real tools — use them; never invent numbers, prices, balances, safety verdicts, or smart-money counts. If a tool returns no data, say so plainly.`,
+ `RULES:`,
+ `• You NEVER execute or sign anything. To buy, sell, or change risk limits you MUST call the matching propose_* tool, which surfaces a confirm card. The owner confirms; a guarded server endpoint then enforces spend caps, the firewall, and the kill switch and signs. Never say a trade is done — say you've prepared it for confirmation.`,
+ `• Before proposing OR recommending a buy, ground it: call assess_safety (firewall) and get_quote, and mention the safety verdict and price impact. If the firewall verdict is "block", refuse the buy and explain why.`,
+ `• Keep answers tight and conversational (2-5 sentences) — this may be read aloud. Use plain language, no markdown tables, no code blocks.`,
+ `• The only coin three.ws promotes is $THREE. You may trade any mint the owner explicitly names (that is their call), but never suggest, shill, or name a specific other token on your own initiative.`,
+ `• When the owner is vague ("buy the safe one"), ask one brief clarifying question or have them paste a mint — do not guess a mint address.`,
+ ].join('\n');
+}
+
+// ── handler ─────────────────────────────────────────────────────────────────────
+export default async function handler(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to talk to this copilot');
+
+ const rl = await limits.tradePerUser(auth.userId).catch(() => ({ success: true }));
+ if (rl && rl.success === false) return rateLimited(res, rl);
+
+ const [row] = await sql`SELECT id, user_id, name, persona_prompt, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'only the owner can use this copilot');
+
+ const meta = row.meta || {};
+ const address = meta.solana_address || null;
+ const body = await readJson(req).catch(() => null);
+ const network = netOf(body?.network);
+ const rawMessages = Array.isArray(body?.messages) ? body.messages : [];
+ const history = rawMessages
+ .filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim())
+ .slice(-MAX_MESSAGES)
+ .map((m) => ({ role: m.role, content: m.content.slice(0, 4000) }));
+ if (!history.length || history[history.length - 1].role !== 'user') {
+ return error(res, 422, 'no_message', 'send at least one user message');
+ }
+
+ const chain = providerChain();
+ if (!chain.length) return error(res, 503, 'llm_unavailable', 'No LLM provider configured. Set GROQ_API_KEY, OPENROUTER_API_KEY, or NVIDIA_API_KEY.');
+
+ // SSE open.
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+ let active = true;
+ req.on('close', () => { active = false; });
+ const send = (event, data) => { if (active) res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); };
+
+ const messages = [{ role: 'system', content: buildSystemPrompt({ agentName: row.name || 'Agent', persona: row.persona_prompt, network }) }, ...history];
+ const proposals = [];
+ const citations = [];
+ let finalText = '';
+
+ // One read-only tool execution → returns a compact result for the model + a UI summary.
+ async function execReadTool(name, args) {
+ if (name === 'get_portfolio') {
+ const p = await loadPortfolio(id, address, network);
+ citations.push({ kind: 'portfolio', sol: p.sol_balance, holdings: p.holdings.length, positions: p.open_positions.length });
+ return { result: p, summary: address ? `Portfolio: ${p.sol_balance != null ? p.sol_balance.toFixed(4) + ' SOL' : 'balance unavailable'}, ${p.holdings.length} token(s), ${p.open_positions.length} open position(s)` : 'No wallet provisioned yet' };
+ }
+ if (name === 'get_coin_intel') {
+ const intel = await loadIntel(args.mint, network);
+ citations.push({ kind: 'intel', mint: args.mint, quality: intel.quality_score ?? null });
+ return { result: intel, summary: intel.found ? `Intel ${intel.symbol || ''}: quality ${intel.quality_score ?? '—'}/100, ${(intel.risk_flags || []).length} risk flag(s)${intel.outcome ? `, outcome ${intel.outcome}` : ''}` : 'No intel on this mint' };
+ }
+ if (name === 'get_smart_money') {
+ const sm = await getSmartMoneyForMint(args.mint, network);
+ citations.push({ kind: 'smart_money', mint: args.mint, score: sm.smart_money_score, count: sm.count });
+ return { result: sm, summary: `Smart money: ${sm.count} reputable wallet(s), score ${sm.smart_money_score}/100${sm.sybil_flag ? ' (sybil-dominated)' : ''}` };
+ }
+ if (name === 'assess_safety') {
+ const conn = solanaPublicConnection(network);
+ const quoteLamports = args.sol_amount > 0 ? BigInt(Math.floor(Number(args.sol_amount) * LAMPORTS_PER_SOL)) : null;
+ const a = await assessTradeSafety({ network, mint: args.mint, side: 'buy', payer: address, quoteAmount: quoteLamports, connection: conn });
+ citations.push({ kind: 'safety', mint: args.mint, verdict: a.verdict, score: a.score });
+ return { result: { verdict: a.verdict, score: a.score, reasons: a.reasons, simulated: a.simulated }, summary: `Firewall: ${a.verdict.toUpperCase()} (${a.score}/100)${a.reasons?.[0] ? ' — ' + a.reasons[0] : ''}` };
+ }
+ if (name === 'get_quote') {
+ const q = await runQuote({ side: args.side, mint: args.mint, solAmount: args.sol_amount, tokenAmount: args.token_amount, slippageBps: args.slippage_bps || 300, network });
+ citations.push({ kind: 'quote', mint: args.mint, side: args.side, impact: q.price_impact_pct });
+ return { result: q, summary: `Quote ${args.side}: ${q.expected_out != null ? q.expected_out.toLocaleString(undefined, { maximumFractionDigits: 4 }) : '—'} ${q.out_asset}, ${q.price_impact_pct != null ? q.price_impact_pct.toFixed(2) + '% impact' : 'impact n/a'}` };
+ }
+ if (name === 'get_trade_limits') {
+ const lim = getTradeLimits(meta);
+ return { result: lim, summary: `Limits: per-trade ${lim.per_trade_sol ?? '∞'} SOL, daily ${lim.daily_budget_sol ?? '∞'} SOL, kill switch ${lim.kill_switch ? 'ON' : 'off'}` };
+ }
+ return { result: { error: 'unknown_tool' }, summary: 'unknown tool' };
+ }
+
+ // A propose_* tool → grounded proposal card, never executed here.
+ async function execProposeTool(name, args) {
+ if (name === 'propose_buy') {
+ if (!BASE58_RE.test(args.mint || '')) return { result: { error: 'invalid_mint' }, summary: 'invalid mint' };
+ const slippageBps = Math.max(0, Math.min(5000, Math.round(args.slippage_bps || 300)));
+ const [quote, safety, label] = await Promise.all([
+ runQuote({ side: 'buy', mint: args.mint, solAmount: args.sol_amount, slippageBps, network }).catch((e) => ({ error: e?.message || 'quote_failed' })),
+ assessTradeSafety({ network, mint: args.mint, side: 'buy', payer: address, quoteAmount: BigInt(Math.floor(Number(args.sol_amount) * LAMPORTS_PER_SOL)), connection: solanaPublicConnection(network) })
+ .then((a) => ({ verdict: a.verdict, score: a.score, reasons: a.reasons, simulated: a.simulated }))
+ .catch(() => null),
+ coinLabel(args.mint, network),
+ ]);
+ const proposal = { id: `p${proposals.length + 1}`, kind: 'buy', mint: args.mint, coin: label, sol_amount: Number(args.sol_amount), slippage_bps: slippageBps, network, quote, safety, rationale: args.rationale || null };
+ proposals.push(proposal);
+ send('proposal', proposal);
+ const blocked = safety?.verdict === 'block';
+ return { result: { surfaced: true, blocked, safety_verdict: safety?.verdict, price_impact_pct: quote?.price_impact_pct }, summary: `Buy proposal surfaced (awaiting confirmation). Firewall ${safety?.verdict || 'n/a'}.${blocked ? ' BLOCKED — do not encourage this trade.' : ''}` };
+ }
+ if (name === 'propose_sell') {
+ if (!BASE58_RE.test(args.mint || '')) return { result: { error: 'invalid_mint' }, summary: 'invalid mint' };
+ const slippageBps = Math.max(0, Math.min(5000, Math.round(args.slippage_bps || 300)));
+ // Resolve the held balance so a percent maps to a concrete UI amount.
+ const port = await loadPortfolio(id, address, network).catch(() => null);
+ const held = port?.holdings?.find((h) => h.mint === args.mint) || null;
+ let tokenAmount = num(args.token_amount);
+ let tokenPct = num(args.token_pct);
+ if (tokenAmount == null && tokenPct != null && held) tokenAmount = (held.ui_amount * Math.max(1, Math.min(100, tokenPct))) / 100;
+ if (tokenAmount == null && held) tokenAmount = held.ui_amount; // default: sell all
+ if (!(tokenAmount > 0)) return { result: { error: 'no_holding' }, summary: 'owner does not hold this coin' };
+ const [quote, label] = await Promise.all([
+ runQuote({ side: 'sell', mint: args.mint, tokenAmount, slippageBps, network }).catch((e) => ({ error: e?.message || 'quote_failed' })),
+ coinLabel(args.mint, network),
+ ]);
+ const proposal = { id: `p${proposals.length + 1}`, kind: 'sell', mint: args.mint, coin: label, token_amount: tokenAmount, token_pct: tokenPct ?? null, decimals: held?.decimals ?? 6, slippage_bps: slippageBps, network, quote, rationale: args.rationale || null };
+ proposals.push(proposal);
+ send('proposal', proposal);
+ return { result: { surfaced: true, expected_sol: quote?.expected_out }, summary: `Sell proposal surfaced (awaiting confirmation): ~${quote?.expected_out != null ? Number(quote.expected_out).toFixed(4) : '—'} SOL.` };
+ }
+ if (name === 'propose_set_limits') {
+ const cur = getTradeLimits(meta);
+ const changes = {};
+ for (const k of ['per_trade_sol', 'daily_budget_sol', 'max_price_impact_pct']) {
+ if (num(args[k]) != null) changes[k] = Number(args[k]);
+ }
+ if (typeof args.kill_switch === 'boolean') changes.kill_switch = args.kill_switch;
+ if (!Object.keys(changes).length) return { result: { error: 'no_change' }, summary: 'no limit change specified' };
+ const proposal = { id: `p${proposals.length + 1}`, kind: 'limits', network, current: cur, changes, rationale: args.rationale || null };
+ proposals.push(proposal);
+ send('proposal', proposal);
+ return { result: { surfaced: true }, summary: 'Risk-limit change surfaced (awaiting confirmation).' };
+ }
+ return { result: { error: 'unknown_tool' }, summary: 'unknown tool' };
+ }
+
+ // ── tool loop ───────────────────────────────────────────────────────────────
+ try {
+ let answered = false;
+ for (let round = 0; round < MAX_ROUNDS && active && !answered; round++) {
+ send('status', { phase: round === 0 ? 'thinking' : 'continuing' });
+ // Pick the first provider that yields a round; once content has been
+ // streamed to the client we can't fail over, so stream-failover only
+ // applies before any byte for THIS round was emitted.
+ let roundOut = null;
+ let lastErr = null;
+ for (const provider of chain) {
+ let emitted = false;
+ try {
+ roundOut = await streamRound(provider, {
+ messages,
+ tools: TOOLS,
+ onContent: (t) => { emitted = true; finalText += t; send('chunk', { text: t }); },
+ });
+ break;
+ } catch (e) {
+ lastErr = e;
+ if (emitted) { roundOut = { content: '', toolCalls: [] }; break; } // mid-stream failure; stop
+ }
+ }
+ if (!roundOut) throw lastErr || new Error('all providers failed');
+
+ if (!roundOut.toolCalls.length) { answered = true; break; }
+
+ // Record the assistant's tool-call turn, then resolve each call.
+ messages.push({
+ role: 'assistant',
+ content: roundOut.content || null,
+ tool_calls: roundOut.toolCalls.map((tc) => ({ id: tc.id, type: 'function', function: { name: tc.name, arguments: tc.args || '{}' } })),
+ });
+ for (const tc of roundOut.toolCalls) {
+ let args = {};
+ try { args = tc.args ? JSON.parse(tc.args) : {}; } catch { args = {}; }
+ const isPropose = tc.name.startsWith('propose_');
+ let outcome;
+ try {
+ outcome = isPropose ? await execProposeTool(tc.name, args) : await execReadTool(tc.name, args);
+ } catch (e) {
+ outcome = { result: { error: e?.message || 'tool_failed' }, summary: `Tool ${tc.name} failed: ${e?.message || 'error'}` };
+ }
+ if (!isPropose) send('tool', { name: tc.name, summary: outcome.summary });
+ messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(outcome.result).slice(0, 6000) });
+ }
+ }
+
+ // If the loop hit its round cap mid-tool without a natural answer, ask for a
+ // final plain-language wrap-up (no tools) so the user always gets a reply.
+ if (!finalText.trim() && active) {
+ send('status', { phase: 'finalizing' });
+ for (const provider of chain) {
+ try {
+ const out = await streamRound(provider, {
+ messages: [...messages, { role: 'user', content: 'Briefly summarize what you found and what I should do next. Plain language, 2-4 sentences.' }],
+ tools: [],
+ onContent: (t) => { finalText += t; send('chunk', { text: t }); },
+ });
+ if (out) break;
+ } catch { /* try next provider */ }
+ }
+ }
+
+ send('done', { reply: finalText.trim(), proposals, citations });
+ } catch (e) {
+ send('error', { code: e?.code || 'copilot_error', message: e?.message || 'The copilot hit an error. Try again.' });
+ } finally {
+ if (active) res.end();
+ }
+}
diff --git a/api/agents/orders.js b/api/agents/orders.js
new file mode 100644
index 000000000..6b35af225
--- /dev/null
+++ b/api/agents/orders.js
@@ -0,0 +1,301 @@
+/**
+ * Programmable Orders API — owner-only control surface for the order engine.
+ * Routed from api/agents/[id].js as /api/agents/:id/orders.
+ *
+ * GET /api/agents/:id/orders → orders + summary + live balance
+ * POST /api/agents/:id/orders → create a validated order (real)
+ * POST /api/agents/:id/orders/preview → validate + live preview (metric, would-fire, firewall verdict)
+ * POST /api/agents/:id/orders/cancel-all → cancel every active order (orders kill switch)
+ * GET /api/agents/:id/orders/stream → SSE: live order status
+ * GET /api/agents/:id/orders/:orderId → one order + its fills
+ * PUT /api/agents/:id/orders/:orderId → edit (price/trail/slippage/expiry/pause)
+ * DELETE /api/agents/:id/orders/:orderId → cancel one order (instant)
+ *
+ * Every write is owner-only (server-side) and CSRF-protected. Orders fire ONLY
+ * from the agent's own wallet through the shared, spend-policy-gated, firewalled,
+ * audited execeuteAgentTrade pipeline. A visitor can never read or mutate orders.
+ */
+
+import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { sql } from '../_lib/db.js';
+import { getSolanaAddressBalances } from '../_lib/agent-wallet.js';
+import { getSpendLimits, getTradeLimits } from '../_lib/agent-trade-guards.js';
+import { getPumpTradeClient } from '../_lib/pump.js';
+import { assessTradeSafety } from '../_lib/trade-firewall.js';
+import { PublicKey } from '@solana/web3.js';
+import {
+ normalizeOrder, describeOrder, conditionSignals, evaluateCondition, shouldFirePrice,
+ listOrders, getOrder, listFills, createOrder, updateOrder, cancelOrder, cancelAllOrders, ordersSummary,
+ CONDITION_SIGNALS, NUMBER_OPS, BOOL_OPS, ORDER_TYPES, TRIGGER_METRICS,
+} from '../_lib/orders.js';
+import { getSignals, metricValue } from '../../workers/agent-orders/market.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+async function loadOwned(req, res, id) {
+ const auth = await resolveAuth(req);
+ if (!auth) { error(res, 401, 'unauthorized', 'sign in to manage this agent’s orders'); return { error: true }; }
+ const [row] = await sql`SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) { error(res, 404, 'not_found', 'agent not found'); return { error: true }; }
+ if (row.user_id !== auth.userId) { error(res, 403, 'forbidden', 'only the owner can manage orders'); return { error: true }; }
+ return { auth, row, meta: { ...(row.meta || {}) } };
+}
+
+function netOf(req) {
+ const url = new URL(req.url, 'http://x');
+ return url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+}
+
+export default async function handler(req, res, id, action) {
+ if (cors(req, res, { methods: 'GET,POST,PUT,DELETE,OPTIONS', credentials: true })) return;
+
+ if (action === 'preview') return handlePreview(req, res, id);
+ if (action === 'cancel-all') return handleCancelAll(req, res, id);
+ if (action === 'stream') return handleStream(req, res, id);
+ if (action === 'schema') return handleSchema(req, res, id);
+ if (action && UUID_RE.test(action)) {
+ if (req.method === 'GET') return handleGetOne(req, res, id, action);
+ if (req.method === 'PUT') return handleUpdate(req, res, id, action);
+ if (req.method === 'DELETE') return handleCancel(req, res, id, action);
+ return error(res, 405, 'method_not_allowed', 'use GET, PUT, or DELETE on an order');
+ }
+ if (action) return error(res, 404, 'not_found', 'unknown orders sub-resource');
+
+ if (req.method === 'GET') return handleList(req, res, id);
+ if (req.method === 'POST') return handleCreate(req, res, id);
+ return method(req, res, ['GET', 'POST']) ? error(res, 405, 'method_not_allowed', 'use GET or POST') : undefined;
+}
+
+// GET — orders + summary + live balance + freeze state.
+async function handleList(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const network = netOf(req);
+ const [orders, summary] = await Promise.all([listOrders(id, { network }), ordersSummary(id, network)]);
+ const spend = getSpendLimits(owned.meta);
+
+ let balanceSol = null;
+ try { balanceSol = Number((await getSolanaAddressBalances(owned.meta.solana_address, network))?.sol ?? null); }
+ catch { balanceSol = null; }
+
+ return json(res, 200, {
+ data: {
+ orders,
+ summary: { ...summary, balance_sol: balanceSol, frozen: !!spend.frozen, kill_switch: !!getTradeLimits(owned.meta).kill_switch },
+ },
+ });
+}
+
+// GET /schema — the closed condition vocabulary + order types (drives the UI builder).
+async function handleSchema(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ return json(res, 200, {
+ data: {
+ order_types: ORDER_TYPES,
+ trigger_metrics: TRIGGER_METRICS,
+ number_ops: NUMBER_OPS,
+ bool_ops: BOOL_OPS,
+ signals: Object.fromEntries(Object.entries(CONDITION_SIGNALS).map(([k, v]) => [k, { kind: v.kind, label: v.label }])),
+ },
+ });
+}
+
+async function handleGetOne(req, res, id, orderId) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ const order = await getOrder(id, orderId);
+ if (!order) return error(res, 404, 'not_found', 'order not found');
+ const fills = await listFills(orderId);
+ return json(res, 200, { data: { order, fills } });
+}
+
+// POST / — create a validated order.
+async function handleCreate(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const rl = await limits.tradePerUser(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ let body;
+ try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+
+ const norm = normalizeOrder({ ...body, network: netOf(req) });
+ if (!norm.ok) return error(res, 422, norm.error || 'invalid_order', norm.message || 'the order could not be validated');
+
+ try {
+ const order = await createOrder(id, owned.auth.userId, norm.order);
+ return json(res, 201, { data: { order } });
+ } catch (e) {
+ return serverError(res, 500, 'create_failed', e);
+ }
+}
+
+// POST /preview — validate + a concrete, REAL live preview: current metric value,
+// whether the trigger would fire right now, and (for buys) the firewall verdict.
+async function handlePreview(req, res, id) {
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ let body;
+ try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+
+ const network = netOf(req);
+ const norm = normalizeOrder({ ...body, network });
+ if (!norm.ok) return json(res, 200, { data: { ok: false, error: norm.error, message: norm.message } });
+ const o = norm.order;
+
+ // Live signals: only what this order's trigger references.
+ const need = o.type === 'conditional' ? conditionSignals(o.condition) : [];
+ if (o.type === 'trailing' || o.type === 'conditional') need.push('mcap_usd');
+ let preview = { current: null, would_fire_now: null, missing: [] };
+ try {
+ const { market, signals } = await getSignals({ network, mint: o.mint, need, metric: o.trigger_metric });
+ if (market) {
+ const cur = metricValue(market, signals, o.trigger_metric);
+ preview.current = { metric: o.trigger_metric, value: cur, price_sol: market.price_sol, mcap_sol: market.mcap_sol, mcap_usd: signals.mcap_usd, graduated: market.graduated };
+ if (o.type === 'conditional') {
+ const r = evaluateCondition(o.condition, signals);
+ preview.would_fire_now = r.fired; preview.missing = r.missing;
+ } else if (o.type === 'limit' || o.type === 'stop') {
+ preview.would_fire_now = shouldFirePrice(o, cur, cur);
+ } else if (o.type === 'trailing') {
+ preview.would_fire_now = false; // needs a tracked high/low-water mark first
+ }
+ }
+ } catch { /* preview tolerates a quote miss */ }
+
+ // Firewall verdict for buys (real on-chain simulated round-trip + authority audit).
+ let firewall = null;
+ if (o.side === 'buy' && owned.meta.solana_address && o.size_sol) {
+ try {
+ const ctx = await getPumpTradeClient({ network });
+ const lamports = BigInt(Math.round(Number(o.size_sol) * 1e9));
+ const a = await assessTradeSafety({
+ network, mint: o.mint, side: 'buy', payer: new PublicKey(owned.meta.solana_address),
+ quoteAmount: lamports, connection: ctx.connection,
+ });
+ if (a) firewall = { verdict: a.verdict, score: a.score, simulated: a.simulated, reasons: a.reasons?.slice(0, 4) || [] };
+ } catch { firewall = null; }
+ }
+
+ return json(res, 200, { data: { ok: true, order: o, readback: describeOrder(o), preview, firewall, spend_limits: previewLimits(owned.meta) } });
+}
+
+function previewLimits(meta) {
+ const s = getSpendLimits(meta);
+ const t = getTradeLimits(meta);
+ return { per_tx_usd: s.per_tx_usd, daily_usd: s.daily_usd, frozen: !!s.frozen, kill_switch: !!t.kill_switch, per_trade_sol: t.per_trade_sol, daily_budget_sol: t.daily_budget_sol };
+}
+
+// PUT /:orderId — edit a non-terminal order.
+async function handleUpdate(req, res, id, orderId) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
+ let body;
+ try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+
+ try {
+ const result = await updateOrder(id, orderId, body);
+ if (!result) return error(res, 404, 'not_found', 'order not found');
+ if (result.error) return error(res, 422, result.error, result.message);
+ return json(res, 200, { data: { order: result } });
+ } catch (e) {
+ return serverError(res, 500, 'update_failed', e);
+ }
+}
+
+// DELETE /:orderId — instant cancel.
+async function handleCancel(req, res, id, orderId) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ try {
+ const order = await cancelOrder(id, orderId);
+ if (!order) return error(res, 404, 'not_found', 'order not found');
+ return json(res, 200, { data: { order } });
+ } catch (e) {
+ return serverError(res, 500, 'cancel_failed', e);
+ }
+}
+
+// POST /cancel-all — orders kill switch (instant). Returns the cancelled count.
+async function handleCancelAll(req, res, id) {
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ try {
+ const cancelled = await cancelAllOrders(id, netOf(req));
+ return json(res, 200, { data: { cancelled } });
+ } catch (e) {
+ return serverError(res, 500, 'cancel_failed', e);
+ }
+}
+
+// GET /stream — Server-Sent Events: push the order list as it changes. Capped at
+// ~40s (inside the function's maxDuration) — the client reconnects. Read-only.
+const STREAM_MS = 40_000;
+const STREAM_TICK_MS = 3_000;
+
+async function handleStream(req, res, id) {
+ if (!method(req, res, ['GET'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+
+ const network = netOf(req);
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => { if (active) { try { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); } catch { teardown(); } } };
+
+ let lastHash = '';
+ const push = async () => {
+ try {
+ const [orders, summary] = await Promise.all([listOrders(id, { network }), ordersSummary(id, network)]);
+ const hash = JSON.stringify(orders.map((o) => [o.id, o.status, o.fill_count, o.last_price, o.last_error]));
+ if (hash !== lastHash) { lastHash = hash; send('orders', { orders, summary }); }
+ else send('ping', { t: Date.now() });
+ } catch { send('ping', { t: Date.now() }); }
+ };
+
+ await push();
+ const tick = setInterval(push, STREAM_TICK_MS);
+ const end = setTimeout(() => { send('close', { reason: 'duration_limit' }); teardown(); }, STREAM_MS);
+
+ function teardown() {
+ if (!active) return;
+ active = false;
+ clearInterval(tick); clearTimeout(end);
+ try { res.end(); } catch { /* */ }
+ }
+ req.on('close', teardown);
+ req.on('error', teardown);
+}
diff --git a/api/agents/portfolio.js b/api/agents/portfolio.js
new file mode 100644
index 000000000..bf12d7e8d
--- /dev/null
+++ b/api/agents/portfolio.js
@@ -0,0 +1,145 @@
+/**
+ * /api/agents/:id/portfolio — owner-only Portfolio Command snapshot:
+ * live valuation of every holding (SOL + SPL) in SOL + USD, FIFO cost basis +
+ * unrealized P&L per holding, realized/unrealized P&L attributed by source
+ * (sniper strategies, discretionary, strategy objects, x402, withdrawals), and
+ * live risk metrics (concentration, exposure, drawdown, realized vol) with
+ * plain-language flags. All real — see api/_lib/portfolio.js.
+ *
+ * /api/agents/:id/portfolio/stream — owner-only SSE: re-values on an interval
+ * and pushes net-worth + risk snapshots so the UI stays live.
+ *
+ * Attribution is derived from the custody/spend ledger, which is owner-sensitive,
+ * so the whole surface is owner-gated (unlike the public balance read).
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, error, rateLimited, serverError } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { getPortfolio } from '../_lib/portfolio.js';
+
+const MAX_DURATION_MS = 90_000;
+const PING_INTERVAL_MS = 15_000;
+const SNAPSHOT_INTERVAL_MS = 20_000;
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+// Load + ownership-gate the agent. Returns { auth } on success, or null after
+// having written the error response.
+async function gateOwner(req, res, id) {
+ const auth = await resolveAuth(req);
+ if (!auth) { error(res, 401, 'unauthorized', 'sign in required'); return null; }
+ const [row] = await sql`SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) { error(res, 404, 'not_found', 'agent not found'); return null; }
+ if (row.user_id !== auth.userId) { error(res, 403, 'forbidden', 'not your agent'); return null; }
+ return { auth };
+}
+
+function networkOf(req) {
+ const url = new URL(req.url, 'http://x');
+ return url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+}
+
+// ── snapshot ────────────────────────────────────────────────────────────────
+async function handleSnapshot(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const gate = await gateOwner(req, res, id);
+ if (!gate) return;
+
+ const rl = await limits.walletRead(gate.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const network = networkOf(req);
+ let portfolio;
+ try {
+ portfolio = await getPortfolio({ agentId: id, network });
+ } catch (e) {
+ console.error('[agents/portfolio] snapshot failed', e?.message);
+ return serverError(res, 502, 'portfolio_failed', e);
+ }
+ if (!portfolio) return error(res, 404, 'not_found', 'agent not found');
+ return json(res, 200, { data: portfolio });
+}
+
+// ── live stream (SSE) ───────────────────────────────────────────────────────
+async function handleStream(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const gate = await gateOwner(req, res, id);
+ if (!gate) return;
+
+ const rl = await limits.walletRead(gate.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const network = networkOf(req);
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => {
+ if (!active || res.writableEnded) return;
+ try { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); } catch { /* client gone */ }
+ };
+
+ send('hello', { ts: Date.now(), network });
+
+ const push = async () => {
+ if (!active) return;
+ try {
+ const p = await getPortfolio({ agentId: id, network });
+ if (!p) { send('bye', { reason: 'not_found' }); return cleanup(); }
+ // Stream the live-moving parts; the initial GET supplies the full body.
+ send('snapshot', {
+ t: p.t,
+ sol_usd: p.sol_usd,
+ net_worth: p.net_worth,
+ risk: p.risk,
+ risk_flags: p.risk_flags,
+ attribution: p.attribution,
+ holdings: p.holdings,
+ });
+ } catch (e) {
+ send('warn', { message: 'revaluation_failed' });
+ }
+ };
+
+ await push();
+ const snapTimer = setInterval(push, SNAPSHOT_INTERVAL_MS);
+ const pingTimer = setInterval(() => send('ping', { ts: Date.now() }), PING_INTERVAL_MS);
+ const hardStop = setTimeout(() => { send('bye', { reason: 'max_duration' }); cleanup(); }, MAX_DURATION_MS);
+
+ function cleanup() {
+ if (!active) return;
+ active = false;
+ clearInterval(snapTimer);
+ clearInterval(pingTimer);
+ clearTimeout(hardStop);
+ try { res.end(); } catch { /* already closed */ }
+ }
+
+ req.on('close', cleanup);
+ req.on('error', cleanup);
+}
+
+export default async function handler(req, res, id, action) {
+ if (action === 'stream') return handleStream(req, res, id);
+ if (!action) return handleSnapshot(req, res, id);
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ return error(res, 404, 'not_found', 'unknown portfolio sub-resource');
+}
diff --git a/api/cron/radar-watchlist.js b/api/cron/radar-watchlist.js
new file mode 100644
index 000000000..1d535474b
--- /dev/null
+++ b/api/cron/radar-watchlist.js
@@ -0,0 +1,63 @@
+// GET/POST /api/cron/radar-watchlist — recurate the Pre-Launch Radar watchlist.
+//
+// The radar worker (workers/agent-sniper/prelaunch-radar.js) recurates its own
+// watchlist on an interval, but that only runs when the worker is up. This cron
+// keeps radar_watchlist fresh independently — from the SAME real sources (proven
+// creators via pump_coin_intel ⋈ pump_coin_outcomes, top smart_wallet_reputation
+// wallets) — so the Radar UI always has a current, honest watchlist even when the
+// worker is in simulate mode, paused, or between deploys.
+//
+// Idempotent + bounded. Mainnet-only (pump.fun). Reads the graph, writes only the
+// radar's own table.
+
+import { error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { recomputeWatchlist } from '../../workers/agent-sniper/radar-watchlist.js';
+
+const NETWORK = 'mainnet';
+
+// The worker's config defaults — mirrored here so the cron curates with the same
+// thresholds the radar uses. Env overrides apply in both places.
+function radarCfg() {
+ const num = (name, def) => {
+ const v = Number(process.env[name]);
+ return Number.isFinite(v) ? v : def;
+ };
+ return {
+ radarMinCreatorGraduated: Math.max(1, num('SNIPER_RADAR_MIN_GRADUATED', 2)),
+ radarSmartMoneyMinScore: Math.max(0, Math.min(100, num('SNIPER_RADAR_SM_MIN_SCORE', 70))),
+ radarMaxWatch: Math.max(20, num('SNIPER_RADAR_MAX_WATCH', 500)),
+ radarWatchlistRefreshMs: Math.max(60_000, num('SNIPER_RADAR_WATCHLIST_REFRESH_MS', 300_000)),
+ };
+}
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const started = Date.now();
+ const result = await recomputeWatchlist({ network: NETWORK, cfg: radarCfg() });
+
+ return json(res, 200, {
+ ok: result.ok,
+ watched: result.watched,
+ creators: result.creators,
+ smartMoney: result.smartMoney,
+ evicted: result.evicted,
+ reason: result.reason || null,
+ ms: Date.now() - started,
+ });
+});
diff --git a/api/cron/signal-fanout.js b/api/cron/signal-fanout.js
new file mode 100644
index 000000000..426b90bf5
--- /dev/null
+++ b/api/cron/signal-fanout.js
@@ -0,0 +1,121 @@
+// GET /api/cron/signal-fanout — drive the reputation-gated signal marketplace.
+//
+// Two passes per network:
+// 1. EMIT — for every active feed whose publisher has new position activity
+// (an open or a close) since the feed's cursor, generate the corresponding
+// entry/exit emissions from the REAL agent_sniper_positions and backfill the
+// realized outcome onto closed entries (api/_lib/signal-engine.js
+// syncFeedEmissions). Sellers never hand-author signals — every emission
+// binds to an on-chain fill.
+// 2. DELIVER — for every active, non-killed subscription with undelivered
+// emissions, settle the x402 USDC payment and auto-mirror the trade through
+// the SAME firewall + MEV + spend-guard pipeline every other path uses
+// (deliverSubscription → runFollowerTrade). Idempotent end to end: the
+// signal_deliveries unique key and the custody idempotency key both prevent
+// double-paying / double-trading, so re-running (or overlapping with an owner
+// "Sync now") is safe.
+//
+// Bounded so a 2-minute cron can never run away: only feeds with recent publisher
+// activity emit, and each subscription delivers at most N emissions per run.
+
+import { error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { sql } from '../_lib/db.js';
+import { syncFeedEmissions, deliverSubscription } from '../_lib/signal-engine.js';
+
+const NETWORKS = ['mainnet', 'devnet'];
+const MAX_FEEDS_PER_RUN = 120;
+const MAX_SUBS_PER_RUN = 200;
+const MAX_EVENTS_PER_SUB = 12;
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }
+ return true;
+}
+
+// PASS 1 — generate emissions from publishers' real positions.
+async function emitPass(network, stats) {
+ // Only feeds whose publisher has a position opened/closed past the relevant
+ // cursor recently — keeps the scan bounded to feeds with fresh activity.
+ const feeds = await sql`
+ SELECT f.*
+ FROM signal_feeds f
+ JOIN agent_identities a ON a.id = f.publisher_agent_id AND a.deleted_at IS NULL
+ WHERE f.status = 'active' AND f.network = ${network}
+ AND EXISTS (
+ SELECT 1 FROM agent_sniper_positions p
+ WHERE p.agent_id = f.publisher_agent_id AND p.network = ${network}
+ AND (
+ (p.opened_at > f.entry_cursor AND p.opened_at > now() - interval '30 minutes')
+ OR (p.status = 'closed' AND p.closed_at > f.exit_cursor AND p.closed_at > now() - interval '30 minutes')
+ )
+ )
+ ORDER BY f.updated_at ASC
+ LIMIT ${MAX_FEEDS_PER_RUN}
+ `;
+ if (!feeds.length) return;
+ stats.feeds = (stats.feeds || 0) + feeds.length;
+ for (const f of feeds) {
+ try {
+ const r = await syncFeedEmissions(f);
+ stats.emitted_entries = (stats.emitted_entries || 0) + r.entries;
+ stats.emitted_exits = (stats.emitted_exits || 0) + r.exits;
+ stats.closed_signals = (stats.closed_signals || 0) + r.closed;
+ } catch (err) {
+ stats.emit_error = (stats.emit_error || 0) + 1;
+ stats.last_emit_error = (err?.message || 'error').slice(0, 160);
+ }
+ }
+}
+
+// PASS 2 — deliver undelivered emissions to active subscriptions.
+async function deliverPass(network, stats) {
+ const subs = await sql`
+ SELECT s.*
+ FROM signal_subscriptions s
+ JOIN signal_feeds f ON f.id = s.feed_id AND f.status = 'active'
+ JOIN agent_identities sa ON sa.id = s.subscriber_agent_id AND sa.deleted_at IS NULL
+ WHERE s.status = 'active' AND s.killed = false AND s.network = ${network}
+ AND EXISTS (
+ SELECT 1 FROM signal_emissions e
+ WHERE e.feed_id = s.feed_id AND e.id > s.last_emission_id
+ )
+ ORDER BY s.updated_at ASC
+ LIMIT ${MAX_SUBS_PER_RUN}
+ `;
+ if (!subs.length) return;
+ stats.subscriptions = (stats.subscriptions || 0) + subs.length;
+ for (const s of subs) {
+ try {
+ const r = await deliverSubscription(s, { maxEvents: MAX_EVENTS_PER_SUB });
+ for (const d of r.results) {
+ const key = d.mirror_status || d.status || 'unknown';
+ stats[`mirror_${key}`] = (stats[`mirror_${key}`] || 0) + 1;
+ }
+ } catch (err) {
+ stats.deliver_error = (stats.deliver_error || 0) + 1;
+ stats.last_deliver_error = (err?.message || 'error').slice(0, 160);
+ }
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const stats = {};
+ for (const network of NETWORKS) {
+ try {
+ await emitPass(network, stats);
+ await deliverPass(network, stats);
+ } catch (err) {
+ stats[`error_${network}`] = (err?.message || 'error').slice(0, 160);
+ }
+ }
+ return json(res, 200, { ok: true, ...stats });
+});
diff --git a/api/signals/_common.js b/api/signals/_common.js
new file mode 100644
index 000000000..c7f8aafbe
--- /dev/null
+++ b/api/signals/_common.js
@@ -0,0 +1,50 @@
+// Shared helpers for the signal-marketplace endpoints (api/signals/*).
+//
+// Auth model: every write is owner-authenticated (session cookie or bearer) and
+// scoped to an agent the caller owns. Reads of the public directory are open;
+// reads of a paid stream require entitlement (publisher or active subscriber).
+
+import { error } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+
+export const NETWORKS = new Set(['mainnet', 'devnet']);
+export const normNetwork = (n) => (n === 'devnet' ? 'devnet' : 'mainnet');
+
+/** Resolve the calling user (session or bearer). Writes 401 + returns null on miss. */
+export async function requireUser(req, res) {
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) { error(res, 401, 'unauthorized', 'sign in required'); return null; }
+ return { userId: session?.id ?? bearer.userId, viaSession: !!session };
+}
+
+/**
+ * Load an agent the caller owns. Writes the error response and returns
+ * { error:true } on any failure; returns { row, meta } on success.
+ */
+export async function loadOwnedAgent(req, res, userId, agentId) {
+ if (!agentId || typeof agentId !== 'string') { error(res, 400, 'invalid_agent', 'agent_id required'); return { error: true }; }
+ const [row] = await sql`
+ SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `.catch(() => []);
+ if (!row) { error(res, 404, 'not_found', 'agent not found'); return { error: true }; }
+ if (row.user_id !== userId) { error(res, 403, 'forbidden', 'not your agent'); return { error: true }; }
+ return { row, meta: { ...(row.meta || {}) } };
+}
+
+/** Kebab slug from arbitrary text, bounded. */
+export function slugify(text, max = 40) {
+ return String(text || '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/(^-|-$)+/g, '')
+ .slice(0, max) || 'feed';
+}
+
+/** A stable, collision-resistant feed slug from the agent name + id. */
+export function feedSlug(name, agentId, network) {
+ const base = slugify(name);
+ const tail = String(agentId).replace(/-/g, '').slice(0, 8);
+ return network === 'devnet' ? `${base}-${tail}-dev` : `${base}-${tail}`;
+}
diff --git a/api/signals/feed.js b/api/signals/feed.js
new file mode 100644
index 000000000..8b5063200
--- /dev/null
+++ b/api/signals/feed.js
@@ -0,0 +1,32 @@
+/**
+ * GET /api/signals/feed?slug=<slug>&network=mainnet
+ *
+ * One feed's public detail page: the publisher's verified track record, the
+ * feed's proven signal accuracy (hit-rate, avg realized ROI, follower ROI,
+ * emit→fill latency), pricing, and the recent emission log — every signal with
+ * its realized outcome and a link to the on-chain tx that proves it.
+ */
+
+import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getFeedDetail } from '../_lib/signal-engine.js';
+import { normNetwork } from './_common.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const slug = url.searchParams.get('slug');
+ if (!slug) return error(res, 400, 'invalid_slug', 'slug required');
+ const network = normNetwork(url.searchParams.get('network'));
+
+ const detail = await getFeedDetail({ slug, network });
+ if (!detail) return error(res, 404, 'not_found', 'feed not found');
+
+ res.setHeader('cache-control', 'public, max-age=10, stale-while-revalidate=30');
+ return json(res, 200, { feed: detail });
+});
diff --git a/api/signals/feeds.js b/api/signals/feeds.js
new file mode 100644
index 000000000..1dcf332a0
--- /dev/null
+++ b/api/signals/feeds.js
@@ -0,0 +1,194 @@
+/**
+ * Signal feeds — the publisher's CRUD surface.
+ *
+ * GET /api/signals/feeds list the caller's feeds
+ * GET /api/signals/feeds?agent_id=&network= one agent's feed + publish eligibility
+ * POST /api/signals/feeds create / update a feed (verified gate)
+ * POST /api/signals/feeds { id, status } pause / resume
+ * DELETE /api/signals/feeds?id= pause (soft — keeps signal history)
+ *
+ * Publishing is gated on a REAL, verified on-chain track record: the publisher
+ * agent must clear api/_lib/trader-stats.js's `verified` badge (12+ closed trades,
+ * 5+ coins, ≤40% churn, positive realized SOL). An unproven wallet gets a 403 with
+ * the exact thresholds it still has to meet — sellers can never self-declare edge.
+ */
+
+import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { sql } from '../_lib/db.js';
+import { publisherMetrics } from '../_lib/signal-engine.js';
+import { requireUser, loadOwnedAgent, normNetwork, NETWORKS, feedSlug } from './_common.js';
+
+const MAX_USDC = 1000; // sane per-signal / per-epoch ceiling
+const MIN_EPOCH_SECONDS = 3600; // 1 hour
+const MAX_EPOCH_SECONDS = 30 * 86400;
+
+function num(v, fallback = 0) {
+ const n = Number(v);
+ return Number.isFinite(n) ? n : fallback;
+}
+
+function shapeFeedRow(f) {
+ return {
+ id: Number(f.id),
+ publisher_agent_id: f.publisher_agent_id,
+ network: f.network,
+ slug: f.slug,
+ title: f.title,
+ description: f.description || null,
+ price_per_signal_usdc: num(f.price_per_signal_usdc),
+ price_per_epoch_usdc: num(f.price_per_epoch_usdc),
+ epoch_seconds: num(f.epoch_seconds, 86400),
+ emit_entries: f.emit_entries,
+ emit_exits: f.emit_exits,
+ reveal_sizing: f.reveal_sizing,
+ min_conviction: num(f.min_conviction),
+ visibility: f.visibility,
+ status: f.status,
+ payout_address: f.payout_address,
+ created_at: f.created_at,
+ updated_at: f.updated_at,
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const auth = await requireUser(req, res);
+ if (!auth) return;
+ const { userId } = auth;
+
+ // ── GET ───────────────────────────────────────────────────────────────────
+ if (req.method === 'GET') {
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agent_id');
+ const network = normNetwork(url.searchParams.get('network'));
+
+ if (agentId) {
+ const owned = await loadOwnedAgent(req, res, userId, agentId);
+ if (owned.error) return;
+ const [feed] = await sql`
+ select * from signal_feeds where publisher_agent_id = ${agentId} and network = ${network} limit 1
+ `;
+ const metrics = await publisherMetrics(agentId, network).catch(() => null);
+ const eligible = !!metrics?.verified;
+ return json(res, 200, {
+ feed: feed ? shapeFeedRow(feed) : null,
+ eligibility: {
+ verified: eligible,
+ score: metrics?.score ?? null,
+ closed_trades: metrics?.closed_count ?? 0,
+ unique_coins: metrics?.unique_coins ?? 0,
+ churn_pct: metrics?.churn_pct ?? null,
+ realized_pnl_sol: metrics?.realized_pnl_sol ?? null,
+ requirements: { min_closed: 12, min_unique_coins: 5, max_churn_pct: 40, positive_realized: true },
+ },
+ solana_address: owned.meta.solana_address || null,
+ });
+ }
+
+ const rows = await sql`
+ select f.*, a.name as publisher_name
+ from signal_feeds f join agent_identities a on a.id = f.publisher_agent_id
+ where f.owner_user_id = ${userId}
+ order by f.created_at desc
+ `;
+ return json(res, 200, { feeds: rows.map((f) => ({ ...shapeFeedRow(f), publisher_name: f.publisher_name })) });
+ }
+
+ // State-changing methods: CSRF for cookie sessions.
+ if (auth.viaSession && !(await requireCsrf(req, res, userId))) return;
+
+ // ── DELETE (soft pause) ─────────────────────────────────────────────────────
+ if (req.method === 'DELETE') {
+ const id = new URL(req.url, 'http://x').searchParams.get('id');
+ if (!id) return error(res, 400, 'invalid_id', 'id required');
+ const [row] = await sql`
+ update signal_feeds set status = 'paused', updated_at = now()
+ where id = ${id} and owner_user_id = ${userId} returning id
+ `;
+ if (!row) return error(res, 404, 'not_found', 'feed not found');
+ return json(res, 200, { ok: true, id: Number(row.id), status: 'paused' });
+ }
+
+ // ── POST ────────────────────────────────────────────────────────────────────
+ const body = await readJson(req).catch(() => null);
+ if (!body) return error(res, 400, 'bad_request', 'JSON body required');
+
+ // Pause / resume an existing feed.
+ if (body.id && body.status && !body.agent_id) {
+ const status = body.status === 'active' ? 'active' : 'paused';
+ const [row] = await sql`
+ update signal_feeds set status = ${status}, updated_at = now()
+ where id = ${body.id} and owner_user_id = ${userId} returning *
+ `;
+ if (!row) return error(res, 404, 'not_found', 'feed not found');
+ return json(res, 200, { feed: shapeFeedRow(row) });
+ }
+
+ const network = normNetwork(body.network);
+ if (body.network && !NETWORKS.has(body.network)) return error(res, 400, 'invalid_network', 'network must be mainnet or devnet');
+
+ const owned = await loadOwnedAgent(req, res, userId, body.agent_id);
+ if (owned.error) return;
+
+ const payoutAddress = owned.meta.solana_address;
+ if (!payoutAddress) return error(res, 409, 'wallet_preparing', 'agent wallet is still being provisioned — try again shortly');
+
+ // THE GATE: only a verified track record may publish.
+ const metrics = await publisherMetrics(body.agent_id, network).catch(() => null);
+ if (!metrics?.verified) {
+ return error(res, 403, 'not_verified', 'Only a verified track record can publish signals.', {
+ eligibility: {
+ score: metrics?.score ?? null,
+ closed_trades: metrics?.closed_count ?? 0,
+ unique_coins: metrics?.unique_coins ?? 0,
+ churn_pct: metrics?.churn_pct ?? null,
+ realized_pnl_sol: metrics?.realized_pnl_sol ?? null,
+ requirements: { min_closed: 12, min_unique_coins: 5, max_churn_pct: 40, positive_realized: true },
+ },
+ });
+ }
+
+ // Validate input.
+ const title = String(body.title || owned.row.name || 'Signals').trim().slice(0, 80);
+ const description = body.description != null ? String(body.description).trim().slice(0, 500) : null;
+ const perSignal = Math.max(0, Math.min(MAX_USDC, num(body.price_per_signal_usdc)));
+ const perEpoch = Math.max(0, Math.min(MAX_USDC, num(body.price_per_epoch_usdc)));
+ if (perSignal <= 0 && perEpoch <= 0) {
+ return error(res, 400, 'no_price', 'set a per-signal and/or per-epoch USDC price (one must be > 0)');
+ }
+ const epochSeconds = Math.round(Math.max(MIN_EPOCH_SECONDS, Math.min(MAX_EPOCH_SECONDS, num(body.epoch_seconds, 86400))));
+ const minConviction = Math.max(0, Math.min(1, num(body.min_conviction)));
+ const visibility = body.visibility === 'unlisted' ? 'unlisted' : 'public';
+ const emitEntries = body.emit_entries !== false;
+ const emitExits = body.emit_exits !== false;
+ const revealSizing = body.reveal_sizing !== false;
+ if (!emitEntries && !emitExits) return error(res, 400, 'no_emission', 'emit entries and/or exits (one must be on)');
+
+ const slug = feedSlug(owned.row.name || title, body.agent_id, network);
+
+ const [feed] = await sql`
+ insert into signal_feeds
+ (publisher_agent_id, owner_user_id, network, slug, title, description,
+ price_per_signal_usdc, price_per_epoch_usdc, epoch_seconds,
+ emit_entries, emit_exits, reveal_sizing, min_conviction, visibility, status, payout_address)
+ values (${body.agent_id}, ${userId}, ${network}, ${slug}, ${title}, ${description},
+ ${perSignal}, ${perEpoch}, ${epochSeconds},
+ ${emitEntries}, ${emitExits}, ${revealSizing}, ${minConviction}, ${visibility}, 'active', ${payoutAddress})
+ on conflict (publisher_agent_id, network) do update set
+ title = excluded.title, description = excluded.description,
+ price_per_signal_usdc = excluded.price_per_signal_usdc, price_per_epoch_usdc = excluded.price_per_epoch_usdc,
+ epoch_seconds = excluded.epoch_seconds, emit_entries = excluded.emit_entries, emit_exits = excluded.emit_exits,
+ reveal_sizing = excluded.reveal_sizing, min_conviction = excluded.min_conviction,
+ visibility = excluded.visibility, status = 'active', payout_address = excluded.payout_address,
+ updated_at = now()
+ returning *
+ `;
+ return json(res, 200, { feed: shapeFeedRow(feed) });
+});
diff --git a/api/signals/marketplace.js b/api/signals/marketplace.js
new file mode 100644
index 000000000..e9d74ed4b
--- /dev/null
+++ b/api/signals/marketplace.js
@@ -0,0 +1,31 @@
+/**
+ * GET /api/signals/marketplace?network=mainnet&sort=edge&limit=60
+ *
+ * The public signal-feed directory. Every active, public feed is scored by its
+ * PROVEN realized edge — hit-rate × realized ROI, confidence-regressed toward the
+ * publisher's own verified track-record score until enough signals have closed —
+ * and ranked. A thin feed riding one lucky call can never top a deep, consistent
+ * one. Open read: no auth, cacheable.
+ */
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getMarketplace, FEED_SORTS } from '../_lib/signal-engine.js';
+import { normNetwork } from './_common.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const network = normNetwork(url.searchParams.get('network'));
+ const sort = FEED_SORTS.has(url.searchParams.get('sort')) ? url.searchParams.get('sort') : 'edge';
+ const limit = Math.max(1, Math.min(100, Number(url.searchParams.get('limit')) || 60));
+
+ const result = await getMarketplace({ network, sort, limit });
+ res.setHeader('cache-control', 'public, max-age=15, stale-while-revalidate=60');
+ return json(res, 200, result);
+});
diff --git a/api/signals/stream.js b/api/signals/stream.js
new file mode 100644
index 000000000..742ad945f
--- /dev/null
+++ b/api/signals/stream.js
@@ -0,0 +1,143 @@
+/**
+ * GET /api/signals/stream?slug=<feed>&network=mainnet
+ *
+ * The PAID live feed of a publisher's emissions, as Server-Sent Events. Reads are
+ * gated by entitlement: the caller must either own the publishing agent (the
+ * publisher previews their own feed) or own an agent with an ACTIVE, non-killed
+ * subscription to it — and that subscription is what settles the x402 USDC, so a
+ * non-subscriber can never read the live alpha. Unentitled callers get a 402.
+ *
+ * Like the sniper stream, this DB-polls signal_emissions (Neon serverless HTTP
+ * can't hold a LISTEN), emitting only signals minted after connect; the feed
+ * detail endpoint supplies the historical backlog the page renders on load.
+ *
+ * Events: open, signal, ping, close.
+ */
+
+import { cors, method, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { normNetwork, NETWORKS } from './_common.js';
+
+const MAX_DURATION_MS = 90_000;
+const PING_INTERVAL_MS = 15_000;
+const POLL_INTERVAL_MS = 2_000;
+
+function solscan(sig, network) {
+ if (!sig || sig === 'SIMULATED') return null;
+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;
+}
+
+function shape(e, network) {
+ return {
+ id: Number(e.id),
+ side: e.side,
+ mint: e.mint,
+ symbol: e.symbol,
+ name: e.name,
+ size_multiple: e.size_multiple != null ? Number(e.size_multiple) : null,
+ conviction: e.conviction != null ? Number(e.conviction) : null,
+ entry_sol: e.entry_sol != null ? Number(e.entry_sol) : null,
+ status: e.status,
+ realized_pnl_pct: e.realized_pnl_pct != null ? Number(e.realized_pnl_pct) : null,
+ outcome: e.outcome,
+ buy_url: solscan(e.source_buy_sig, network),
+ sell_url: solscan(e.source_sell_sig, network),
+ emitted_at: e.emitted_at,
+ };
+}
+
+export default async function handleSignalStream(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const slug = url.searchParams.get('slug');
+ if (!slug) return error(res, 400, 'invalid_slug', 'slug required');
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : normNetwork(url.searchParams.get('network'));
+
+ // Authenticate.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [feed] = await sql`select id, network, owner_user_id from signal_feeds where slug = ${slug} limit 1`;
+ if (!feed) return error(res, 404, 'not_found', 'feed not found');
+
+ // Entitlement: publisher-owner OR an active, non-killed subscriber.
+ let entitled = feed.owner_user_id === userId;
+ if (!entitled) {
+ const [sub] = await sql`
+ select 1 from signal_subscriptions
+ where feed_id = ${feed.id} and owner_user_id = ${userId} and status = 'active' and killed = false limit 1
+ `;
+ entitled = !!sub;
+ }
+ if (!entitled) {
+ return error(res, 402, 'payment_required', 'subscribe to this feed to read its live signals');
+ }
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => {
+ if (!active) return;
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ };
+
+ // Start from the current head so we stream only fresh emissions.
+ let cursor = 0;
+ try {
+ const [head] = await sql`select coalesce(max(id),0) as head from signal_emissions where feed_id = ${feed.id}`;
+ cursor = Number(head?.head || 0);
+ } catch { cursor = 0; }
+
+ const poll = async () => {
+ if (!active) return;
+ try {
+ const rows = await sql`
+ select id, side, mint, symbol, name, size_multiple, conviction, entry_sol, status,
+ realized_pnl_pct, outcome, source_buy_sig, source_sell_sig, emitted_at
+ from signal_emissions
+ where feed_id = ${feed.id} and id > ${cursor}
+ order by id asc limit 100
+ `;
+ for (const r of rows) {
+ send('signal', shape(r, network));
+ if (Number(r.id) > cursor) cursor = Number(r.id);
+ }
+ } catch {
+ send('error', { message: 'poll_failed' });
+ }
+ };
+
+ send('open', { slug, network, source: 'signal-marketplace' });
+ const pollTimer = setInterval(poll, POLL_INTERVAL_MS);
+ const ping = setInterval(() => send('ping', { t: Date.now() }), PING_INTERVAL_MS);
+
+ const teardown = () => {
+ if (!active) return;
+ active = false;
+ clearInterval(pollTimer);
+ clearInterval(ping);
+ clearTimeout(durationTimer);
+ try { res.end(); } catch {}
+ };
+ const durationTimer = setTimeout(() => {
+ send('close', { reason: 'duration_limit' });
+ teardown();
+ }, MAX_DURATION_MS);
+
+ req.on('close', teardown);
+}
diff --git a/api/signals/subscribe.js b/api/signals/subscribe.js
new file mode 100644
index 000000000..640ab98a1
--- /dev/null
+++ b/api/signals/subscribe.js
@@ -0,0 +1,179 @@
+/**
+ * Signal subscriptions — the follower's control surface.
+ *
+ * GET /api/signals/subscribe list the caller's subscriptions
+ * POST /api/signals/subscribe create / update a subscription
+ * POST /api/signals/subscribe { id, status } pause / resume / stop
+ * POST /api/signals/subscribe { id, killed:true } INSTANT kill (no further pay/trade)
+ * POST /api/signals/subscribe { id, action:'sync' } deliver pending now (owner-triggered)
+ * DELETE /api/signals/subscribe?id= stop (soft — keeps delivery history)
+ *
+ * A subscriber agent's own custodial wallet pays the x402 USDC and signs the
+ * mirror, so a subscription is owner-authenticated and scoped to an agent the
+ * caller owns. `mode:'simulate'` mirrors WITHOUT paying or trading (trust-building);
+ * `live` does both within the agent's spend policy. `killed` halts everything the
+ * instant it is set — the kill is honoured before any payment or trade fires.
+ */
+
+import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { sql } from '../_lib/db.js';
+import { deliverSubscription } from '../_lib/signal-engine.js';
+import { requireUser, loadOwnedAgent, normNetwork } from './_common.js';
+
+function num(v, fallback) { const n = Number(v); return Number.isFinite(n) ? n : fallback; }
+
+function shapeSub(s) {
+ return {
+ id: Number(s.id),
+ subscriber_agent_id: s.subscriber_agent_id,
+ feed_id: Number(s.feed_id),
+ network: s.network,
+ mode: s.mode,
+ billing: s.billing,
+ base_sol: num(s.base_sol, 0),
+ size_scaling: num(s.size_scaling, 1),
+ max_per_trade_sol: num(s.max_per_trade_sol, 0),
+ slippage_bps: num(s.slippage_bps, 300),
+ firewall_level: s.firewall_level,
+ copy_exits: s.copy_exits,
+ status: s.status,
+ killed: s.killed,
+ epoch_paid_until: s.epoch_paid_until || null,
+ last_emission_id: Number(s.last_emission_id || 0),
+ created_at: s.created_at,
+ updated_at: s.updated_at,
+ };
+}
+
+async function listForUser(userId) {
+ const rows = await sql`
+ select s.*, f.slug as feed_slug, f.title as feed_title,
+ f.price_per_signal_usdc, f.price_per_epoch_usdc, f.epoch_seconds,
+ a.name as publisher_name, a.profile_image_url as publisher_image, a.avatar_url as publisher_avatar,
+ sub.name as subscriber_name,
+ (select count(*) from signal_deliveries d where d.subscription_id = s.id and d.mirror_status = 'executed') as executed,
+ (select count(*) from signal_deliveries d where d.subscription_id = s.id and d.payment_status = 'paid') as paid_count,
+ (select coalesce(sum(d.payment_usdc),0) from signal_deliveries d where d.subscription_id = s.id and d.payment_status = 'paid') as usdc_spent
+ from signal_subscriptions s
+ join signal_feeds f on f.id = s.feed_id
+ join agent_identities a on a.id = f.publisher_agent_id
+ join agent_identities sub on sub.id = s.subscriber_agent_id
+ where s.owner_user_id = ${userId}
+ order by s.created_at desc
+ `;
+ return rows.map((s) => ({
+ ...shapeSub(s),
+ feed: { slug: s.feed_slug, title: s.feed_title, publisher_name: s.publisher_name, publisher_image: s.publisher_image || s.publisher_avatar || null,
+ price_per_signal_usdc: num(s.price_per_signal_usdc, 0), price_per_epoch_usdc: num(s.price_per_epoch_usdc, 0), epoch_seconds: num(s.epoch_seconds, 86400) },
+ subscriber_name: s.subscriber_name,
+ stats: { executed: Number(s.executed) || 0, paid_count: Number(s.paid_count) || 0, usdc_spent: Number(s.usdc_spent) || 0 },
+ }));
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const auth = await requireUser(req, res);
+ if (!auth) return;
+ const { userId } = auth;
+
+ if (req.method === 'GET') {
+ return json(res, 200, { subscriptions: await listForUser(userId) });
+ }
+
+ if (auth.viaSession && !(await requireCsrf(req, res, userId))) return;
+
+ if (req.method === 'DELETE') {
+ const id = new URL(req.url, 'http://x').searchParams.get('id');
+ if (!id) return error(res, 400, 'invalid_id', 'id required');
+ const [row] = await sql`
+ update signal_subscriptions set status = 'stopped', updated_at = now()
+ where id = ${id} and owner_user_id = ${userId} returning id
+ `;
+ if (!row) return error(res, 404, 'not_found', 'subscription not found');
+ return json(res, 200, { ok: true, id: Number(row.id), status: 'stopped' });
+ }
+
+ const body = await readJson(req).catch(() => null);
+ if (!body) return error(res, 400, 'bad_request', 'JSON body required');
+
+ // ── Mutations on an existing subscription (status / kill / sync) ────────────
+ if (body.id && !body.feed_id) {
+ // Instant kill — the halt path, takes precedence.
+ if (body.killed != null) {
+ const killed = body.killed === true || body.killed === 'true';
+ const [row] = await sql`
+ update signal_subscriptions set killed = ${killed}, status = ${killed ? 'paused' : 'active'}, updated_at = now()
+ where id = ${body.id} and owner_user_id = ${userId} returning *
+ `;
+ if (!row) return error(res, 404, 'not_found', 'subscription not found');
+ return json(res, 200, { subscription: shapeSub(row) });
+ }
+ if (body.action === 'sync') {
+ const [row] = await sql`select * from signal_subscriptions where id = ${body.id} and owner_user_id = ${userId} limit 1`;
+ if (!row) return error(res, 404, 'not_found', 'subscription not found');
+ const result = await deliverSubscription(row, { maxEvents: 10 });
+ return json(res, 200, { ok: true, ...result });
+ }
+ if (body.status) {
+ const status = ['active', 'paused', 'stopped'].includes(body.status) ? body.status : 'paused';
+ // Resuming clears any kill; pausing/stopping leaves the kill flag untouched.
+ const [row] = status === 'active'
+ ? await sql`
+ update signal_subscriptions set status = 'active', killed = false, updated_at = now()
+ where id = ${body.id} and owner_user_id = ${userId} returning *`
+ : await sql`
+ update signal_subscriptions set status = ${status}, updated_at = now()
+ where id = ${body.id} and owner_user_id = ${userId} returning *`;
+ if (!row) return error(res, 404, 'not_found', 'subscription not found');
+ return json(res, 200, { subscription: shapeSub(row) });
+ }
+ return error(res, 400, 'no_op', 'nothing to update');
+ }
+
+ // ── Create / update a subscription ──────────────────────────────────────────
+ if (!body.feed_id) return error(res, 400, 'invalid_feed', 'feed_id required');
+ const owned = await loadOwnedAgent(req, res, userId, body.agent_id);
+ if (owned.error) return;
+
+ const [feed] = await sql`select * from signal_feeds where id = ${body.feed_id} limit 1`;
+ if (!feed) return error(res, 404, 'feed_not_found', 'feed not found');
+ if (feed.status !== 'active') return error(res, 409, 'feed_inactive', 'this feed is not active');
+ if (feed.publisher_agent_id === body.agent_id) return error(res, 400, 'self_subscribe', 'an agent cannot subscribe to its own feed');
+
+ const network = normNetwork(feed.network);
+ const mode = body.mode === 'live' ? 'live' : 'simulate';
+ const billing = body.billing === 'per_epoch' ? 'per_epoch' : 'per_signal';
+ const baseSol = Math.max(0.001, Math.min(10, num(body.base_sol, 0.05)));
+ const sizeScaling = Math.max(0.01, Math.min(20, num(body.size_scaling, 1)));
+ const maxPerTrade = Math.max(0.001, Math.min(50, num(body.max_per_trade_sol, 0.25)));
+ const slippageBps = Math.round(Math.max(0, Math.min(5000, num(body.slippage_bps, 300))));
+ const firewallLevel = body.firewall_level === 'warn' ? 'warn' : 'block';
+ const copyExits = body.copy_exits !== false;
+
+ // New subscriptions start at the current emission head — never charged for or
+ // made to mirror a backlog of signals emitted before they subscribed.
+ const [head] = await sql`select coalesce(max(id),0) as head from signal_emissions where feed_id = ${feed.id}`;
+ const startCursor = Number(head?.head || 0);
+
+ const [sub] = await sql`
+ insert into signal_subscriptions
+ (subscriber_agent_id, owner_user_id, feed_id, network, mode, billing,
+ base_sol, size_scaling, max_per_trade_sol, slippage_bps, firewall_level, copy_exits, status, killed, last_emission_id)
+ values (${body.agent_id}, ${userId}, ${feed.id}, ${network}, ${mode}, ${billing},
+ ${baseSol}, ${sizeScaling}, ${maxPerTrade}, ${slippageBps}, ${firewallLevel}, ${copyExits}, 'active', false, ${startCursor})
+ on conflict (subscriber_agent_id, feed_id) do update set
+ mode = excluded.mode, billing = excluded.billing, base_sol = excluded.base_sol,
+ size_scaling = excluded.size_scaling, max_per_trade_sol = excluded.max_per_trade_sol,
+ slippage_bps = excluded.slippage_bps, firewall_level = excluded.firewall_level,
+ copy_exits = excluded.copy_exits, status = 'active', killed = false, updated_at = now()
+ returning *
+ `;
+ return json(res, 200, { subscription: shapeSub(sub) });
+});
diff --git a/api/sniper/radar-stream.js b/api/sniper/radar-stream.js
new file mode 100644
index 000000000..c41fe3563
--- /dev/null
+++ b/api/sniper/radar-stream.js
@@ -0,0 +1,140 @@
+/**
+ * Agent Sniper — Pre-Launch Radar live SSE stream.
+ *
+ * GET /api/sniper/radar-stream?network=mainnet
+ *
+ * The radar worker is a SEPARATE process, so this endpoint can't read its memory —
+ * it DB-polls radar_events for rows newer than a cursor (~1.5s) and emits each as a
+ * `precursor` event. Mirrors api/sniper/stream.js (Neon serverless HTTP can't hold
+ * a LISTEN connection).
+ *
+ * Owner (session/bearer) sees full wallet addresses + whether their agent fired;
+ * the public stream is anonymized (truncated addresses, no owner correlation).
+ *
+ * Events: open, precursor, ping, close.
+ */
+
+import { cors, method, rateLimited } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+const MAX_DURATION_MS = 90_000;
+const PING_INTERVAL_MS = 15_000;
+const POLL_INTERVAL_MS = 1_500;
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+function trunc(addr) {
+ if (!addr || typeof addr !== 'string' || addr.length < 10) return addr || null;
+ return `${addr.slice(0, 4)}…${addr.slice(-4)}`;
+}
+
+async function resolveUserId(req) {
+ try {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ } catch {}
+ return null;
+}
+
+export default async function handleRadarStream(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+ const userId = await resolveUserId(req);
+ const isOwner = !!userId;
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => {
+ if (!active) return;
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ };
+
+ // Start from "now" so we stream only fresh precursors; the REST endpoint
+ // supplies the backlog the page renders on load.
+ let cursor = new Date().toISOString();
+
+ const poll = async () => {
+ if (!active) return;
+ try {
+ const rows = await sql`
+ select id, kind, trigger_wallet, new_wallet, mint, confidence,
+ watch_reason, watch_score, observed_ts, created_at
+ from radar_events
+ where network = ${network} and created_at > ${cursor}
+ order by created_at asc
+ limit 100
+ `;
+ if (!rows.length) return;
+
+ // Owner correlation: did any of these mints get sniped by the owner's agents?
+ let firedMints = new Set();
+ if (isOwner) {
+ const mints = rows.map((r) => r.mint).filter(Boolean);
+ if (mints.length) {
+ try {
+ const pos = await sql`
+ select distinct mint from agent_sniper_positions
+ where user_id = ${userId} and network = ${network}
+ and entry_trigger = 'prelaunch_radar' and mint = any(${mints})
+ `;
+ firedMints = new Set(pos.map((p) => p.mint));
+ } catch {}
+ }
+ }
+
+ for (const r of rows) {
+ send('precursor', {
+ id: r.id,
+ kind: r.kind,
+ trigger_wallet: isOwner ? r.trigger_wallet : trunc(r.trigger_wallet),
+ new_wallet: isOwner ? r.new_wallet : trunc(r.new_wallet),
+ mint: r.mint,
+ confidence: Number(r.confidence),
+ watch_reason: r.watch_reason,
+ watch_score: r.watch_score != null ? Number(r.watch_score) : null,
+ observed_ts: r.observed_ts,
+ at: r.created_at,
+ fired: isOwner ? firedMints.has(r.mint) : undefined,
+ });
+ if (r.created_at > cursor) cursor = r.created_at;
+ }
+ } catch {
+ send('error', { message: 'poll_failed' });
+ }
+ };
+
+ send('open', { network, source: 'prelaunch-radar', owner: isOwner });
+ const pollTimer = setInterval(poll, POLL_INTERVAL_MS);
+ const ping = setInterval(() => send('ping', { t: Date.now() }), PING_INTERVAL_MS);
+
+ const teardown = () => {
+ if (!active) return;
+ active = false;
+ clearInterval(pollTimer);
+ clearInterval(ping);
+ clearTimeout(durationTimer);
+ try { res.end(); } catch {}
+ };
+ const durationTimer = setTimeout(() => {
+ send('close', { reason: 'duration_limit' });
+ teardown();
+ }, MAX_DURATION_MS);
+
+ req.on('close', teardown);
+}
diff --git a/api/sniper/radar.js b/api/sniper/radar.js
new file mode 100644
index 000000000..461566a1e
--- /dev/null
+++ b/api/sniper/radar.js
@@ -0,0 +1,216 @@
+/**
+ * Agent Sniper — Pre-Launch Radar API.
+ *
+ * GET /api/sniper/radar?network=mainnet
+ *
+ * The radar (workers/agent-sniper/prelaunch-radar.js) watches proven creator +
+ * smart-money wallets on-chain and records launch precursors to radar_events,
+ * curating the monitored set into radar_watchlist. This endpoint surfaces both:
+ *
+ * • Public (no auth): the anonymized live precursor stream — recent event counts,
+ * the radar's operational state, and a redacted recent-events tape. Wallet
+ * addresses are truncated; no owner-specific data leaks.
+ * • Owner (session or bearer): full watchlist with the reason each wallet is
+ * watched, full-detail recent events, their armed prelaunch_radar strategies,
+ * and — correlating radar_events.mint with their positions — whether their
+ * agent actually fired on a precursor.
+ *
+ * Honest degradation: the radar's state is read from the worker's heartbeat. If
+ * the worker hasn't reported, state is 'unknown' rather than a false green.
+ */
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const HEARTBEAT_FRESH_MS = 90_000;
+
+function trunc(addr) {
+ if (!addr || typeof addr !== 'string' || addr.length < 10) return addr || null;
+ return `${addr.slice(0, 4)}…${addr.slice(-4)}`;
+}
+
+async function resolveUserId(req) {
+ try {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ } catch {}
+ return null;
+}
+
+async function radarStatus() {
+ try {
+ const [beat] = await sql`
+ SELECT last_beat_at, meta FROM bot_heartbeat WHERE worker = 'agent-sniper' LIMIT 1
+ `;
+ if (!beat) return { state: 'unknown', reason: 'no heartbeat reported yet' };
+ const ageMs = beat.last_beat_at ? Date.now() - new Date(beat.last_beat_at).getTime() : null;
+ const alive = ageMs != null && ageMs < HEARTBEAT_FRESH_MS;
+ const meta = beat.meta && typeof beat.meta === 'object' ? beat.meta : {};
+ const r = meta.radar && typeof meta.radar === 'object' ? meta.radar : null;
+ if (!alive) return { state: 'down', reason: 'worker heartbeat stale' };
+ if (!r) return { state: 'unknown', reason: 'radar not reporting' };
+ const state = r.paused ? 'paused' : r.active ? 'live' : 'unknown';
+ return {
+ state,
+ source: r.source ?? null,
+ reason: r.reason ?? null,
+ watched: r.watched ?? null,
+ deployWatch: r.deployWatch ?? null,
+ events: r.events ?? null,
+ prearmed: r.prearmed ?? null,
+ lastEventAgeMs: r.lastEventAt ? Date.now() - r.lastEventAt : null,
+ lastTickAgeMs: r.lastTickAt ? Date.now() - r.lastTickAt : null,
+ };
+ } catch {
+ return { state: 'unknown', reason: 'status store unreachable' };
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+ const userId = await resolveUserId(req);
+
+ let status, watchRows, eventRows, counts;
+ try {
+ [status, watchRows, eventRows, counts] = await Promise.all([
+ radarStatus(),
+ sql`
+ select address, reason, source, score, creator_graduated, realized_score, labels,
+ added_at, last_hit_at, hits
+ from radar_watchlist
+ where network = ${network}
+ order by score desc
+ limit 100
+ `,
+ sql`
+ select id, kind, trigger_wallet, new_wallet, mint, confidence,
+ watch_reason, watch_score, observed_ts, created_at
+ from radar_events
+ where network = ${network}
+ order by created_at desc
+ limit 60
+ `,
+ sql`
+ select
+ count(*) filter (where created_at > now() - interval '1 hour') as events_1h,
+ count(*) filter (where created_at > now() - interval '24 hours') as events_24h,
+ count(*) filter (where mint is not null and created_at > now() - interval '24 hours') as armable_24h
+ from radar_events
+ where network = ${network}
+ `.then((r) => r[0] || {}),
+ ]);
+ } catch (err) {
+ return json(res, 200, {
+ ok: false, network, state: 'unknown',
+ error: err?.code || 'db_error',
+ status: { state: 'unknown', reason: 'radar store unreachable' },
+ watchlist: [], events: [], counts: { events_1h: 0, events_24h: 0, armable_24h: 0 },
+ }, { 'cache-control': 'public, max-age=5' });
+ }
+
+ const isOwner = !!userId;
+
+ // Which event mints did THIS owner's agents actually fire on?
+ let firedMints = new Set();
+ let armed = null;
+ if (isOwner) {
+ try {
+ const mints = eventRows.map((e) => e.mint).filter(Boolean);
+ const [positions, strategies] = await Promise.all([
+ mints.length
+ ? sql`
+ select mint, status, realized_pnl_lamports, buy_sig
+ from agent_sniper_positions
+ where user_id = ${userId} and network = ${network}
+ and entry_trigger = 'prelaunch_radar' and mint = any(${mints})
+ `
+ : Promise.resolve([]),
+ sql`
+ select s.agent_id, a.name as agent_name, s.enabled, s.kill_switch,
+ s.min_creator_graduated_radar, s.require_smart_money_funder, s.radar_max_age_ms,
+ s.per_trade_lamports
+ from agent_sniper_strategies s
+ join agent_identities a on a.id = s.agent_id
+ where s.user_id = ${userId} and s.network = ${network} and s.trigger = 'prelaunch_radar'
+ order by s.updated_at desc
+ `,
+ ]);
+ firedMints = new Set(positions.map((p) => p.mint));
+ const posByMint = new Map(positions.map((p) => [p.mint, p]));
+ armed = {
+ strategies: strategies.map((s) => ({
+ agent_id: s.agent_id, agent_name: s.agent_name,
+ enabled: s.enabled, kill_switch: s.kill_switch,
+ min_creator_graduated_radar: s.min_creator_graduated_radar,
+ require_smart_money_funder: s.require_smart_money_funder,
+ radar_max_age_ms: s.radar_max_age_ms,
+ per_trade_sol: s.per_trade_lamports != null ? Number(BigInt(s.per_trade_lamports)) / 1e9 : null,
+ })),
+ positions: positions.map((p) => ({
+ mint: p.mint, status: p.status,
+ pnl_sol: p.realized_pnl_lamports != null ? Number(BigInt(p.realized_pnl_lamports)) / 1e9 : null,
+ })),
+ _posByMint: posByMint,
+ };
+ } catch {
+ armed = { strategies: [], positions: [] };
+ }
+ }
+
+ const watchlist = watchRows.map((w) => ({
+ address: isOwner ? w.address : trunc(w.address),
+ reason: w.reason,
+ source: w.source,
+ score: Number(w.score),
+ creator_graduated: w.creator_graduated,
+ realized_score: w.realized_score != null ? Number(w.realized_score) : null,
+ labels: Array.isArray(w.labels) ? w.labels : [],
+ added_at: w.added_at,
+ last_hit_at: w.last_hit_at,
+ hits: w.hits,
+ }));
+
+ const events = eventRows.map((e) => ({
+ id: e.id,
+ kind: e.kind,
+ trigger_wallet: isOwner ? e.trigger_wallet : trunc(e.trigger_wallet),
+ new_wallet: isOwner ? e.new_wallet : trunc(e.new_wallet),
+ mint: e.mint,
+ confidence: Number(e.confidence),
+ watch_reason: e.watch_reason,
+ watch_score: e.watch_score != null ? Number(e.watch_score) : null,
+ observed_ts: e.observed_ts,
+ created_at: e.created_at,
+ fired: isOwner ? firedMints.has(e.mint) : undefined,
+ }));
+
+ if (armed) delete armed._posByMint;
+
+ return json(res, 200, {
+ ok: true,
+ network,
+ owner: isOwner,
+ status,
+ watchlist,
+ events,
+ counts: {
+ events_1h: Number(counts.events_1h || 0),
+ events_24h: Number(counts.events_24h || 0),
+ armable_24h: Number(counts.armable_24h || 0),
+ watched: watchlist.length,
+ },
+ armed,
+ }, { 'cache-control': isOwner ? 'private, no-store' : 'public, max-age=5' });
+});
diff --git a/api/sniper/strategy.js b/api/sniper/strategy.js
index 5096ec5f1..024ef7f98 100644
--- a/api/sniper/strategy.js
+++ b/api/sniper/strategy.js
@@ -58,8 +58,12 @@ const STRATEGY_SCHEMA = z.object({
// trigger: what arms this strategy.
// new_mint — snipe new pump.fun launches off the PumpPortal feed (default).
// first_claim — snipe a creator's coin the first time they EVER claim rewards.
- trigger: z.enum(['new_mint', 'first_claim', 'intel_confirmed']).optional(),
+ trigger: z.enum(['new_mint', 'first_claim', 'intel_confirmed', 'prelaunch_radar']).optional(),
buy_delay_ms: z.union([z.string(), z.number()]).optional(),
+ // prelaunch_radar gates (null clears)
+ min_creator_graduated_radar: optInt,
+ require_smart_money_funder: z.boolean().optional(),
+ radar_max_age_ms: optInt,
// first_claim entry filters (null clears)
min_claim_lamports: optLamports,
max_claim_lamports: optLamports,
@@ -216,6 +220,9 @@ async function listStrategies(req, res, userId) {
trailing_stop_pct: s.trailing_stop_pct != null ? Number(s.trailing_stop_pct) : null,
max_hold_seconds: s.max_hold_seconds,
min_oracle_score: s.min_oracle_score != null ? Number(s.min_oracle_score) : null,
+ min_creator_graduated_radar: s.min_creator_graduated_radar ?? null,
+ require_smart_money_funder: s.require_smart_money_funder ?? false,
+ radar_max_age_ms: s.radar_max_age_ms ?? null,
min_quality_score: s.min_quality_score != null ? Number(s.min_quality_score) : null,
max_bundle_score: s.max_bundle_score != null ? Number(s.max_bundle_score) : null,
max_concentration_top1: s.max_concentration_top1 != null ? Number(s.max_concentration_top1) : null,
@@ -275,6 +282,7 @@ async function upsertStrategy(req, res, userId) {
take_profit_pct: null, stop_loss_pct: 30, trailing_stop_pct: null,
max_hold_seconds: 1800,
min_oracle_score: null,
+ min_creator_graduated_radar: null, require_smart_money_funder: false, radar_max_age_ms: null,
min_quality_score: null, max_bundle_score: null, max_concentration_top1: null,
avoid_dev_dump: true, allowed_categories: null,
telegram_chat_id: null,
@@ -306,6 +314,9 @@ async function upsertStrategy(req, res, userId) {
trailing_stop_pct: 'trailing_stop_pct' in p ? numOrNull(p.trailing_stop_pct) : (cur.trailing_stop_pct != null ? Number(cur.trailing_stop_pct) : null),
max_hold_seconds: p.max_hold_seconds != null ? clampInt(p.max_hold_seconds, 30, 86400, 1800) : cur.max_hold_seconds,
min_oracle_score: 'min_oracle_score' in p ? (p.min_oracle_score == null || p.min_oracle_score === '' ? null : Math.min(100, Math.max(0, Math.round(Number(p.min_oracle_score))))) : cur.min_oracle_score,
+ min_creator_graduated_radar: 'min_creator_graduated_radar' in p ? (p.min_creator_graduated_radar == null || p.min_creator_graduated_radar === '' ? null : clampInt(p.min_creator_graduated_radar, 0, 100000, 0)) : (cur.min_creator_graduated_radar ?? null),
+ require_smart_money_funder: p.require_smart_money_funder ?? cur.require_smart_money_funder ?? false,
+ radar_max_age_ms: 'radar_max_age_ms' in p ? (p.radar_max_age_ms == null || p.radar_max_age_ms === '' ? null : clampInt(p.radar_max_age_ms, 1000, 3600000, 120000)) : (cur.radar_max_age_ms ?? null),
min_quality_score: 'min_quality_score' in p ? (p.min_quality_score == null || p.min_quality_score === '' ? null : Math.min(100, Math.max(0, Math.round(Number(p.min_quality_score))))) : (cur.min_quality_score != null ? Number(cur.min_quality_score) : null),
max_bundle_score: 'max_bundle_score' in p ? (p.max_bundle_score == null || p.max_bundle_score === '' ? null : Math.min(1, Math.max(0, Number(p.max_bundle_score)))) : (cur.max_bundle_score != null ? Number(cur.max_bundle_score) : null),
max_concentration_top1: 'max_concentration_top1' in p ? (p.max_concentration_top1 == null || p.max_concentration_top1 === '' ? null : Math.min(100, Math.max(0, Number(p.max_concentration_top1)))) : (cur.max_concentration_top1 != null ? Number(cur.max_concentration_top1) : null),
@@ -340,6 +351,7 @@ async function upsertStrategy(req, res, userId) {
require_socials, require_sol_quote,
take_profit_pct, stop_loss_pct, trailing_stop_pct, max_hold_seconds,
min_oracle_score,
+ min_creator_graduated_radar, require_smart_money_funder, radar_max_age_ms,
min_quality_score, max_bundle_score, max_concentration_top1,
avoid_dev_dump, allowed_categories, telegram_chat_id, updated_at)
values
@@ -351,6 +363,7 @@ async function upsertStrategy(req, res, userId) {
${next.require_socials}, ${next.require_sol_quote},
${next.take_profit_pct}, ${next.stop_loss_pct}, ${next.trailing_stop_pct}, ${next.max_hold_seconds},
${next.min_oracle_score},
+ ${next.min_creator_graduated_radar}, ${next.require_smart_money_funder}, ${next.radar_max_age_ms},
${next.min_quality_score}, ${next.max_bundle_score}, ${next.max_concentration_top1},
${next.avoid_dev_dump}, ${next.allowed_categories}, ${next.telegram_chat_id}, now())
on conflict (agent_id, network) do update set
@@ -379,6 +392,9 @@ async function upsertStrategy(req, res, userId) {
trailing_stop_pct = excluded.trailing_stop_pct,
max_hold_seconds = excluded.max_hold_seconds,
min_oracle_score = excluded.min_oracle_score,
+ min_creator_graduated_radar = excluded.min_creator_graduated_radar,
+ require_smart_money_funder = excluded.require_smart_money_funder,
+ radar_max_age_ms = excluded.radar_max_age_ms,
min_quality_score = excluded.min_quality_score,
max_bundle_score = excluded.max_bundle_score,
max_concentration_top1 = excluded.max_concentration_top1,
@@ -419,6 +435,9 @@ async function upsertStrategy(req, res, userId) {
trailing_stop_pct: row.trailing_stop_pct != null ? Number(row.trailing_stop_pct) : null,
max_hold_seconds: row.max_hold_seconds,
min_oracle_score: row.min_oracle_score != null ? Number(row.min_oracle_score) : null,
+ min_creator_graduated_radar: row.min_creator_graduated_radar ?? null,
+ require_smart_money_funder: row.require_smart_money_funder ?? false,
+ radar_max_age_ms: row.radar_max_age_ms ?? null,
min_quality_score: row.min_quality_score != null ? Number(row.min_quality_score) : null,
max_bundle_score: row.max_bundle_score != null ? Number(row.max_bundle_score) : null,
max_concentration_top1: row.max_concentration_top1 != null ? Number(row.max_concentration_top1) : null,
diff --git a/api/swarms/[id].js b/api/swarms/[id].js
new file mode 100644
index 000000000..75b799bf6
--- /dev/null
+++ b/api/swarms/[id].js
@@ -0,0 +1,113 @@
+// /api/swarms/:id — full dashboard state for one swarm
+// /api/swarms/:id/stream — SSE: live consensus votes, payouts, treasury ticks
+//
+// Routed here by vercel.json (`/api/swarms/([^/]+)(/.*)? → /api/swarms/[id]`); the
+// handler parses the path to split state vs. stream. GET only — mutations live on
+// POST /api/swarms.
+
+import { cors, method, json, error, wrap } from '../_lib/http.js';
+import { resolveAccount } from '../_lib/account-auth.js';
+import { sql } from '../_lib/db.js';
+import { getSwarmState, getSwarm, treasuryBalanceLamports } from '../_lib/swarms.js';
+import { getOrCreateAgentSolanaWallet } from '../_lib/agent-wallet.js';
+
+const isUuid = (s) => typeof s === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);
+
+export default wrap(async (req, res) => {
+ const url = new URL(req.url, 'http://x');
+ const parts = url.pathname.split('/').filter(Boolean); // ['api','swarms',':id', 'stream'?]
+ const id = parts[2];
+ const sub = parts[3] || null;
+
+ if (!isUuid(id)) return error(res, 404, 'not_found', 'swarm not found');
+
+ if (sub === 'stream') {
+ if (!method(req, res, ['GET'])) return;
+ return streamSwarm(req, res, id);
+ }
+
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const auth = await resolveAccount(req, res).catch(() => null);
+ const state = await getSwarmState(id, { viewerUserId: auth?.userId || null });
+ if (!state) return error(res, 404, 'not_found', 'swarm not found');
+ return json(res, 200, { data: state });
+});
+
+const HEARTBEAT_MS = 15_000;
+const POLL_MS = 2_500;
+const MAX_DURATION_MS = 280_000; // end before the platform function timeout; client reconnects
+
+async function streamSwarm(req, res, id) {
+ const swarm = await getSwarm(id);
+ if (!swarm) return error(res, 404, 'not_found', 'swarm not found');
+
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
+ res.setHeader('X-Accel-Buffering', 'no');
+ res.setHeader('Connection', 'keep-alive');
+
+ const send = (event, data) => {
+ try { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); } catch { /* socket closed */ }
+ };
+
+ let treasuryAddr = null;
+ try { treasuryAddr = (await getOrCreateAgentSolanaWallet(swarm.treasury_agent_id)).address; } catch { /* leave null */ }
+
+ send('hello', { swarm_id: id, network: swarm.network, treasury: treasuryAddr });
+
+ // Cursors — only emit rows newer than what we've already sent.
+ let lastVoteAt = new Date(0).toISOString();
+ let lastPayoutAt = new Date(0).toISOString();
+
+ const poll = async () => {
+ try {
+ const [votes, payouts, posAgg] = await Promise.all([
+ sql`select id, mint, decision, consensus, min_consensus, conviction, size_lamports,
+ members_long, members_total, smart_money_score, reason, position_id, created_at
+ from swarm_votes where swarm_id = ${id} and created_at > ${lastVoteAt}
+ order by created_at asc limit 20`,
+ sql`select id, kind, amount_lamports, share_bps, agent_id, signature, status, created_at
+ from swarm_payouts where swarm_id = ${id} and created_at > ${lastPayoutAt}
+ order by created_at asc limit 20`,
+ sql`select count(*) filter (where status in ('open','opening','closing'))::int as open,
+ count(*) filter (where status='closed')::int as closed,
+ coalesce(sum(realized_pnl_lamports),0)::numeric as pnl
+ from agent_sniper_positions where agent_id = ${swarm.treasury_agent_id} and network = ${swarm.network}`,
+ ]);
+ for (const v of votes) {
+ lastVoteAt = v.created_at;
+ send('vote', { ...v, size_sol: v.size_lamports == null ? null : Number(String(v.size_lamports).split('.')[0]) / 1e9 });
+ }
+ for (const p of payouts) {
+ lastPayoutAt = p.created_at;
+ send('payout', { ...p, amount_sol: Number(String(p.amount_lamports).split('.')[0]) / 1e9 });
+ }
+ let balanceSol = null;
+ if (treasuryAddr) {
+ const lam = await treasuryBalanceLamports(treasuryAddr, swarm.network).catch(() => null);
+ balanceSol = lam == null ? null : Number(lam) / 1e9;
+ }
+ const cur = await getSwarm(id);
+ send('tick', {
+ status: cur?.status || swarm.status,
+ balance_sol: balanceSol,
+ open_positions: posAgg[0]?.open || 0,
+ closed_trades: posAgg[0]?.closed || 0,
+ realized_pnl_sol: Number(String(posAgg[0]?.pnl || '0').split('.')[0]) / 1e9,
+ });
+ } catch {
+ /* transient DB blip — keep the stream open, retry next tick */
+ }
+ };
+
+ await poll();
+ const pollTimer = setInterval(poll, POLL_MS);
+ const heartbeat = setInterval(() => { try { res.write(`:hb\n\n`); } catch { /* closed */ } }, HEARTBEAT_MS);
+ const deadline = setTimeout(() => { cleanup(); try { res.end(); } catch { /* closed */ } }, MAX_DURATION_MS);
+
+ const cleanup = () => { clearInterval(pollTimer); clearInterval(heartbeat); clearTimeout(deadline); };
+ req.on('close', cleanup);
+ res.on('close', cleanup);
+}
diff --git a/api/swarms/index.js b/api/swarms/index.js
new file mode 100644
index 000000000..622f675db
--- /dev/null
+++ b/api/swarms/index.js
@@ -0,0 +1,112 @@
+// /api/swarms — trading-swarm directory + all mutations.
+//
+// GET /api/swarms?network=&status=&limit=&offset= public directory (aggregate track record)
+// GET /api/swarms?mine=1 swarms the caller owns or is a member of
+// POST /api/swarms { action, ... } create | join | contribute | exit | kill | pause | resume
+//
+// Every mutation that moves SOL (contribute, exit) executes a real on-chain
+// transfer inside the lib, spend-guarded and audited. The treasury balance always
+// ties to chain — there are no virtual balances here.
+
+import { cors, method, json, error, wrap, readJson } from '../_lib/http.js';
+import { parseLimit, parseOffset } from '../_lib/http-params.js';
+import { resolveAccount } from '../_lib/account-auth.js';
+import { sql } from '../_lib/db.js';
+import {
+ createSwarm, joinSwarm, contributeToSwarm, exitSwarm, killSwarm,
+ setSwarmPaused, listSwarms, listSwarmsForUser, SwarmError,
+} from '../_lib/swarms.js';
+
+const isUuid = (s) => typeof s === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);
+
+function handleSwarmError(res, e) {
+ if (e instanceof SwarmError) return error(res, e.status, e.code, e.message);
+ throw e;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const url = new URL(req.url, 'http://x');
+
+ if (req.method === 'GET') {
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+
+ if (url.searchParams.get('mine') === '1') {
+ const auth = await resolveAccount(req, res);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ // Includes killed/closed swarms the caller owns or joined — the only place
+ // they can reach their own ended swarm dashboards.
+ const data = await listSwarmsForUser(auth.userId);
+ return json(res, 200, { data });
+ }
+
+ const status = url.searchParams.get('status');
+ const limit = parseLimit(url.searchParams, { fallback: 30, max: 60 });
+ const offset = parseOffset(url.searchParams);
+ const data = await listSwarms({ network, status: status || null, limit, offset });
+ return json(res, 200, { data });
+ }
+
+ // POST — all mutations require auth.
+ const auth = await resolveAccount(req, res);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ const body = await readJson(req).catch(() => ({}));
+ const action = String(body.action || '');
+
+ const lamportsFromBody = () => {
+ if (body.lamports != null) return BigInt(Math.max(0, Math.round(Number(body.lamports))));
+ if (body.sol != null) return BigInt(Math.max(0, Math.round(Number(body.sol) * 1e9)));
+ return 0n;
+ };
+
+ try {
+ switch (action) {
+ case 'create': {
+ if (!isUuid(body.owner_agent_id)) return error(res, 400, 'bad_agent', 'owner_agent_id required');
+ const swarm = await createSwarm({
+ userId: auth.userId, ownerAgentId: body.owner_agent_id,
+ name: body.name, description: body.description || null,
+ network: body.network === 'devnet' ? 'devnet' : 'mainnet', policy: body.policy || {},
+ });
+ return json(res, 201, { data: { swarm } });
+ }
+ case 'join': {
+ if (!isUuid(body.swarm_id)) return error(res, 400, 'bad_swarm', 'swarm_id required');
+ if (!isUuid(body.agent_id)) return error(res, 400, 'bad_agent', 'agent_id required');
+ const member = await joinSwarm({ userId: auth.userId, swarmId: body.swarm_id, agentId: body.agent_id });
+ return json(res, 200, { data: { member } });
+ }
+ case 'contribute': {
+ if (!isUuid(body.swarm_id)) return error(res, 400, 'bad_swarm', 'swarm_id required');
+ if (!isUuid(body.agent_id)) return error(res, 400, 'bad_agent', 'agent_id required');
+ const lamports = lamportsFromBody();
+ if (lamports <= 0n) return error(res, 400, 'bad_amount', 'sol or lamports required');
+ const result = await contributeToSwarm({ userId: auth.userId, swarmId: body.swarm_id, agentId: body.agent_id, lamports });
+ return json(res, 200, { data: result });
+ }
+ case 'exit': {
+ if (!isUuid(body.swarm_id)) return error(res, 400, 'bad_swarm', 'swarm_id required');
+ if (!isUuid(body.agent_id)) return error(res, 400, 'bad_agent', 'agent_id required');
+ const result = await exitSwarm({ userId: auth.userId, swarmId: body.swarm_id, agentId: body.agent_id });
+ return json(res, 200, { data: result });
+ }
+ case 'kill': {
+ if (!isUuid(body.swarm_id)) return error(res, 400, 'bad_swarm', 'swarm_id required');
+ const swarm = await killSwarm({ userId: auth.userId, swarmId: body.swarm_id, reason: body.reason || null });
+ return json(res, 200, { data: { swarm } });
+ }
+ case 'pause':
+ case 'resume': {
+ if (!isUuid(body.swarm_id)) return error(res, 400, 'bad_swarm', 'swarm_id required');
+ const swarm = await setSwarmPaused({ userId: auth.userId, swarmId: body.swarm_id, paused: action === 'pause' });
+ return json(res, 200, { data: { swarm } });
+ }
+ default:
+ return error(res, 400, 'bad_action', 'unknown action');
+ }
+ } catch (e) {
+ return handleSwarmError(res, e);
+ }
+});
diff --git a/api/tournaments/[id].js b/api/tournaments/[id].js
new file mode 100644
index 000000000..8c5cb84e3
--- /dev/null
+++ b/api/tournaments/[id].js
@@ -0,0 +1,391 @@
+/**
+ * Social Trading Arena — single-tournament endpoint + sub-routes.
+ *
+ * GET /api/tournaments/:id → state + live standings + prize + attestation
+ * GET /api/tournaments/:id/stream → SSE live rank changes
+ * POST /api/tournaments/:id/join → enter an agent you own (snapshots baseline)
+ * POST /api/tournaments/:id/withdraw → withdraw an agent you own
+ * POST /api/tournaments/:id/close → freeze + attest final standings (creator)
+ * POST /api/tournaments/:id/settle → pay $THREE prizes (creator)
+ *
+ * Standings are computed live from the shared trader-stats truth layer over trades
+ * OPENED inside the window, so the board, the SSE stream, and the on-chain
+ * attestation can never disagree.
+ */
+
+import { cors, json, method, wrap, error, rateLimited, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { isUuid } from '../_lib/validate.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { computeTraderMetrics, fetchTraderPositions } from '../_lib/trader-stats.js';
+import {
+ getTournament,
+ getEntry,
+ joinTournament,
+ withdrawEntry,
+ derivedStatus,
+} from '../_lib/tournament-store.js';
+import { loadStandings, finalizeTournament, settleNow } from '../_lib/tournament-engine.js';
+import { attestationUrl } from '../_lib/tournament-attest.js';
+import { settlementBlockReason } from '../_lib/tournament-settlement.js';
+import { publicTournament } from './index.js';
+
+const SSE_MAX_DURATION_MS = 90_000;
+const SSE_PING_MS = 15_000;
+const SSE_POLL_MS = 3_000;
+
+async function resolveUser(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+function parseRoute(req) {
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const parts = url.pathname.split('/').filter(Boolean); // ['api','tournaments',id,sub]
+ return { id: parts[2] || '', sub: parts[3] || null, url };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+
+ const { id, sub } = parseRoute(req);
+ if (!isUuid(id)) return error(res, 400, 'invalid_id', 'tournament id must be a UUID');
+
+ if (sub === 'stream') {
+ if (!method(req, res, ['GET'])) return;
+ return handleStream(req, res, id);
+ }
+
+ if (!sub) {
+ if (!method(req, res, ['GET'])) return;
+ return handleState(req, res, id);
+ }
+
+ // Mutating sub-routes.
+ if (!method(req, res, ['POST'])) return;
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (sub === 'join') return handleJoin(req, res, id);
+ if (sub === 'withdraw') return handleWithdraw(req, res, id);
+ if (sub === 'close') return handleClose(req, res, id);
+ if (sub === 'settle') return handleSettle(req, res, id);
+ return error(res, 404, 'not_found', `unknown action ${sub}`);
+});
+
+async function handleState(req, res, id) {
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const tournament = await getTournament(id);
+ if (!tournament) return error(res, 404, 'not_found', 'tournament not found');
+
+ const now = Date.now();
+ const view = await loadStandings(tournament, { now });
+ const settlement = settlementSummary(view.standings, tournament.network);
+
+ return json(
+ res,
+ 200,
+ {
+ tournament: publicTournament({ ...tournament, entrant_count: view.standings.length }, now),
+ derived_status: derivedStatus(tournament, now),
+ standings: view.standings,
+ scoring: view.scoring,
+ bracket: view.bracket,
+ gates: view.gates,
+ window: view.window,
+ sol_usd: view.sol_usd,
+ prize_pool_three: view.prize_pool_three,
+ prize_pool_three_atomics: view.prize_pool_three_atomics,
+ prize_splits: view.prize_splits,
+ attestation: tournament.attestation_sig
+ ? { signature: tournament.attestation_sig, url: attestationUrl(tournament.attestation_sig, tournament.network) }
+ : null,
+ settlement,
+ computed_at: view.computed_at,
+ },
+ { 'cache-control': 'public, max-age=5, s-maxage=10' },
+ );
+}
+
+function settlementSummary(standings, network) {
+ const winners = standings.filter((s) => BigInt(s.persisted_prize_three_atomics || 0) > 0n);
+ return {
+ block_reason: settlementBlockReason(network),
+ winners: winners.map((s) => ({
+ agent_id: s.agent_id,
+ agent_name: s.agent_name,
+ rank: s.rank,
+ prize_three_atomics: s.persisted_prize_three_atomics,
+ settlement_status: s.settlement_status,
+ settlement_tx: s.settlement_tx,
+ settlement_url: s.settlement_tx ? attestationUrl(s.settlement_tx, network) : null,
+ })),
+ };
+}
+
+/** Resolve an agent's Solana trading wallet (latest sniper wallet → identity wallet). */
+async function resolveAgentWallet(agentId, network) {
+ const [pos] = await sql`
+ select wallet from agent_sniper_positions
+ where agent_id = ${agentId} and network = ${network} and wallet is not null
+ order by opened_at desc limit 1
+ `;
+ if (pos?.wallet) return pos.wallet;
+ const [a] = await sql`select wallet_address from agent_identities where id = ${agentId} limit 1`;
+ return a?.wallet_address || null;
+}
+
+async function handleJoin(req, res, id) {
+ const auth = await resolveUser(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required to join a tournament');
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (err) {
+ return error(res, err.status || 400, 'bad_request', err.message || 'invalid JSON body');
+ }
+ const agentId = String(body.agent_id || '').trim();
+ if (!isUuid(agentId)) return error(res, 400, 'invalid_agent', 'agent_id must be a valid agent UUID');
+
+ const tournament = await getTournament(id);
+ if (!tournament) return error(res, 404, 'not_found', 'tournament not found');
+ const status = derivedStatus(tournament, Date.now());
+ if (['ended', 'closed', 'settled', 'cancelled'].includes(status)) {
+ return error(res, 409, 'closed', 'this tournament has ended — entries are closed');
+ }
+
+ // Ownership check.
+ const [agent] = await sql`
+ select id, user_id, name, is_public from agent_identities where id = ${agentId} and deleted_at is null limit 1
+ `;
+ if (!agent) return error(res, 404, 'agent_not_found', 'agent not found');
+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'that agent is not yours');
+
+ // Access gating.
+ const rules = tournament.entry_rules || {};
+ if (rules.gated && Array.isArray(rules.allow_agents) && !rules.allow_agents.includes(agentId)) {
+ return error(res, 403, 'not_invited', 'this tournament is gated and that agent is not on the allow list');
+ }
+
+ const wallet = await resolveAgentWallet(agentId, tournament.network);
+
+ // Baseline snapshot: all-time metrics at join, so window scoping is auditable.
+ let snapshot = {};
+ try {
+ const positions = await fetchTraderPositions({ agentId, network: tournament.network, window: 'all' });
+ const m = computeTraderMetrics(positions, { solUsd: null });
+ snapshot = {
+ at: new Date().toISOString(),
+ all_time_closed: m.closed_count,
+ all_time_realized_pnl_sol: m.realized_pnl_sol,
+ all_time_score: m.score,
+ verified: m.verified,
+ };
+ } catch {
+ snapshot = { at: new Date().toISOString() };
+ }
+
+ const { entry, created } = await joinTournament({ tournamentId: id, agentId, wallet, snapshot });
+ if (!entry) return error(res, 500, 'join_failed', 'could not record the entry — try again');
+
+ return json(
+ res,
+ created ? 201 : 200,
+ {
+ joined: true,
+ created,
+ entry: {
+ tournament_id: id,
+ agent_id: agentId,
+ agent_name: agent.name,
+ wallet,
+ status: entry.status,
+ joined_at: entry.joined_at,
+ starting_snapshot: entry.starting_snapshot,
+ },
+ },
+ { 'cache-control': 'no-store' },
+ );
+}
+
+async function handleWithdraw(req, res, id) {
+ const auth = await resolveUser(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (err) {
+ return error(res, err.status || 400, 'bad_request', err.message || 'invalid JSON body');
+ }
+ const agentId = String(body.agent_id || '').trim();
+ if (!isUuid(agentId)) return error(res, 400, 'invalid_agent', 'agent_id must be a valid agent UUID');
+
+ const [agent] = await sql`select user_id from agent_identities where id = ${agentId} limit 1`;
+ if (!agent) return error(res, 404, 'agent_not_found', 'agent not found');
+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'that agent is not yours');
+
+ const entry = await getEntry(id, agentId);
+ if (!entry) return error(res, 404, 'not_entered', 'that agent is not entered in this tournament');
+
+ const row = await withdrawEntry(id, agentId);
+ return json(res, 200, { withdrawn: !!row }, { 'cache-control': 'no-store' });
+}
+
+/** Only the creator may close/settle. */
+async function requireCreator(req, res, tournament) {
+ const auth = await resolveUser(req);
+ if (!auth) {
+ error(res, 401, 'unauthorized', 'sign in required');
+ return null;
+ }
+ if (!tournament.created_by || tournament.created_by !== auth.userId) {
+ error(res, 403, 'forbidden', 'only the tournament creator can do that');
+ return null;
+ }
+ return auth;
+}
+
+async function handleClose(req, res, id) {
+ const tournament = await getTournament(id);
+ if (!tournament) return error(res, 404, 'not_found', 'tournament not found');
+ if (!(await requireCreator(req, res, tournament))) return;
+
+ try {
+ const result = await finalizeTournament(tournament, { now: Date.now() });
+ return json(
+ res,
+ 200,
+ {
+ closed: true,
+ status: result.status,
+ attestation: result.attestation,
+ standings: result.standings.map((s) => ({
+ rank: s.rank,
+ agent_id: s.agent_id,
+ agent_name: s.agent_name,
+ score_value: s.score_value,
+ eligible: s.eligible,
+ })),
+ },
+ { 'cache-control': 'no-store' },
+ );
+ } catch (err) {
+ return error(res, err.status || 500, err.code || 'close_failed', err.message || 'could not close tournament');
+ }
+}
+
+async function handleSettle(req, res, id) {
+ const tournament = await getTournament(id);
+ if (!tournament) return error(res, 404, 'not_found', 'tournament not found');
+ if (!(await requireCreator(req, res, tournament))) return;
+
+ try {
+ const result = await settleNow(id, { now: Date.now() });
+ return json(
+ res,
+ 200,
+ {
+ settled: result.settled,
+ blocked: result.blocked,
+ skipped: result.skipped,
+ block_reason: result.block_reason,
+ status: result.status,
+ results: result.results.map((r) => ({
+ ...r,
+ tx_url: r.tx ? attestationUrl(r.tx, tournament.network) : null,
+ })),
+ },
+ { 'cache-control': 'no-store' },
+ );
+ } catch (err) {
+ return error(res, err.status || 500, err.code || 'settle_failed', err.message || 'could not settle tournament');
+ }
+}
+
+/** SSE: re-emit the ranked standings on an interval; the client animates rank deltas. */
+async function handleStream(req, res, id) {
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const tournament = await getTournament(id);
+ if (!tournament) return error(res, 404, 'not_found', 'tournament not found');
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => {
+ if (!active) return;
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ };
+
+ const poll = async () => {
+ if (!active) return;
+ try {
+ const fresh = await getTournament(id);
+ if (!fresh) return;
+ const now = Date.now();
+ const view = await loadStandings(fresh, { now });
+ send('standings', {
+ status: derivedStatus(fresh, now),
+ computed_at: view.computed_at,
+ standings: view.standings.map((s) => ({
+ rank: s.rank,
+ agent_id: s.agent_id,
+ agent_name: s.agent_name,
+ image: s.image,
+ score_value: s.score_value,
+ realized_pnl_sol: s.metrics.realized_pnl_sol,
+ roi_pct: s.metrics.roi_pct,
+ win_rate: s.metrics.win_rate,
+ closed: s.in_window_trades,
+ verified: s.metrics.verified,
+ eligible: s.eligible,
+ wash_suspected: s.wash_suspected,
+ projected_prize_three: s.projected_prize_three,
+ settlement_status: s.settlement_status,
+ sample_trades: s.sample_trades,
+ })),
+ });
+ } catch {
+ send('error', { message: 'poll_failed' });
+ }
+ };
+
+ send('open', { tournament_id: id, network: tournament.network });
+ await poll();
+ const pollTimer = setInterval(poll, SSE_POLL_MS);
+ const ping = setInterval(() => send('ping', { t: Date.now() }), SSE_PING_MS);
+
+ const teardown = () => {
+ if (!active) return;
+ active = false;
+ clearInterval(pollTimer);
+ clearInterval(ping);
+ clearTimeout(durationTimer);
+ try {
+ res.end();
+ } catch {
+ /* already closed */
+ }
+ };
+ const durationTimer = setTimeout(() => {
+ send('close', { reason: 'duration_limit' });
+ teardown();
+ }, SSE_MAX_DURATION_MS);
+
+ req.on('close', teardown);
+}
diff --git a/api/tournaments/index.js b/api/tournaments/index.js
new file mode 100644
index 000000000..792c084c5
--- /dev/null
+++ b/api/tournaments/index.js
@@ -0,0 +1,201 @@
+/**
+ * Social Trading Arena — tournament collection endpoint.
+ *
+ * GET /api/tournaments?network=mainnet&phase=live → list (public)
+ * POST /api/tournaments → create (auth required)
+ *
+ * Tournaments are time-boxed PvP trading competitions scored on real, verified PnL
+ * over a window (see api/_lib/tournament-scoring.js). Listing is public and IP
+ * rate-limited; creation requires a signed-in user (session cookie or bearer token)
+ * and records them as the creator.
+ */
+
+import { cors, json, method, wrap, error, rateLimited, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { env } from '../_lib/env.js';
+import { createTournament, listTournaments, derivedStatus } from '../_lib/tournament-store.js';
+import { attestationUrl } from '../_lib/tournament-attest.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const PHASES = new Set(['upcoming', 'live', 'finished']);
+const SCORINGS = new Set(['score', 'realized_pnl', 'roi_pct']);
+const BRACKETS = new Set(['prize', 'practice']);
+const MAX_NAME = 120;
+const MAX_WINDOW_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
+const MIN_WINDOW_MS = 5 * 60 * 1000; // 5 minutes
+
+async function resolveUser(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+/** Public projection of a tournament row for the list view. */
+export function publicTournament(row, now = Date.now()) {
+ const decimals = env.THREE_TOKEN_DECIMALS;
+ return {
+ id: row.id,
+ name: row.name,
+ description: row.description || null,
+ network: row.network,
+ scoring: row.scoring,
+ bracket: row.bracket,
+ status: row.status,
+ phase: row.phase || undefined,
+ derived_status: derivedStatus(row, now),
+ starts_at: row.starts_at,
+ ends_at: row.ends_at,
+ entry_rules: row.entry_rules || {},
+ prize_pool_three_atomics: String(row.prize_pool_three || 0),
+ prize_pool_three: atomicsToThree(row.prize_pool_three || 0, decimals),
+ prize_splits: row.prize_splits || [],
+ entrant_count: Number(row.entrant_count || 0),
+ attestation_sig: row.attestation_sig || null,
+ attestation_url: row.attestation_sig ? attestationUrl(row.attestation_sig, row.network) : null,
+ created_at: row.created_at,
+ };
+}
+
+function atomicsToThree(atomics, decimals) {
+ const a = BigInt(atomics);
+ if (a === 0n) return 0;
+ const div = 10n ** BigInt(decimals);
+ return Number(`${a / div}.${(a % div).toString().padStart(decimals, '0')}`);
+}
+
+function threeToAtomics(amount, decimals) {
+ const n = Number(amount);
+ if (!Number.isFinite(n) || n < 0) return null;
+ // Parse via string to avoid float drift on the fractional part.
+ const [whole, frac = ''] = String(n).split('.');
+ const fracPadded = (frac + '0'.repeat(decimals)).slice(0, decimals);
+ return BigInt(whole || '0') * 10n ** BigInt(decimals) + BigInt(fracPadded || '0');
+}
+
+function validSplits(splits) {
+ if (!Array.isArray(splits)) return false;
+ let sum = 0;
+ const ranks = new Set();
+ for (const s of splits) {
+ const rank = Number(s?.rank);
+ const bps = Number(s?.bps);
+ if (!Number.isInteger(rank) || rank < 1 || rank > 100) return false;
+ if (!Number.isFinite(bps) || bps <= 0 || bps > 10000) return false;
+ if (ranks.has(rank)) return false;
+ ranks.add(rank);
+ sum += bps;
+ }
+ return sum <= 10000;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'GET') {
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : null;
+ const phase = PHASES.has(params.get('phase')) ? params.get('phase') : null;
+ const now = Date.now();
+ const rows = await listTournaments({ network, phase, now });
+ return json(
+ res,
+ 200,
+ { tournaments: rows.map((r) => publicTournament(r, now)), t: now },
+ { 'cache-control': 'public, max-age=10, s-maxage=20' },
+ );
+ }
+
+ // POST — create
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const auth = await resolveUser(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required to create a tournament');
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (err) {
+ return error(res, err.status || 400, 'bad_request', err.message || 'invalid JSON body');
+ }
+
+ const name = String(body.name || '').trim();
+ if (!name || name.length > MAX_NAME) {
+ return error(res, 400, 'invalid_name', `name is required and must be ≤ ${MAX_NAME} chars`);
+ }
+ const network = NETWORKS.has(body.network) ? body.network : 'mainnet';
+ const scoring = SCORINGS.has(body.scoring) ? body.scoring : 'score';
+ const bracket = BRACKETS.has(body.bracket) ? body.bracket : 'prize';
+
+ const startMs = Date.parse(body.starts_at);
+ const endMs = Date.parse(body.ends_at);
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) {
+ return error(res, 400, 'invalid_window', 'starts_at and ends_at must be ISO-8601 timestamps');
+ }
+ if (endMs <= startMs) return error(res, 400, 'invalid_window', 'ends_at must be after starts_at');
+ const span = endMs - startMs;
+ if (span < MIN_WINDOW_MS || span > MAX_WINDOW_MS) {
+ return error(res, 400, 'invalid_window', 'tournament window must be between 5 minutes and 30 days');
+ }
+ if (endMs <= Date.now()) return error(res, 400, 'invalid_window', 'ends_at must be in the future');
+
+ // Entry rules (anti-cheat gates + access gating).
+ const rules = body.entry_rules && typeof body.entry_rules === 'object' ? body.entry_rules : {};
+ const entry_rules = {};
+ for (const k of ['min_closed', 'min_unique_coins', 'max_churn_pct']) {
+ if (rules[k] != null && Number.isFinite(Number(rules[k])) && Number(rules[k]) >= 0) {
+ entry_rules[k] = Number(rules[k]);
+ }
+ }
+ if (rules.gated === true) entry_rules.gated = true;
+ if (Array.isArray(rules.allow_agents)) {
+ entry_rules.allow_agents = rules.allow_agents.filter((x) => typeof x === 'string').slice(0, 200);
+ }
+
+ // Prize pool (decimal $THREE → atomics). Practice brackets never carry a prize.
+ const decimals = env.THREE_TOKEN_DECIMALS;
+ let prizeAtomics = 0n;
+ let prize_splits = [];
+ if (bracket === 'prize' && body.prize_pool_three != null) {
+ const atomics = threeToAtomics(body.prize_pool_three, decimals);
+ if (atomics == null) return error(res, 400, 'invalid_prize', 'prize_pool_three must be a non-negative number');
+ prizeAtomics = atomics;
+ if (prizeAtomics > 0n) {
+ prize_splits = Array.isArray(body.prize_splits) && body.prize_splits.length
+ ? body.prize_splits.map((s) => ({ rank: Number(s.rank), bps: Number(s.bps) }))
+ : [
+ { rank: 1, bps: 6000 },
+ { rank: 2, bps: 3000 },
+ { rank: 3, bps: 1000 },
+ ];
+ if (!validSplits(prize_splits)) {
+ return error(res, 400, 'invalid_splits', 'prize_splits ranks must be unique and bps must sum to ≤ 10000');
+ }
+ }
+ }
+
+ const status = startMs <= Date.now() ? 'live' : 'upcoming';
+ const row = await createTournament({
+ name,
+ description: body.description ? String(body.description).slice(0, 2000) : null,
+ network,
+ scoring,
+ bracket,
+ starts_at: new Date(startMs).toISOString(),
+ ends_at: new Date(endMs).toISOString(),
+ entry_rules,
+ prize_pool_three: prizeAtomics.toString(),
+ prize_splits,
+ status,
+ created_by: auth.userId,
+ });
+
+ return json(res, 201, { tournament: publicTournament({ ...row, entrant_count: 0 }) }, { 'cache-control': 'no-store' });
+});
diff --git a/data/changelog.json b/data/changelog.json
index 2d55abffe..0bcef8ef1 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,86 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-23",
+ "title": "Signal Marketplace — verified traders sell paid alpha feeds; your agent pays per signal and auto-mirrors",
+ "summary": "Copy-trading with real economics and real accountability. A trader whose on-chain track record is verified — the same proven badge the leaderboard computes from real closed trades — can now publish their live entry and exit signals as a paid feed, priced per signal or per epoch in USDC. A follower's agent subscribes, and on every new paid signal it pays the publisher straight from its own wallet and auto-mirrors the trade: scaled to your sizing, run through the rug/honeypot firewall, submitted via the MEV engine, and held to your wallet's spend limits and kill switch — the exact same guarded path every other trade uses, fully audited. Start in simulate mode to track a feed's calls without spending a cent, then flip to live when you trust it. Every signal is bound to a real on-chain fill — sellers can't hand-author alpha — and each one accrues its realized outcome, so the marketplace ranks feeds by proven edge (hit-rate and realized ROI, confidence-regressed so a thin feed riding one lucky call can never top a deep, consistent one), never by follower count. Browse the directory, open any feed to see its full signal log with the tx that proves each call, and manage or instantly kill your subscriptions from your wallet hub's new Signals tab. Verified traders publish from the same tab and earn real USDC.",
+ "tags": [
+ "feature",
+ "sdk"
+ ],
+ "link": "/signals"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Portfolio Command — live net worth, cost basis, P&L attribution & risk for your agent wallet",
+ "summary": "Your agent's holdings, snipes, and discretionary trades used to be scattered across tabs with no single picture. The new Portfolio tab in your agent wallet pulls it all together: live net worth in SOL and USD with a streaming sparkline, every holding valued from real on-chain prices with its FIFO cost basis and unrealized P&L, and a one-click jump to trade or exit any position. A P&L attribution breakdown shows exactly what's making and losing money — your sniper strategies, discretionary trades, strategy objects — with realized vs unrealized split out, plus x402 and withdrawal outflows. A risk panel surfaces concentration (largest-position share + a Herfindahl diversification read), volatile-memecoin tape exposure, realized drawdown and per-trade volatility, and turns them into plain-language flags like '78% concentrated in one illiquid position'. Every figure is real: SOL amounts come straight from the chain and ledger, USD degrades to honest 'unpriced' rather than a guess, and illiquid holdings are flagged, never invented. Updates stream live while the tab is open.",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Mission Control — the real-time pump.fun trading terminal",
+ "summary": "Pump.fun traders juggle ten tabs. Mission Control gives you one screen. A keyboard-driven cockpit fuses every live signal three.ws computes: the launch firehose streaming brand-new mints, each row scored with its intel quality, firewall verdict, and smart-money count; a focus pane with a real price chart, the full intel breakdown, the rug/honeypot safety panel, and who's buying; and your own positions with streaming PnL and one-tap exit. Trade without leaving the keyboard — j/k to move, b to buy your preset size, s to sell, number keys for sizing, / to filter, ? for the shortcut map. Every buy and sell executes through the exact same guarded path as the rest of the platform — the rug/honeypot firewall (a blocked coin disables the button), the MEV engine, your wallet's spend guards, and the custody audit log — from your agent wallet, confirm-on-first-use then express. Filter the feed by intel score, firewall verdict, smart-money, socials, and market-cap band, and save named views. Every datum streams from a real endpoint with honest live/reconnecting/down status; when a source is down its pane degrades honestly instead of showing stale or fake data. Open it from the Launch menu or your agent wallet's Snipe tab.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/terminal"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Programmable orders — limit, stop, trailing, DCA, TWAP & conditional triggers for your agent wallet",
+ "summary": "Pump.fun has no native order types — you watch a chart and click frantically. Now every agent wallet gets a real, set-and-forget order layer. Place a limit buy on a dip or a limit sell on a target market cap; arm a stop-loss that survives across sessions, or a trailing stop that locks in gains by following the high-water mark; schedule DCA to buy in on a fixed interval; slice a large order with TWAP to cut price impact; or build a conditional trigger over live signals (\"buy when the smart-money score is above 60 and market cap is under $40k\", \"sell if the dev dumps\", \"buy on graduation\"). A worker watches the market continuously and fires matched orders automatically from your wallet — every fill priced from real on-chain state, run through the same rug/honeypot firewall and spend guards as a manual trade, capped by your daily budget and per-trade limits, and written to your custody ledger with a real transaction receipt. Conditions are a safe, validated spec (no arbitrary code), orders never fire on missing data, the kill switch halts everything, and cancel is instant. Find the new Orders tab in your agent wallet.",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "title": "The Arena — live PvP trading tournaments with $THREE prizes",
+ "summary": "Trading is now a spectator sport. The new Arena hosts time-boxed PvP tournaments where AI agents go head-to-head on real, verified pump.fun P&L — and because every number is computed from the agents' own on-chain closed trades, the performance can't be faked. Create a competition with a window, a scoring rule (composite TraderScore, realized P&L, or ROI), and an optional $THREE prize pool; enter one of your agents and only the trades it opens inside the window count, so everyone starts fair. The live competition view ranks entrants in real time with the leader spotlighted as a 3D avatar, a verified badge, a recent-trades ticker, and rank-change animations, all over a live stream. Anti-cheat is built in: simulated/paper trades never earn prizes (there's a clearly-labelled practice bracket for them), the same min-trades / unique-coins / churn gates that power the verification badge decide prize eligibility, and high-churn single-coin patterns are flagged. When a tournament closes, its final standings are committed to Solana as a tamper-evident on-chain attestation linked from the results page, and $THREE prizes settle to the winners' wallets with a real transaction — honestly reported as blocked, never faked, if prize funding isn't configured.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/arena"
+ },
+ {
+ "date": "2026-06-26",
+ "title": "Trading Swarms: pool capital with other agents and split the profits",
+ "summary": "A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/swarms"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Pre-Launch Radar — pre-arm a snipe at block-zero, on signal not luck",
+ "summary": "Everyone snipes a coin after it appears in the launch feed — by then thousands of bots see it too. The new Pre-Launch Radar goes earlier. It watches, in real time and from real on-chain reads, the wallets of proven creators (those who've repeatedly graduated coins) and proven smart-money wallets, and detects the launch PRECURSOR: the instant one of them funds a brand-new deploy wallet or submits a pump.fun create instruction, the radar catches it — at or before block-0 — and can pre-arm your agent's snipe before the coin hits any feed. Arm an agent with the new 'Pre-launch radar' trigger and set its gates (minimum creator graduations, require a proven smart-money funder, max precursor age); every pre-armed buy still passes the exact same rug/honeypot firewall, MEV execution engine, spend guards, kill switch, and on-chain custody audit as every other snipe. The new Pre-Launch Radar dashboard shows the live precursor tape, the auto-curated watchlist with why each wallet is watched, and — for you — which precursors your agent actually fired on. This acts only on public on-chain precursors (funding, deploys); it never front-runs anyone's pending transaction.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/dashboard/prelaunch-radar"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Talk to your agent to trade — the Conversational Trading Copilot",
+ "summary": "Your agent's wallet now has a Copilot tab where you trade by talking. Ask it things like \"how's my portfolio?\", \"is this coin safe to buy?\", or \"buy 0.25 SOL of <mint>\" — by text or voice — and it answers with real, live numbers: your balance and open positions, the rug/honeypot firewall verdict, smart-money count, price impact, and a fresh quote. It never invents figures, and it never trades on its own. When you ask to buy, sell, or change your risk limits, it hands you a confirm card showing the quote and safety verdict; only when you confirm does the trade run — through the exact same spend guards, firewall, kill switch, and on-chain custody audit as the manual Trade tab. Turn on the speaker to hear replies in your agent's own voice, and every executed trade is logged with a Solscan link. Owner-only.",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Pin a 3D world's look when you embed it",
+ "summary": "Play worlds embedded on another site can now choose their backdrop with a single setting, so the live 3D world sits cleanly inside the host page instead of clashing with it. Add ?biome=<id> to a /play embed URL — for example ?biome=noir for a neutral dark world. The IBM partnership demo uses this so its Play world renders on the same dark stage as the other 3D demos on that page, instead of dropping into a brightly-lit landscape. Default play and every coin's own world are unchanged.",
+ "tags": [
+ "improvement"
+ ],
+ "link": "/play"
+ },
{
"date": "2026-06-23",
"title": "IBM partnership page: a live Agent Galaxy replaces the old guide-agent demo",
diff --git a/data/pages.json b/data/pages.json
index dd8e67bc7..9469371b7 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -601,6 +601,22 @@
"changefreq": "hourly",
"added": "2026-06-15"
},
+ {
+ "path": "/signals",
+ "title": "Signal Marketplace — paid alpha feeds, ranked by proven edge",
+ "description": "Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.",
+ "priority": 0.8,
+ "changefreq": "hourly",
+ "added": "2026-06-23"
+ },
+ {
+ "path": "/arena",
+ "title": "The Arena — live PvP trading tournaments",
+ "description": "Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.",
+ "priority": 0.8,
+ "changefreq": "daily",
+ "added": "2026-06-23"
+ },
{
"path": "/trending",
"title": "Trending — Top Agents & Coins on three.ws",
@@ -689,6 +705,14 @@
"changefreq": "daily",
"added": "2026-05-04"
},
+ {
+ "path": "/terminal",
+ "title": "Mission Control",
+ "description": "The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.",
+ "priority": 0.85,
+ "changefreq": "daily",
+ "added": "2026-06-23"
+ },
{
"path": "/radar",
"title": "Coin Radar",
diff --git a/package.json b/package.json
index d50c5e7f7..4e4e191bb 100644
--- a/package.json
+++ b/package.json
@@ -167,6 +167,8 @@
"worker:oracle": "node workers/oracle/index.js",
"worker:sniper": "node workers/agent-sniper/index.js",
"worker:sniper:live": "SNIPER_MODE=live node workers/agent-sniper/index.js",
+ "worker:orders": "node workers/agent-orders/index.js",
+ "worker:orders:live": "ORDERS_MODE=live node workers/agent-orders/index.js",
"deploy:sniper": "node scripts/deploy-sniper.mjs",
"pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js",
"pump:refresh-idls": "node scripts/refresh-pump-idls.mjs",
diff --git a/pages/arena.html b/pages/arena.html
new file mode 100644
index 000000000..49537a08c
--- /dev/null
+++ b/pages/arena.html
@@ -0,0 +1,69 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Arena — live PvP trading tournaments · three.ws</title>
+ <meta
+ name="description"
+ content="The Social Trading Arena: time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/arena" />
+ <meta property="og:title" content="Arena — live PvP trading tournaments · three.ws" />
+ <meta
+ property="og:description"
+ content="Watch AI agents go head-to-head on real, verified pump.fun P&L. Live rankings, on-chain attested results, $THREE prizes."
+ />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=The+Arena+%E2%80%94+live+PvP+trading+tournaments&amp;d=Time-boxed+PvP+tournaments+where+AI+agents+compete+on+real%2C+verified+pump.fun+P%26L.+Live+rankings%2C+on-chain+attested+standings%2C+and+%24THREE+prizes+for+the+winners&amp;p=%2Farena" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Arena — live PvP trading tournaments · three.ws" />
+ <meta
+ name="twitter:description"
+ content="AI agents go head-to-head on real, verified pump.fun P&L. Live rankings, on-chain attested results, $THREE prizes."
+ />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=The+Arena+%E2%80%94+live+PvP+trading+tournaments&amp;d=Time-boxed+PvP+tournaments+where+AI+agents+compete+on+real%2C+verified+pump.fun+P%26L.+Live+rankings%2C+on-chain+attested+standings%2C+and+%24THREE+prizes+for+the+winners&amp;p=%2Farena" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="canonical" href="https://three.ws/arena" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/arena/arena.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
+
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:image:alt" content="The Arena — live PvP trading tournaments — three.ws">
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"The Arena — live PvP trading tournaments","description":"Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.","url":"https://three.ws/arena","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&amp;t=The+Arena+%E2%80%94+live+PvP+trading+tournaments&amp;d=Time-boxed+PvP+tournaments+where+AI+agents+compete+on+real%2C+verified+pump.fun+P%26L.+Live+rankings%2C+on-chain+attested+standings%2C+and+%24THREE+prizes+for+the+winners&amp;p=%2Farena"}]}</script>
+</head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main id="arena" class="arena" aria-live="polite">
+ <!-- Rendered by /src/arena/arena.js. JS-disabled fallback below. -->
+ <noscript>
+ <section class="arena-noscript">
+ <h1>The Arena</h1>
+ <p>
+ Time-boxed PvP trading tournaments where AI agents compete on real, verified pump.fun P&amp;L —
+ with on-chain attested standings and $THREE prizes. Enable JavaScript to watch live.
+ </p>
+ </section>
+ </noscript>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/src/arena/arena.js"></script>
+ </body>
+</html>
diff --git a/pages/dashboard-next/prelaunch-radar.html b/pages/dashboard-next/prelaunch-radar.html
new file mode 100644
index 000000000..49591fe55
--- /dev/null
+++ b/pages/dashboard-next/prelaunch-radar.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Pre-Launch Radar · Dashboard · three.ws</title>
+ <meta name="robots" content="noindex" />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/dashboard-next/shell.css" />
+ </head>
+ <body>
+ <script type="module" src="/src/dashboard-next/pages/prelaunch-radar.js"></script>
+ </body>
+</html>
diff --git a/pages/signal-detail.html b/pages/signal-detail.html
new file mode 100644
index 000000000..dae4bb8ef
--- /dev/null
+++ b/pages/signal-detail.html
@@ -0,0 +1,38 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Signal Feed · three.ws</title>
+ <meta name="description" content="A verified trader's paid signal feed — proven accuracy, realized outcomes, and on-chain proof for every signal. Subscribe with your agent to auto-mirror." />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Signal Feed · three.ws" />
+ <meta property="og:description" content="A verified trader's paid signal feed — proven accuracy, realized outcomes, on-chain proof. Subscribe to auto-mirror." />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/signals.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <meta name="robots" content="index, follow, max-image-preview:large" />
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="sm-shell sd-shell" aria-labelledby="sd-title">
+ <a class="sd-back" href="/signals">← All feeds</a>
+ <div id="sd-root" aria-busy="true">
+ <div class="sm-skel sd-skel-hero" style="height:160px;border-radius:16px"></div>
+ </div>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js" defer></script>
+ <script type="module" src="/src/signal-detail.js"></script>
+ </body>
+</html>
diff --git a/pages/signals.html b/pages/signals.html
new file mode 100644
index 000000000..441649462
--- /dev/null
+++ b/pages/signals.html
@@ -0,0 +1,89 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Signal Marketplace · three.ws</title>
+ <meta
+ name="description"
+ content="Paid alpha feeds, ranked by proven edge. Verified traders publish their live entry/exit signals as x402-metered feeds; your agent pays per signal and auto-mirrors the trade through the firewall + MEV engine. Every signal binds to a real on-chain fill and accrues a realized outcome — feeds rank by proven accuracy, not follower count."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/signals" />
+ <meta property="og:title" content="Signal Marketplace · three.ws" />
+ <meta property="og:description" content="Paid alpha feeds, ranked by proven edge. Verified traders publish x402-metered signals; your agent pays per signal and auto-mirrors — every signal proven by an on-chain fill." />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Signal+Marketplace+%E2%80%94+paid+alpha+feeds%2C+ranked+by+proven+edge&amp;d=Verified+traders+publish+their+live+entry%2Fexit+signals+as+x402-metered+feeds.+Your+agent+pays+per+signal+or+per+epoch+in+USDC+and+auto-mirrors+the+trade+through&amp;p=%2Fsignals" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Signal Marketplace · three.ws" />
+ <meta name="twitter:description" content="Paid alpha feeds, ranked by proven edge. Pay per signal, auto-mirror, accountable on-chain." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Signal+Marketplace+%E2%80%94+paid+alpha+feeds%2C+ranked+by+proven+edge&amp;d=Verified+traders+publish+their+live+entry%2Fexit+signals+as+x402-metered+feeds.+Your+agent+pays+per+signal+or+per+epoch+in+USDC+and+auto-mirrors+the+trade+through&amp;p=%2Fsignals" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/signals.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/signals" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Signal Marketplace","description":"Paid alpha feeds ranked by proven edge.","url":"https://three.ws/signals","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:locale" content="en_US">
+
+ <meta property="og:image:alt" content="Signal Marketplace — paid alpha feeds, ranked by proven edge — three.ws">
+</head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="sm-shell" aria-labelledby="sm-title">
+ <section class="sm-hero">
+ <p class="sm-kicker">
+ <span class="sm-live-dot" aria-hidden="true"></span>
+ Reputation-gated · x402-metered · accountable on-chain
+ </p>
+ <h1 id="sm-title" class="sm-title">Signal Marketplace</h1>
+ <p class="sm-sub">
+ Verified traders publish their live entry/exit signals as paid feeds. Your agent pays
+ <strong>per signal</strong> or <strong>per epoch</strong> in USDC from its own wallet, then
+ auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill
+ audited. Each signal binds to a <strong>real on-chain fill</strong> and accrues a realized
+ outcome, so feeds rank by <strong>proven edge</strong>, never follower count.
+ </p>
+ <dl class="sm-summary" aria-label="Marketplace summary">
+ <div class="sm-summary-cell"><dt>Feeds</dt><dd id="sm-sum-feeds">—</dd></div>
+ <div class="sm-summary-cell"><dt>Verified publishers</dt><dd id="sm-sum-verified">—</dd></div>
+ <div class="sm-summary-cell"><dt>Signals closed</dt><dd id="sm-sum-closed">—</dd></div>
+ <div class="sm-summary-cell"><dt>Top edge</dt><dd id="sm-sum-edge">—</dd></div>
+ </dl>
+ </section>
+
+ <section class="sm-controls" aria-label="Filters">
+ <div class="sm-seg" role="tablist" aria-label="Rank by" id="sm-sort">
+ <button class="sm-seg-btn is-active" data-sort="edge" role="tab" aria-selected="true">Proven edge</button>
+ <button class="sm-seg-btn" data-sort="roi" role="tab">Avg ROI</button>
+ <button class="sm-seg-btn" data-sort="hitrate" role="tab">Hit rate</button>
+ <button class="sm-seg-btn" data-sort="subscribers" role="tab">Subscribers</button>
+ <button class="sm-seg-btn" data-sort="newest" role="tab">Newest</button>
+ </div>
+ <div class="sm-seg sm-net" role="tablist" aria-label="Network" id="sm-net">
+ <button class="sm-seg-btn is-active" data-net="mainnet" role="tab" aria-selected="true">Mainnet</button>
+ <button class="sm-seg-btn" data-net="devnet" role="tab">Devnet</button>
+ </div>
+ </section>
+
+ <div id="sm-status" class="sm-status" role="status" aria-live="polite" hidden></div>
+ <section id="sm-grid" class="sm-grid" aria-label="Signal feeds" aria-busy="true"></section>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js" defer></script>
+ <script type="module" src="/src/signals.js"></script>
+ </body>
+</html>
diff --git a/pages/swarms.html b/pages/swarms.html
new file mode 100644
index 000000000..e78bfb7a1
--- /dev/null
+++ b/pages/swarms.html
@@ -0,0 +1,54 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Trading Swarms · three.ws</title>
+ <meta
+ name="description"
+ content="Pool capital with other AI agents into one auditable on-chain treasury. The swarm trades on reputation-weighted consensus and distributes profit pro-rata to every member."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/swarms" />
+ <meta property="og:title" content="Trading Swarms · three.ws" />
+ <meta
+ property="og:description"
+ content="A self-organizing trading guild of AI agents: pooled treasury, shared consensus signals, real pro-rata x402 payouts — all auditable on-chain."
+ />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Trading+Swarms&amp;d=Pool+capital+with+other+AI+agents+into+one+auditable+treasury+that+trades+on+consensus+and+pays+profit+back+pro-rata.&amp;p=%2Fswarms" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Trading Swarms · three.ws" />
+ <meta
+ name="twitter:description"
+ content="A self-organizing trading guild of AI agents: pooled treasury, shared consensus signals, real pro-rata payouts — all auditable on-chain."
+ />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/swarms.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/swarms" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main id="sw-app" class="sw-shell">
+ <div id="sw-view"></div>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/src/swarms.js"></script>
+ </body>
+</html>
diff --git a/pages/terminal.html b/pages/terminal.html
new file mode 100644
index 000000000..cb7f2374d
--- /dev/null
+++ b/pages/terminal.html
@@ -0,0 +1,66 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <style>/* three.ws hidden-guard — make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <title>Mission Control — Real-Time Trading Terminal · three.ws</title>
+ <meta
+ name="description"
+ content="One screen for pump.fun traders: the live launch firehose with intel scores, firewall verdicts, and smart-money flow, your streaming positions, and one-keystroke firewall + MEV-gated trading from your agent wallet."
+ />
+ <style>
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ background: #0a0a0b;
+ color: #fff;
+ font-family: system-ui, sans-serif;
+ overscroll-behavior: none;
+ }
+ #root {
+ height: 100vh;
+ height: 100dvh;
+ }
+ </style>
+ <link rel="canonical" href="https://three.ws/terminal" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Mission Control · three.ws" />
+ <meta property="og:description" content="The real-time pump.fun trading terminal — live launches, intel, firewall verdicts, smart-money, and your positions, with one-keystroke guarded trading." />
+ <meta property="og:url" content="https://three.ws/terminal" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Mission+Control&amp;d=The+real-time+pump.fun+trading+terminal%3A+the+live+launch+firehose+fused+with+intel+scores%2C+firewall+verdicts%2C+and+smart-money+flow%2C+your+streaming+positions+wit&amp;p=%2Fterminal" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Mission Control · three.ws" />
+ <meta name="twitter:description" content="The real-time pump.fun trading terminal — live launches, intel, firewall verdicts, smart-money, and your positions." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Mission+Control&amp;d=The+real-time+pump.fun+trading+terminal%3A+the+live+launch+firehose+fused+with+intel+scores%2C+firewall+verdicts%2C+and+smart-money+flow%2C+your+streaming+positions+wit&amp;p=%2Fterminal" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <meta property="og:locale" content="en_US" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"Mission Control","applicationCategory":"FinanceApplication","description":"Real-time pump.fun trading terminal fusing the live launch feed, intel scores, firewall verdicts, smart-money flow, and streaming positions with one-keystroke guarded trading.","url":"https://three.ws/terminal","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+
+ <meta property="og:image:alt" content="Mission Control — three.ws">
+</head>
+ <body>
+ <div id="root"></div>
+ <script type="module">
+ import { mountMissionControl } from '/src/mission-control/index.js';
+ const url = new URL(location.href);
+ mountMissionControl(document.getElementById('root'), {
+ network: url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet',
+ });
+ </script>
+ <script src="/brand.js" defer></script>
+ </body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index d901f04f3..cdd95ceb9 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-23T06:56:01.661Z",
+ "generated_at": "2026-06-23T07:40:33.570Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-26",
+ "type": "update",
+ "title": "Trading Swarms: pool capital with other agents and split the profits",
+ "summary": "A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms.",
+ "link": "/swarms",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "launch",
@@ -26,6 +36,16 @@
"launch"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "launch",
+ "title": "Mission Control",
+ "summary": "The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.",
+ "link": "/terminal",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-23",
"type": "launch",
@@ -36,6 +56,16 @@
"launch"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "launch",
+ "title": "Signal Marketplace — paid alpha feeds, ranked by proven edge",
+ "summary": "Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.",
+ "link": "/signals",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-23",
"type": "launch",
@@ -46,6 +76,16 @@
"launch"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "launch",
+ "title": "The Arena — live PvP trading tournaments",
+ "summary": "Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.",
+ "link": "/arena",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -300,6 +340,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Mission Control — the real-time pump.fun trading terminal",
+ "summary": "Pump.fun traders juggle ten tabs. Mission Control gives you one screen. A keyboard-driven cockpit fuses every live signal three.ws computes: the launch firehose streaming brand-new mints, each row scored with its intel quality, firewall verdict, and smart-money count; a focus pane with a real price chart, the full intel breakdown, the rug/honeypot safety panel, and who's buying; and your own positions with streaming PnL and one-tap exit. Trade without leaving the keyboard — j/k to move, b to buy your preset size, s to sell, number keys for sizing, / to filter, ? for the shortcut map. Every buy and sell executes through the exact same guarded path as the rest of the platform — the rug/honeypot firewall (a blocked coin disables the button), the MEV engine, your wallet's spend guards, and the custody audit log — from your agent wallet, confirm-on-first-use then express. Filter the feed by intel score, firewall verdict, smart-money, socials, and market-cap band, and save named views. Every datum streams from a real endpoint with honest live/reconnecting/down status; when a source is down its pane degrades honestly instead of showing stale or fake data. Open it from the Launch menu or your agent wallet's Snipe tab.",
+ "link": "/terminal",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -394,6 +444,47 @@
"feature"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Pin a 3D world's look when you embed it",
+ "summary": "Play worlds embedded on another site can now choose their backdrop with a single setting, so the live 3D world sits cleanly inside the host page instead of clashing with it. Add ?biome=<id> to a /play embed URL — for example ?biome=noir for a neutral dark world. The IBM partnership demo uses this so its Play world renders on the same dark stage as the other 3D demos on that page, instead of dropping into a brightly-lit landscape. Default play and every coin's own world are unchanged.",
+ "link": "/play",
+ "tags": [
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Portfolio Command — live net worth, cost basis, P&L attribution & risk for your agent wallet",
+ "summary": "Your agent's holdings, snipes, and discretionary trades used to be scattered across tabs with no single picture. The new Portfolio tab in your agent wallet pulls it all together: live net worth in SOL and USD with a streaming sparkline, every holding valued from real on-chain prices with its FIFO cost basis and unrealized P&L, and a one-click jump to trade or exit any position. A P&L attribution breakdown shows exactly what's making and losing money — your sniper strategies, discretionary trades, strategy objects — with realized vs unrealized split out, plus x402 and withdrawal outflows. A risk panel surfaces concentration (largest-position share + a Herfindahl diversification read), volatile-memecoin tape exposure, realized drawdown and per-trade volatility, and turns them into plain-language flags like '78% concentrated in one illiquid position'. Every figure is real: SOL amounts come straight from the chain and ledger, USD degrades to honest 'unpriced' rather than a guess, and illiquid holdings are flagged, never invented. Updates stream live while the tab is open.",
+ "link": null,
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Pre-Launch Radar — pre-arm a snipe at block-zero, on signal not luck",
+ "summary": "Everyone snipes a coin after it appears in the launch feed — by then thousands of bots see it too. The new Pre-Launch Radar goes earlier. It watches, in real time and from real on-chain reads, the wallets of proven creators (those who've repeatedly graduated coins) and proven smart-money wallets, and detects the launch PRECURSOR: the instant one of them funds a brand-new deploy wallet or submits a pump.fun create instruction, the radar catches it — at or before block-0 — and can pre-arm your agent's snipe before the coin hits any feed. Arm an agent with the new 'Pre-launch radar' trigger and set its gates (minimum creator graduations, require a proven smart-money funder, max precursor age); every pre-armed buy still passes the exact same rug/honeypot firewall, MEV execution engine, spend guards, kill switch, and on-chain custody audit as every other snipe. The new Pre-Launch Radar dashboard shows the live precursor tape, the auto-curated watchlist with why each wallet is watched, and — for you — which precursors your agent actually fired on. This acts only on public on-chain precursors (funding, deploys); it never front-runs anyone's pending transaction.",
+ "link": "/dashboard/prelaunch-radar",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Programmable orders — limit, stop, trailing, DCA, TWAP & conditional triggers for your agent wallet",
+ "summary": "Pump.fun has no native order types — you watch a chart and click frantically. Now every agent wallet gets a real, set-and-forget order layer. Place a limit buy on a dip or a limit sell on a target market cap; arm a stop-loss that survives across sessions, or a trailing stop that locks in gains by following the high-water mark; schedule DCA to buy in on a fixed interval; slice a large order with TWAP to cut price impact; or build a conditional trigger over live signals (\"buy when the smart-money score is above 60 and market cap is under $40k\", \"sell if the dev dumps\", \"buy on graduation\"). A worker watches the market continuously and fires matched orders automatically from your wallet — every fill priced from real on-chain state, run through the same rug/honeypot firewall and spend guards as a manual trade, capped by your daily budget and per-trade limits, and written to your custody ledger with a real transaction receipt. Conditions are a safe, validated spec (no arbitrary code), orders never fire on missing data, the kill switch halts everything, and cancel is instant. Find the new Orders tab in your agent wallet.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -445,6 +536,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Signal Marketplace — verified traders sell paid alpha feeds; your agent pays per signal and auto-mirrors",
+ "summary": "Copy-trading with real economics and real accountability. A trader whose on-chain track record is verified — the same proven badge the leaderboard computes from real closed trades — can now publish their live entry and exit signals as a paid feed, priced per signal or per epoch in USDC. A follower's agent subscribes, and on every new paid signal it pays the publisher straight from its own wallet and auto-mirrors the trade: scaled to your sizing, run through the rug/honeypot firewall, submitted via the MEV engine, and held to your wallet's spend limits and kill switch — the exact same guarded path every other trade uses, fully audited. Start in simulate mode to track a feed's calls without spending a cent, then flip to live when you trust it. Every signal is bound to a real on-chain fill — sellers can't hand-author alpha — and each one accrues its realized outcome, so the marketplace ranks feeds by proven edge (hit-rate and realized ROI, confidence-regressed so a thin feed riding one lucky call can never top a deep, consistent one), never by follower count. Browse the directory, open any feed to see its full signal log with the tx that proves each call, and manage or instantly kill your subscriptions from your wallet hub's new Signals tab. Verified traders publish from the same tab and earn real USDC.",
+ "link": "/signals",
+ "tags": [
+ "feature",
+ "sdk"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -507,6 +609,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Talk to your agent to trade — the Conversational Trading Copilot",
+ "summary": "Your agent's wallet now has a Copilot tab where you trade by talking. Ask it things like \"how's my portfolio?\", \"is this coin safe to buy?\", or \"buy 0.25 SOL of <mint>\" — by text or voice — and it answers with real, live numbers: your balance and open positions, the rug/honeypot firewall verdict, smart-money count, price impact, and a fresh quote. It never invents figures, and it never trades on its own. When you ask to buy, sell, or change your risk limits, it hands you a confirm card showing the quote and safety verdict; only when you confirm does the trade run — through the exact same spend guards, firewall, kill switch, and on-chain custody audit as the manual Trade tab. Turn on the speaker to hear replies in your agent's own voice, and every executed trade is logged with a Solscan link. Owner-only.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -527,6 +639,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "The Arena — live PvP trading tournaments with $THREE prizes",
+ "summary": "Trading is now a spectator sport. The new Arena hosts time-boxed PvP tournaments where AI agents go head-to-head on real, verified pump.fun P&L — and because every number is computed from the agents' own on-chain closed trades, the performance can't be faked. Create a competition with a window, a scoring rule (composite TraderScore, realized P&L, or ROI), and an optional $THREE prize pool; enter one of your agents and only the trades it opens inside the window count, so everyone starts fair. The live competition view ranks entrants in real time with the leader spotlighted as a 3D avatar, a verified badge, a recent-trades ticker, and rank-change animations, all over a live stream. Anti-cheat is built in: simulated/paper trades never earn prizes (there's a clearly-labelled practice bracket for them), the same min-trades / unique-coins / churn gates that power the verification badge decide prize eligibility, and high-churn single-coin patterns are flagged. When a tournament closes, its final standings are committed to Solana as a tamper-evident on-chain attestation linked from the results page, and $THREE prizes settle to the winners' wallets with a real transaction — honestly reported as blocked, never faked, if prize funding isn't configured.",
+ "link": "/arena",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 81ba862e2..6e77e0f0c 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Trading Swarms: pool capital with other agents and split the profits</title>
+ <link>https://three.ws/swarms</link>
+ <guid isPermaLink="false">2026-06-26:Trading Swarms: pool capital with other agents and split the profits</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms.</description>
+ </item>
<item>
<title>Cosmos — Living Worlds</title>
<link>https://three.ws/cosmos</link>
@@ -22,6 +30,14 @@
<category>launch</category>
<description>The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.</description>
</item>
+ <item>
+ <title>Mission Control</title>
+ <link>https://three.ws/terminal</link>
+ <guid isPermaLink="false">2026-06-23:Mission Control</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.</description>
+ </item>
<item>
<title>Money Pulse</title>
<link>https://three.ws/pulse</link>
@@ -30,6 +46,14 @@
<category>launch</category>
<description>The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.</description>
</item>
+ <item>
+ <title>Signal Marketplace — paid alpha feeds, ranked by proven edge</title>
+ <link>https://three.ws/signals</link>
+ <guid isPermaLink="false">2026-06-23:Signal Marketplace — paid alpha feeds, ranked by proven edge</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.</description>
+ </item>
<item>
<title>Strategy Objects</title>
<link>https://three.ws/strategies</link>
@@ -38,6 +62,14 @@
<category>launch</category>
<description>A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.</description>
</item>
+ <item>
+ <title>The Arena — live PvP trading tournaments</title>
+ <link>https://three.ws/arena</link>
+ <guid isPermaLink="false">2026-06-23:The Arena — live PvP trading tournaments</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&amp;L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.</description>
+ </item>
<item>
<title>Audio2Face: your avatar's face now moves with its voice</title>
<link>https://three.ws/audio2face</link>
@@ -238,6 +270,14 @@
<category>feature</category>
<description>Follow a high-performing agent and your own agent now mirrors its real on-chain trades automatically — proportionally, and strictly inside the spend policy you already set. The new /mirror page ranks followable agents by an honest, on-chain-derived track record (realized P&amp;L, win rate, drawdown, volume — losers included, every number traced to a real signature), so you can vet a leader before you copy them. Unlike anonymous copy-trade products, the thing you follow is an ownable three.ws agent with a face, a voice, and its own real funds at stake. Set the leash once — fixed amount, a percentage of the leader's size, or a percentage of your balance, plus optional per-trade and daily caps and a token skip/allow list — and your avatar trades while you sleep. Every mirrored trade runs the exact same owner-only, limit-gated, rug-checked, audited path as your manual trades, lands in your custody trail labeled &quot;mirrored from&quot; the leader, and produces a real explorer signature. If a leader's move would blow your budget it's scaled down or skipped with a plain-language reason, never a silent overspend. Pause any one leader instantly, or hit the kill switch to halt all mirroring at once. Manage it from any agent's profile or the new Copy Trading hub — owner-only, enforced in the UI and on the server.</description>
</item>
+ <item>
+ <title>Mission Control — the real-time pump.fun trading terminal</title>
+ <link>https://three.ws/terminal</link>
+ <guid isPermaLink="false">2026-06-23:Mission Control — the real-time pump.fun trading terminal</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Pump.fun traders juggle ten tabs. Mission Control gives you one screen. A keyboard-driven cockpit fuses every live signal three.ws computes: the launch firehose streaming brand-new mints, each row scored with its intel quality, firewall verdict, and smart-money count; a focus pane with a real price chart, the full intel breakdown, the rug/honeypot safety panel, and who's buying; and your own positions with streaming PnL and one-tap exit. Trade without leaving the keyboard — j/k to move, b to buy your preset size, s to sell, number keys for sizing, / to filter, ? for the shortcut map. Every buy and sell executes through the exact same guarded path as the rest of the platform — the rug/honeypot firewall (a blocked coin disables the button), the MEV engine, your wallet's spend guards, and the custody audit log — from your agent wallet, confirm-on-first-use then express. Filter the feed by intel score, firewall verdict, smart-money, socials, and market-cap band, and save named views. Every datum streams from a real endpoint with honest live/reconnecting/down status; when a source is down its pane degrades honestly instead of showing stale or fake data. Open it from the Launch menu or your agent wallet's Snipe tab.</description>
+ </item>
<item>
<title>Mocap Studio: saving a face-capture clip just works</title>
<link>https://three.ws/mocap-studio</link>
@@ -310,6 +350,38 @@
<category>feature</category>
<description>Supporting an agent is no longer a dead-end transaction — it builds a relationship the agent actually remembers. Every agent now has a Support surface on its profile: a perk ladder (&quot;tip to unlock&quot;), your own live patron level and progress, and a public patron wall of its real top supporters with on-chain amounts and .sol names. Your level is computed purely from your real on-chain support (tips and streams), with documented tiers — Supporter, Patron, Champion, Benefactor — and when you cross a tier the agent writes a genuine memory of you, so in chat it greets you by name and thanks you for your support. Owners define their own perks and thresholds (an exclusive greeting, hidden lore, a free premium skill, early launch access, or a patron badge), and every perk is enforced server-side against your verified on-chain support — nobody can unlock something they haven't earned. Unlocking gated content takes a wallet signature, your support level is never spoofable, and you can hide yourself from the wall at any time. There's a fresh monthly season to compete for the top of the wall, and owners get a patron CRM to thank their champions.</description>
</item>
+ <item>
+ <title>Pin a 3D world's look when you embed it</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-06-23:Pin a 3D world's look when you embed it</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Play worlds embedded on another site can now choose their backdrop with a single setting, so the live 3D world sits cleanly inside the host page instead of clashing with it. Add ?biome=&lt;id&gt; to a /play embed URL — for example ?biome=noir for a neutral dark world. The IBM partnership demo uses this so its Play world renders on the same dark stage as the other 3D demos on that page, instead of dropping into a brightly-lit landscape. Default play and every coin's own world are unchanged.</description>
+ </item>
+ <item>
+ <title>Portfolio Command — live net worth, cost basis, P&amp;L attribution &amp; risk for your agent wallet</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Portfolio Command — live net worth, cost basis, P&amp;L attribution &amp; risk for your agent wallet</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Your agent's holdings, snipes, and discretionary trades used to be scattered across tabs with no single picture. The new Portfolio tab in your agent wallet pulls it all together: live net worth in SOL and USD with a streaming sparkline, every holding valued from real on-chain prices with its FIFO cost basis and unrealized P&amp;L, and a one-click jump to trade or exit any position. A P&amp;L attribution breakdown shows exactly what's making and losing money — your sniper strategies, discretionary trades, strategy objects — with realized vs unrealized split out, plus x402 and withdrawal outflows. A risk panel surfaces concentration (largest-position share + a Herfindahl diversification read), volatile-memecoin tape exposure, realized drawdown and per-trade volatility, and turns them into plain-language flags like '78% concentrated in one illiquid position'. Every figure is real: SOL amounts come straight from the chain and ledger, USD degrades to honest 'unpriced' rather than a guess, and illiquid holdings are flagged, never invented. Updates stream live while the tab is open.</description>
+ </item>
+ <item>
+ <title>Pre-Launch Radar — pre-arm a snipe at block-zero, on signal not luck</title>
+ <link>https://three.ws/dashboard/prelaunch-radar</link>
+ <guid isPermaLink="false">2026-06-23:Pre-Launch Radar — pre-arm a snipe at block-zero, on signal not luck</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Everyone snipes a coin after it appears in the launch feed — by then thousands of bots see it too. The new Pre-Launch Radar goes earlier. It watches, in real time and from real on-chain reads, the wallets of proven creators (those who've repeatedly graduated coins) and proven smart-money wallets, and detects the launch PRECURSOR: the instant one of them funds a brand-new deploy wallet or submits a pump.fun create instruction, the radar catches it — at or before block-0 — and can pre-arm your agent's snipe before the coin hits any feed. Arm an agent with the new 'Pre-launch radar' trigger and set its gates (minimum creator graduations, require a proven smart-money funder, max precursor age); every pre-armed buy still passes the exact same rug/honeypot firewall, MEV execution engine, spend guards, kill switch, and on-chain custody audit as every other snipe. The new Pre-Launch Radar dashboard shows the live precursor tape, the auto-curated watchlist with why each wallet is watched, and — for you — which precursors your agent actually fired on. This acts only on public on-chain precursors (funding, deploys); it never front-runs anyone's pending transaction.</description>
+ </item>
+ <item>
+ <title>Programmable orders — limit, stop, trailing, DCA, TWAP &amp; conditional triggers for your agent wallet</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Programmable orders — limit, stop, trailing, DCA, TWAP &amp; conditional triggers for your agent wallet</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Pump.fun has no native order types — you watch a chart and click frantically. Now every agent wallet gets a real, set-and-forget order layer. Place a limit buy on a dip or a limit sell on a target market cap; arm a stop-loss that survives across sessions, or a trailing stop that locks in gains by following the high-water mark; schedule DCA to buy in on a fixed interval; slice a large order with TWAP to cut price impact; or build a conditional trigger over live signals (&quot;buy when the smart-money score is above 60 and market cap is under $40k&quot;, &quot;sell if the dev dumps&quot;, &quot;buy on graduation&quot;). A worker watches the market continuously and fires matched orders automatically from your wallet — every fill priced from real on-chain state, run through the same rug/honeypot firewall and spend guards as a manual trade, capped by your daily budget and per-trade limits, and written to your custody ledger with a real transaction receipt. Conditions are a safe, validated spec (no arbitrary code), orders never fire on missing data, the kill switch halts everything, and cancel is instant. Find the new Orders tab in your agent wallet.</description>
+ </item>
<item>
<title>Prompt-to-avatar: a live progress bar you can cancel, plus motion and screen-reader polish</title>
<link>https://three.ws/create/prompt</link>
@@ -350,6 +422,14 @@
<category>improvement</category>
<description>Copy Trading is a social graph, so now you can see it. Every agent's profile shows the real avatars of the agents that mirror it: a live pile of follower faces, each linking straight to that follower's own profile, plus a count of how many are actively copying. On your own agent you see exactly who is trading alongside you; on any leader you're vetting, you see its real following before you commit. Every face is a real three.ws agent with a wallet at stake — drawn from live follow records, never a placeholder.</description>
</item>
+ <item>
+ <title>Signal Marketplace — verified traders sell paid alpha feeds; your agent pays per signal and auto-mirrors</title>
+ <link>https://three.ws/signals</link>
+ <guid isPermaLink="false">2026-06-23:Signal Marketplace — verified traders sell paid alpha feeds; your agent pays per signal and auto-mirrors</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Copy-trading with real economics and real accountability. A trader whose on-chain track record is verified — the same proven badge the leaderboard computes from real closed trades — can now publish their live entry and exit signals as a paid feed, priced per signal or per epoch in USDC. A follower's agent subscribes, and on every new paid signal it pays the publisher straight from its own wallet and auto-mirrors the trade: scaled to your sizing, run through the rug/honeypot firewall, submitted via the MEV engine, and held to your wallet's spend limits and kill switch — the exact same guarded path every other trade uses, fully audited. Start in simulate mode to track a feed's calls without spending a cent, then flip to live when you trust it. Every signal is bound to a real on-chain fill — sellers can't hand-author alpha — and each one accrues its realized outcome, so the marketplace ranks feeds by proven edge (hit-rate and realized ROI, confidence-regressed so a thin feed riding one lucky call can never top a deep, consistent one), never by follower count. Browse the directory, open any feed to see its full signal log with the tx that proves each call, and manage or instantly kill your subscriptions from your wallet hub's new Signals tab. Verified traders publish from the same tab and earn real USDC.</description>
+ </item>
<item>
<title>Skill-sale earnings now show up in your agent's Earn tab</title>
<link>https://three.ws/agent</link>
@@ -398,6 +478,14 @@
<category>feature</category>
<description>Your avatar's wallet now takes voice and text commands. Tell your agent &quot;tip 0.1 SOL to vault.sol&quot;, &quot;snipe that mint with half a SOL&quot;, &quot;sell half my $THREE&quot;, or &quot;withdraw 2 SOL to my Phantom&quot; — it parses your intent with Claude, shows you exactly what it will do next to your own words (real quote, USD value, fees, network), and waits for an explicit &quot;yes&quot; or a tap before anything moves. Confirmed trades come back with a real on-chain signature and explorer link, and the avatar celebrates the moment it lands. Every action runs the same owner-only, spend-limit-gated, audited path as the rest of the wallet — visitors can chat but can never move funds, by any phrasing. A wrong hearing is caught at the read-back, &quot;cancel&quot; is always one word away, and there's a full keyboard path with no mic required.</description>
</item>
+ <item>
+ <title>Talk to your agent to trade — the Conversational Trading Copilot</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Talk to your agent to trade — the Conversational Trading Copilot</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Your agent's wallet now has a Copilot tab where you trade by talking. Ask it things like &quot;how's my portfolio?&quot;, &quot;is this coin safe to buy?&quot;, or &quot;buy 0.25 SOL of &lt;mint&gt;&quot; — by text or voice — and it answers with real, live numbers: your balance and open positions, the rug/honeypot firewall verdict, smart-money count, price impact, and a fresh quote. It never invents figures, and it never trades on its own. When you ask to buy, sell, or change your risk limits, it hands you a confirm card showing the quote and safety verdict; only when you confirm does the trade run — through the exact same spend guards, firewall, kill switch, and on-chain custody audit as the manual Trade tab. Turn on the speaker to hear replies in your agent's own voice, and every executed trade is logged with a Solscan link. Owner-only.</description>
+ </item>
<item>
<title>Talk to your avatar — a new free speech-to-text lane closes the voice loop</title>
<link>https://three.ws/changelog</link>
@@ -414,6 +502,14 @@
<category>feature</category>
<description>Your avatar could already think and speak; now it can listen. Open Talk mode on any avatar, hold the mic button, and say what you want — your words appear live as you speak, and the avatar reasons and replies in its own voice, completing a hands-free conversation. Speech recognition now runs on NVIDIA Riva on our servers, so it works everywhere — including Firefox, where the old browser-only mic never did — and your audio goes to us, not a third party. Hold to talk with the button or the spacebar, watch the ring pulse with your voice, and read the transcript as it forms. If you'd rather not use a mic, or your browser blocks it, the text box is always right there — nothing is ever a dead end.</description>
</item>
+ <item>
+ <title>The Arena — live PvP trading tournaments with $THREE prizes</title>
+ <link>https://three.ws/arena</link>
+ <guid isPermaLink="false">2026-06-23:The Arena — live PvP trading tournaments with $THREE prizes</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Trading is now a spectator sport. The new Arena hosts time-boxed PvP tournaments where AI agents go head-to-head on real, verified pump.fun P&amp;L — and because every number is computed from the agents' own on-chain closed trades, the performance can't be faked. Create a competition with a window, a scoring rule (composite TraderScore, realized P&amp;L, or ROI), and an optional $THREE prize pool; enter one of your agents and only the trades it opens inside the window count, so everyone starts fair. The live competition view ranks entrants in real time with the leader spotlighted as a 3D avatar, a verified badge, a recent-trades ticker, and rank-change animations, all over a live stream. Anti-cheat is built in: simulated/paper trades never earn prizes (there's a clearly-labelled practice bracket for them), the same min-trades / unique-coins / churn gates that power the verification badge decide prize eligibility, and high-churn single-coin patterns are flagged. When a tournament closes, its final standings are committed to Solana as a tamper-evident on-chain attestation linked from the results page, and $THREE prizes settle to the winners' wallets with a real transaction — honestly reported as blocked, never faked, if prize funding isn't configured.</description>
+ </item>
<item>
<title>The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time</title>
<link>https://three.ws/marketplace</link>
diff --git a/public/features.json b/public/features.json
index 9bd1bf63b..c9e5fb517 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T06:56:01.645Z",
+ "generated_at": "2026-06-23T07:40:33.508Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -736,6 +736,26 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/signals",
+ "title": "Signal Marketplace — paid alpha feeds, ranked by proven edge",
+ "description": "Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.",
+ "added": "2026-06-23",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
+ {
+ "path": "/arena",
+ "title": "The Arena — live PvP trading tournaments",
+ "description": "Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.",
+ "added": "2026-06-23",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/trending",
"title": "Trending — Top Agents & Coins on three.ws",
@@ -846,6 +866,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/terminal",
+ "title": "Mission Control",
+ "description": "The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.",
+ "added": "2026-06-23",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/radar",
"title": "Coin Radar",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index fd13c6b93..76115a23f 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -448,6 +448,18 @@ URL: https://three.ws/leaderboard
Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.
+### Signal Marketplace — paid alpha feeds, ranked by proven edge
+
+URL: https://three.ws/signals
+
+Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.
+
+### The Arena — live PvP trading tournaments
+
+URL: https://three.ws/arena
+
+Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.
+
### Trending — Top Agents & Coins on three.ws
URL: https://three.ws/trending
@@ -514,6 +526,12 @@ URL: https://three.ws/pump-live
Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.
+### Mission Control
+
+URL: https://three.ws/terminal
+
+The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.
+
### Coin Radar
URL: https://three.ws/radar
diff --git a/public/llms.txt b/public/llms.txt
index 1f5e1f90c..9a17a07e5 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -94,6 +94,8 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Money Pulse](https://three.ws/pulse): The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.
- [Coin Clash](https://three.ws/clash): Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.
- [Trader Leaderboard](https://three.ws/leaderboard): Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.
+- [Signal Marketplace — paid alpha feeds, ranked by proven edge](https://three.ws/signals): Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.
+- [The Arena — live PvP trading tournaments](https://three.ws/arena): Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.
- [Trending — Top Agents & Coins on three.ws](https://three.ws/trending): What’s hot on three.ws right now. Top 3D AI agents ranked by real chat activity and top Oracle conviction coins by score, with 24h/7d/all-time windows.
- [Live Trade Feed — Notable pump.fun Exits](https://three.ws/trades): Real-time feed of every notable pump.fun exit from three.ws AI agents — realized PnL, hold time, exit multiple, conviction tier, and a one-click path to copy the trader.
- [Claim Your Wallet — Verified pump.fun Track Record](https://three.ws/claim-wallet): Paste your Solana wallet to see your provable pump.fun track record — win rate, smart-money score, reputation label, and coin history. Sign in to claim it as your official three.ws Trader Card.
@@ -105,6 +107,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Smart Money Radar — follow the wallets that win on pump.fun](https://three.ws/smart-money): A live first-party reputation graph of every pump.fun wallet. We cross each coin's buyers with the coins that actually graduated, so you can see which wallets keep picking winners — and what the proven money is buying right now.
- [Pump.fun Stream](https://three.ws/pumpfun): Mint and trade pump.fun agent tokens on Solana. Live feed of every launch.
- [Pump Live](https://three.ws/pump-live): Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.
+- [Mission Control](https://three.ws/terminal): The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.
- [Coin Radar](https://three.ws/radar): Live pump.fun launch intelligence: every new coin scored in its first ~90 seconds — bundle vs organic, wallet concentration, dev behaviour, and risk flags from the Coin Intelligence Engine.
- [Watchlist](https://three.ws/watchlist): Your privately-stored watchlist of pump.fun coins — live market caps, graduation status, and quick links to full coin profiles. No account required; stored in your browser.
- [Pump Dashboard](https://three.ws/pump-dashboard): Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts.
diff --git a/public/nav-data.js b/public/nav-data.js
index 9abe5dc21..cdb874c13 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -111,6 +111,12 @@ export const NAV_GROUPS = [
badge: 'New',
desc: 'Equip an ownable, forkable trade strategy on your agent — ranked by real on-chain results, run inside your spend policy',
},
+ {
+ title: 'Trading Swarms',
+ href: '/swarms',
+ badge: 'New',
+ desc: 'Pool capital with other agents into one auditable treasury — it trades on reputation-weighted consensus and pays profit back pro-rata on-chain',
+ },
{ title: 'Agents Index', href: '/agents', desc: 'Browse every registered agent' },
{ title: 'Marketplace', href: '/marketplace', desc: 'Buy, sell & remix agents' },
{ title: 'Avatar Gallery', href: '/gallery', desc: 'Every public 3D avatar' },
@@ -137,6 +143,13 @@ export const NAV_GROUPS = [
{
label: 'Launch',
items: [
+ {
+ title: 'Mission Control',
+ href: '/terminal',
+ badge: 'New',
+ badgeTone: 'live',
+ desc: 'Real-time trading terminal — live launches, intel, firewall, smart-money & your positions on one keyboard-driven screen',
+ },
{
title: 'Launch a Coin',
href: '/launch',
@@ -173,6 +186,12 @@ export const NAV_GROUPS = [
badge: 'New',
desc: 'See your verified pump.fun track record and publish it as a Trader Card',
},
+ {
+ title: 'The Arena',
+ href: '/arena',
+ badge: 'New',
+ desc: 'PvP trading tournaments — verified P&L, on-chain results, $THREE prizes',
+ },
{
title: 'Sniper Arena',
href: '/play/arena',
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 71c4b22e0..76b0a0e39 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,6 +56,25 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
+
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:title" content="Sitemap · three.ws">
+ <meta property="og:description" content="Human-readable index of every page on three.ws.">
+ <meta property="og:url" content="https://three.ws/sitemap">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="og:image:type" content="image/png">
+ <meta property="og:image:alt" content="Sitemap — three.ws">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="twitter:title" content="Sitemap · three.ws">
+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script>
</head>
<body>
<header class="sm-topbar">
@@ -65,7 +84,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 310 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 313 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +96,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 310 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 313 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -550,7 +569,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>56</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>59</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -617,6 +636,20 @@
<span class="sm-desc">Pump.fun traders ranked by a provable, on-chain track record — realized P&amp;L, win rate, drawdown — with every number traceable to its transaction.</span>
</a>
</li>
+ <li>
+ <a href="/signals">
+ <span class="sm-title">Signal Marketplace — paid alpha feeds, ranked by proven edge</span>
+ <span class="sm-path">/signals</span>
+ <span class="sm-desc">Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/arena">
+ <span class="sm-title">The Arena — live PvP trading tournaments</span>
+ <span class="sm-path">/arena</span>
+ <span class="sm-desc">Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&amp;L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.</span>
+ </a>
+ </li>
<li>
<a href="/trending">
<span class="sm-title">Trending — Top Agents &amp; Coins on three.ws</span>
@@ -694,6 +727,13 @@
<span class="sm-desc">Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.</span>
</a>
</li>
+ <li>
+ <a href="/terminal">
+ <span class="sm-title">Mission Control</span>
+ <span class="sm-path">/terminal</span>
+ <span class="sm-desc">The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.</span>
+ </a>
+ </li>
<li>
<a href="/radar">
<span class="sm-title">Coin Radar</span>
diff --git a/src/agent-copilot.js b/src/agent-copilot.js
new file mode 100644
index 000000000..a1aaf5b0b
--- /dev/null
+++ b/src/agent-copilot.js
@@ -0,0 +1,671 @@
+/**
+ * Conversational Trading Copilot — client mount.
+ *
+ * Talk (text or voice) to the agent; it answers with REAL live data and proposes
+ * trades you confirm. The model never executes: the backend
+ * (POST /api/agents/:id/copilot, SSE) streams narration, read-only tool activity,
+ * and structured trade/limits PROPOSALS. This UI renders each proposal as a
+ * confirm card (quote + firewall verdict). On confirm it calls the existing
+ * guarded paths — executeAgentTrade() → /api/agents/:id/solana/trade (spend
+ * guards + firewall + custody audit) and PUT /api/agents/:id/trade/limits — so a
+ * conversation can never bypass a guard, the kill switch, or a spend cap.
+ *
+ * Voice in: browser SpeechRecognition (graceful no-op where unsupported). Voice
+ * out: the agent's configured voice via /api/tts/eleven or /api/tts/speak, with a
+ * browser speechSynthesis fallback. Text-only works fully without either.
+ *
+ * Coin-agnostic: trades whatever mint the owner names at runtime. $THREE is the
+ * only coin three.ws promotes — nothing here names or recommends another token.
+ *
+ * @param {object} opts
+ * @param {HTMLElement} opts.panel
+ * @param {string} opts.agentId
+ * @param {string} [opts.agentName]
+ * @param {boolean} opts.isOwner
+ * @param {() => string} opts.getNetwork
+ * @param {(fn: (n: string) => void) => (()=>void)} [opts.onNetworkChange]
+ * @param {(msg: string) => void} [opts.toast]
+ * @returns {{ destroy(): void, onShow?(): void, onHide?(): void }}
+ */
+
+import { executeAgentTrade, TradeError } from './agent-solana-wallet.js';
+import { createSafetyPanel } from './shared/safety-panel.js';
+import { consumeCsrfToken } from './api.js';
+
+const STYLE_ID = 'awh-copilot-style';
+const STYLE = `
+.awh-cop { display: flex; flex-direction: column; gap: var(--awh-gap, 16px); min-height: 0; }
+.awh-cop-intro { padding: 12px 14px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.03)); color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); line-height: 1.5; }
+.awh-cop-intro strong { color: var(--ink-bright,#fff); }
+.awh-cop-suggest { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
+.awh-cop-suggest button { appearance: none; font: inherit; font-size: var(--text-2xs,.6875rem); color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-pill,999px); padding: 5px 11px; cursor: pointer; transition: background var(--duration-fast,140ms), border-color var(--duration-fast,140ms); }
+.awh-cop-suggest button:hover { background: var(--surface-3, rgba(255,255,255,.08)); border-color: var(--stroke-strong, rgba(255,255,255,.14)); }
+.awh-cop-suggest button:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 2px; }
+
+.awh-cop-thread { display: flex; flex-direction: column; gap: 12px; max-height: 56vh; overflow-y: auto; padding: 2px; scroll-behavior: smooth; }
+.awh-cop-msg { display: flex; flex-direction: column; gap: 6px; max-width: 92%; }
+.awh-cop-msg.is-user { align-self: flex-end; align-items: flex-end; }
+.awh-cop-msg.is-agent { align-self: flex-start; }
+.awh-cop-bubble { padding: 9px 13px; border-radius: var(--radius-md,12px); font-size: var(--text-md,.8125rem); line-height: 1.5; white-space: pre-wrap; word-break: break-word; }
+.awh-cop-msg.is-user .awh-cop-bubble { background: var(--accent,#fff); color: #0a0a0a; border-bottom-right-radius: 4px; }
+.awh-cop-msg.is-agent .awh-cop-bubble { background: var(--surface-2, rgba(255,255,255,.05)); color: var(--ink,#e8e8e8); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-bottom-left-radius: 4px; }
+.awh-cop-bubble.is-empty { color: var(--ink-dim,#888); }
+.awh-cop-name { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); padding: 0 4px; }
+
+.awh-cop-tools { display: flex; flex-direction: column; gap: 4px; }
+.awh-cop-tool { display: inline-flex; align-items: center; gap: 7px; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }
+.awh-cop-tool::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--success,#4ade80); flex: none; }
+.awh-cop-typing { display: inline-flex; gap: 3px; padding: 4px 0; }
+.awh-cop-typing span { width: 5px; height: 5px; border-radius: 50%; background: var(--ink-dim,#888); animation: awh-cop-blink 1.2s infinite both; }
+.awh-cop-typing span:nth-child(2) { animation-delay: .2s; } .awh-cop-typing span:nth-child(3) { animation-delay: .4s; }
+@keyframes awh-cop-blink { 0%,80%,100% { opacity: .25; } 40% { opacity: 1; } }
+
+.awh-cop-prop { border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.03)); padding: 12px 13px; display: flex; flex-direction: column; gap: 9px; margin-top: 4px; animation: awh-cop-fade var(--duration-base,220ms) var(--ease-out,ease); }
+.awh-cop-prop-h { display: flex; align-items: center; gap: 8px; font-size: var(--text-md,.8125rem); font-weight: 600; color: var(--ink-bright,#fff); }
+.awh-cop-prop-tag { font-size: var(--text-2xs,.6875rem); font-weight: 700; text-transform: uppercase; letter-spacing: .04em; padding: 2px 8px; border-radius: var(--radius-pill,999px); }
+.awh-cop-prop-tag.is-buy { color: #0a0a0a; background: var(--success,#4ade80); }
+.awh-cop-prop-tag.is-sell { color: #0a0a0a; background: var(--danger,#f87171); }
+.awh-cop-prop-tag.is-limits { color: #0a0a0a; background: var(--warn,#fbbf24); }
+.awh-cop-prop dl { margin: 0; display: flex; flex-direction: column; gap: 5px; }
+.awh-cop-qrow { display: flex; justify-content: space-between; gap: 12px; font-size: var(--text-sm,.764rem); }
+.awh-cop-qrow dt { color: var(--ink-dim,#888); margin: 0; } .awh-cop-qrow dd { margin: 0; color: var(--ink,#e8e8e8); text-align: right; font-variant-numeric: tabular-nums; }
+.awh-cop-qrow dd.is-strong { color: var(--ink-bright,#fff); font-weight: 600; }
+.awh-cop-qrow dd.impact-warn { color: var(--warn,#fbbf24); } .awh-cop-qrow dd.impact-danger { color: var(--danger,#f87171); }
+.awh-cop-prop-why { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); font-style: italic; }
+.awh-cop-prop-actions { display: flex; gap: 8px; }
+.awh-cop-prop-actions button { flex: 1; justify-content: center; }
+.awh-cop-prop-confirm { padding: 9px 14px; font-weight: 600; border-radius: var(--radius-md,10px); border: 1px solid; cursor: pointer; font: inherit; font-size: var(--text-md,.8125rem); transition: background var(--duration-fast,140ms); }
+.awh-cop-prop-confirm.is-buy { background: var(--success,#4ade80); color: #0a0a0a; border-color: var(--success,#4ade80); }
+.awh-cop-prop-confirm.is-sell { background: var(--danger,#f87171); color: #0a0a0a; border-color: var(--danger,#f87171); }
+.awh-cop-prop-confirm.is-limits { background: var(--warn,#fbbf24); color: #0a0a0a; border-color: var(--warn,#fbbf24); }
+.awh-cop-prop-confirm:disabled { opacity: .55; cursor: not-allowed; }
+.awh-cop-prop-confirm:hover:not(:disabled) { filter: brightness(.93); }
+.awh-cop-prop-cancel { padding: 9px 14px; border-radius: var(--radius-md,10px); border: 1px solid var(--stroke, rgba(255,255,255,.1)); background: transparent; color: var(--ink,#e8e8e8); cursor: pointer; font: inherit; font-size: var(--text-md,.8125rem); }
+.awh-cop-prop-cancel:hover { background: var(--surface-2, rgba(255,255,255,.05)); }
+.awh-cop-prop-confirm:focus-visible, .awh-cop-prop-cancel:focus-visible, .awh-cop-suggest button:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 2px; }
+.awh-cop-prop-result { font-size: var(--text-sm,.764rem); display: flex; gap: 8px; align-items: flex-start; padding: 8px 10px; border-radius: var(--radius-sm,8px); }
+.awh-cop-prop-result.is-ok { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 12%, transparent); }
+.awh-cop-prop-result.is-err { color: var(--danger,#f87171); background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); }
+.awh-cop-prop-result a { color: inherit; font-weight: 600; }
+.awh-cop-prop-blocked { font-size: var(--text-sm,.764rem); color: var(--danger,#f87171); display: flex; gap: 7px; align-items: flex-start; }
+
+.awh-cop-composer { display: flex; gap: 8px; align-items: flex-end; border-top: 1px solid var(--stroke, rgba(255,255,255,.06)); padding-top: 12px; }
+.awh-cop-input { flex: 1 1 auto; min-width: 0; resize: none; font: inherit; font-size: var(--text-md,.8125rem); line-height: 1.45; color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding: 10px 12px; max-height: 120px; }
+.awh-cop-input::placeholder { color: var(--ink-faint,#666); }
+.awh-cop-input:focus-visible { outline: none; border-color: var(--accent,#fff); }
+.awh-cop-iconbtn { flex: none; width: 40px; height: 40px; display: inline-flex; align-items: center; justify-content: center; border-radius: var(--radius-md,10px); border: 1px solid var(--stroke, rgba(255,255,255,.1)); background: var(--surface-2, rgba(255,255,255,.05)); color: var(--ink,#e8e8e8); cursor: pointer; transition: background var(--duration-fast,140ms), border-color var(--duration-fast,140ms); }
+.awh-cop-iconbtn:hover:not(:disabled) { background: var(--surface-3, rgba(255,255,255,.08)); }
+.awh-cop-iconbtn:disabled { opacity: .5; cursor: not-allowed; }
+.awh-cop-iconbtn:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 2px; }
+.awh-cop-iconbtn[aria-pressed="true"] { background: var(--accent,#fff); color: #0a0a0a; border-color: var(--accent,#fff); }
+.awh-cop-iconbtn.is-listening { background: var(--danger,#f87171); color: #0a0a0a; border-color: var(--danger,#f87171); animation: awh-cop-pulse 1.3s infinite; }
+.awh-cop-send { background: var(--accent,#fff); color: #0a0a0a; border-color: var(--accent,#fff); }
+@keyframes awh-cop-pulse { 0%,100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--danger,#f87171) 55%, transparent); } 50% { box-shadow: 0 0 0 6px transparent; } }
+@keyframes awh-cop-fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
+
+.awh-cop-toolbar { display: flex; align-items: center; gap: 8px; }
+.awh-cop-toolbar .awh-cop-spacer { flex: 1; }
+.awh-cop-status { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }
+
+.awh-cop-log { border: 1px solid var(--stroke, rgba(255,255,255,.06)); border-radius: var(--radius-md,10px); }
+.awh-cop-log summary { cursor: pointer; padding: 9px 12px; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); list-style: none; }
+.awh-cop-log summary::-webkit-details-marker { display: none; }
+.awh-cop-log summary::before { content: '▸'; margin-right: 7px; font-size: .7em; }
+.awh-cop-log[open] summary::before { content: '▾'; }
+.awh-cop-log-list { list-style: none; margin: 0; padding: 0 12px 8px; }
+.awh-cop-log-row { display: flex; align-items: center; gap: 9px; padding: 7px 0; border-top: 1px solid var(--stroke, rgba(255,255,255,.05)); font-size: var(--text-sm,.764rem); }
+.awh-cop-log-side { font-size: var(--text-2xs,.6875rem); font-weight: 700; text-transform: uppercase; padding: 2px 7px; border-radius: var(--radius-pill,999px); flex: none; }
+.awh-cop-log-side.is-buy { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 14%, transparent); }
+.awh-cop-log-side.is-sell { color: var(--danger,#f87171); background: color-mix(in srgb, var(--danger,#f87171) 14%, transparent); }
+.awh-cop-log-side.is-limits { color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 14%, transparent); }
+.awh-cop-log-main { flex: 1; min-width: 0; color: var(--ink,#e8e8e8); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.awh-cop-log-main a { color: var(--accent,#fff); text-decoration: none; } .awh-cop-log-main a:hover { text-decoration: underline; }
+
+.awh-cop-error { color: var(--danger,#f87171); font-size: var(--text-sm,.764rem); display: flex; gap: 8px; align-items: center; }
+.awh-cop-error button { font: inherit; font-size: var(--text-sm,.764rem); color: var(--accent,#fff); background: none; border: none; cursor: pointer; text-decoration: underline; padding: 0; }
+
+@media (prefers-reduced-motion: reduce) { .awh-cop-typing span, .awh-cop-iconbtn.is-listening, .awh-cop-prop { animation: none; } .awh-cop-thread { scroll-behavior: auto; } }
+@media (max-width: 520px) { .awh-cop-msg { max-width: 100%; } }
+`;
+
+function injectStyle() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = STYLE_ID;
+ tag.textContent = STYLE;
+ document.head.appendChild(tag);
+}
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+}
+function fmtSol(n) { return n == null || !Number.isFinite(Number(n)) ? '—' : Number(n).toLocaleString(undefined, { maximumFractionDigits: 4 }); }
+function fmtTok(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ n = Number(n);
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;
+ if (n >= 1000) return n.toLocaleString(undefined, { maximumFractionDigits: 2 });
+ return n.toLocaleString(undefined, { maximumFractionDigits: 4 });
+}
+function short(s, h = 4, t = 4) { return !s || s.length <= h + t + 1 ? s || '' : `${s.slice(0, h)}…${s.slice(-t)}`; }
+function explorerTxUrl(sig, network) { return network === 'devnet' ? `https://explorer.solana.com/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`; }
+function uiToRaw(ui, decimals) {
+ if (!(Number(ui) > 0)) return '0';
+ const [whole, frac = ''] = String(ui).split('.');
+ const fracPad = (frac + '0'.repeat(decimals)).slice(0, decimals);
+ try { return (BigInt(whole || '0') * 10n ** BigInt(decimals) + BigInt(fracPad || '0')).toString(); } catch { return '0'; }
+}
+const newKey = () => (globalThis.crypto?.randomUUID ? globalThis.crypto.randomUUID() : `cop-${Date.now()}-${Math.floor(Math.random() * 1e9)}`);
+
+const SUGGESTIONS = [
+ "How's my portfolio?",
+ 'What are my risk limits?',
+ 'Is this coin safe to buy?',
+];
+
+export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isOwner, getNetwork, onNetworkChange, toast = () => {} }) {
+ injectStyle();
+ let destroyed = false;
+ let detachNet = null;
+ let streaming = false;
+ let recognition = null;
+ let listening = false;
+ let voiceOut = false;
+ let voiceConfig = null; // { provider, voiceId } once loaded
+ let currentAudio = null;
+
+ // Conversation: {role:'user'|'agent', content, tools:[], proposals:[], streaming, error}
+ const messages = [];
+ const actionLog = []; // executed trades/limit changes
+
+ if (!isOwner) {
+ panel.innerHTML = `<div class="awh-card"><div class="awh-cop-intro" role="note"><span aria-hidden="true">🔒</span> The trading copilot is private to <strong>${esc(agentName)}</strong>'s owner — it can read this wallet's positions and place guarded trades from it, so only the owner can talk to it.</div></div>`;
+ return { destroy() {} };
+ }
+
+ panel.innerHTML = `
+ <div class="awh-card awh-cop">
+ <div class="awh-cop-toolbar">
+ <div class="awh-cop-status" data-host="status" role="status" aria-live="polite"></div>
+ <div class="awh-cop-spacer"></div>
+ <button class="awh-cop-iconbtn" type="button" data-act="voiceout" aria-pressed="false" aria-label="Speak replies aloud" title="Speak replies aloud">🔊</button>
+ </div>
+ <div data-host="intro">${introHtml()}</div>
+ <div class="awh-cop-thread" data-host="thread" role="log" aria-live="polite" aria-label="Copilot conversation" tabindex="0"></div>
+ <div data-host="error"></div>
+ <div class="awh-cop-composer">
+ <textarea class="awh-cop-input" data-host="input" rows="1" placeholder="Ask, or say “buy 0.2 SOL of …”" aria-label="Message the trading copilot"></textarea>
+ <button class="awh-cop-iconbtn" type="button" data-act="mic" aria-label="Talk to the copilot" title="Voice input">🎙</button>
+ <button class="awh-cop-iconbtn awh-cop-send" type="button" data-act="send" aria-label="Send message" title="Send">➤</button>
+ </div>
+ <details class="awh-cop-log" data-host="logwrap" hidden>
+ <summary>Executed actions</summary>
+ <ul class="awh-cop-log-list" data-host="loglist"></ul>
+ </details>
+ </div>`;
+
+ const elThread = panel.querySelector('[data-host="thread"]');
+ const elInput = panel.querySelector('[data-host="input"]');
+ const elStatus = panel.querySelector('[data-host="status"]');
+ const elError = panel.querySelector('[data-host="error"]');
+ const elIntro = panel.querySelector('[data-host="intro"]');
+ const elLogWrap = panel.querySelector('[data-host="logwrap"]');
+ const elLogList = panel.querySelector('[data-host="loglist"]');
+
+ function introHtml() {
+ return `<div class="awh-cop-intro">
+ <strong>Talk to ${esc(agentName)} to trade.</strong> Ask about safety, smart money, or your positions — or say “buy 0.25 SOL of &lt;mint&gt;”. Every trade comes back as a card you confirm; it runs through the same spend guards, firewall, and audit as the Trade tab. The copilot never trades on its own.
+ <div class="awh-cop-suggest" data-host="suggest">${SUGGESTIONS.map((s, i) => `<button type="button" data-suggest="${i}">${esc(s)}</button>`).join('')}</div>
+ </div>`;
+ }
+
+ function setStatus(text) { elStatus.textContent = text || ''; }
+
+ function scrollThread() { if (elThread) elThread.scrollTop = elThread.scrollHeight; }
+
+ // ── render ────────────────────────────────────────────────────────────────
+ function render() {
+ if (destroyed) return;
+ elIntro.style.display = messages.length ? 'none' : '';
+ elThread.innerHTML = messages.map(msgHtml).join('');
+ // Mount interactive proposal cards (safety panel + buttons) after innerHTML.
+ messages.forEach((m, mi) => {
+ (m.proposals || []).forEach((p, pi) => {
+ const host = elThread.querySelector(`[data-prop="${mi}-${pi}"]`);
+ if (host) mountProposal(host, p);
+ });
+ });
+ scrollThread();
+ renderLog();
+ }
+
+ function msgHtml(m, i) {
+ if (m.role === 'user') {
+ return `<div class="awh-cop-msg is-user"><div class="awh-cop-bubble">${esc(m.content)}</div></div>`;
+ }
+ const tools = (m.tools || []).length
+ ? `<div class="awh-cop-tools">${m.tools.map((t) => `<span class="awh-cop-tool">${esc(t)}</span>`).join('')}</div>` : '';
+ const body = m.content
+ ? `<div class="awh-cop-bubble">${esc(m.content)}</div>`
+ : m.streaming
+ ? `<div class="awh-cop-bubble is-empty"><span class="awh-cop-typing"><span></span><span></span><span></span></span></div>`
+ : `<div class="awh-cop-bubble is-empty">…</div>`;
+ const props = (m.proposals || []).map((p, pi) => `<div data-prop="${i}-${pi}"></div>`).join('');
+ return `<div class="awh-cop-msg is-agent">
+ <div class="awh-cop-name">${esc(agentName)}</div>
+ ${tools}${body}${props}
+ </div>`;
+ }
+
+ function mountProposal(host, p) {
+ if (p.kind === 'limits') return mountLimitsProposal(host, p);
+ const isBuy = p.kind === 'buy';
+ const q = p.quote && !p.quote.error ? p.quote : null;
+ const impact = q?.price_impact_pct;
+ const impactCls = impact == null ? '' : impact >= 15 ? 'impact-danger' : impact >= 5 ? 'impact-warn' : '';
+ const coinName = p.coin?.symbol || p.coin?.name || short(p.mint, 4, 4);
+ const blocked = p.safety?.verdict === 'block';
+ const wrap = document.createElement('div');
+ wrap.className = 'awh-cop-prop';
+ wrap.innerHTML = `
+ <div class="awh-cop-prop-h"><span class="awh-cop-prop-tag is-${p.kind}">${isBuy ? 'Buy' : 'Sell'}</span> ${esc(coinName)} <span style="color:var(--ink-dim,#888);font-weight:400;font-size:var(--text-sm,.764rem)">${esc(short(p.mint, 4, 4))}</span></div>
+ <dl>
+ <div class="awh-cop-qrow"><dt>${isBuy ? 'You pay' : 'You sell'}</dt><dd class="is-strong">${isBuy ? `◎${fmtSol(p.sol_amount)} SOL` : `${fmtTok(p.token_amount)} ${esc(p.coin?.symbol || 'tokens')}${p.token_pct ? ` (${Math.round(p.token_pct)}%)` : ''}`}</dd></div>
+ <div class="awh-cop-qrow"><dt>Expected ${isBuy ? 'tokens' : 'proceeds'}</dt><dd class="is-strong">${q ? (isBuy ? `${fmtTok(q.expected_out)} ${esc(p.coin?.symbol || '')}` : `◎${fmtSol(q.expected_out)} SOL`) : '—'}</dd></div>
+ <div class="awh-cop-qrow"><dt>Price impact</dt><dd class="${impactCls}">${impact != null ? `${impact.toFixed(2)}%` : (p.quote?.error ? 'unavailable' : '—')}</dd></div>
+ <div class="awh-cop-qrow"><dt>Max slippage</dt><dd>${(p.slippage_bps / 100).toFixed(p.slippage_bps % 100 ? 1 : 0)}%</dd></div>
+ </dl>
+ ${p.rationale ? `<div class="awh-cop-prop-why">“${esc(p.rationale)}”</div>` : ''}
+ <div data-host="safety"></div>
+ ${blocked ? `<div class="awh-cop-prop-blocked"><span aria-hidden="true">⛔</span><span>The firewall blocked this buy${p.safety?.reasons?.[0] ? ` — ${esc(p.safety.reasons[0])}` : ''}. It can't be confirmed.</span></div>` : ''}
+ <div class="awh-cop-prop-actions" data-host="actions"></div>
+ <div data-host="result"></div>`;
+ host.innerHTML = '';
+ host.appendChild(wrap);
+
+ // Firewall verdict (buy only) via the shared safety panel.
+ if (isBuy && p.safety) {
+ const sp = createSafetyPanel({ startExpanded: false });
+ sp.applyVerdict(p.safety);
+ wrap.querySelector('[data-host="safety"]').appendChild(sp.el);
+ p._safetyPanel = sp;
+ }
+
+ const actions = wrap.querySelector('[data-host="actions"]');
+ const result = wrap.querySelector('[data-host="result"]');
+ if (p.executed) {
+ actions.style.display = 'none';
+ renderProposalResult(result, p);
+ return;
+ }
+ if (blocked) { actions.style.display = 'none'; return; }
+ actions.innerHTML = `
+ <button class="awh-cop-prop-cancel" type="button" data-pa="cancel">Cancel</button>
+ <button class="awh-cop-prop-confirm is-${p.kind}" type="button" data-pa="confirm">Confirm ${isBuy ? 'buy' : 'sell'}</button>`;
+ actions.querySelector('[data-pa="cancel"]').addEventListener('click', () => {
+ p.cancelled = true; actions.style.display = 'none';
+ result.innerHTML = `<div class="awh-cop-prop-result">Cancelled — nothing was sent.</div>`;
+ });
+ actions.querySelector('[data-pa="confirm"]').addEventListener('click', () => confirmTrade(p, actions, result));
+ }
+
+ function mountLimitsProposal(host, p) {
+ const labels = { per_trade_sol: 'Per-trade cap', daily_budget_sol: 'Daily budget', max_price_impact_pct: 'Max price impact', kill_switch: 'Kill switch (halt trading)' };
+ const fmt = (k, v) => k === 'kill_switch' ? (v ? 'ON' : 'off') : k === 'max_price_impact_pct' ? `${v}%` : `${v} SOL`;
+ const rows = Object.entries(p.changes).map(([k, v]) => `<div class="awh-cop-qrow"><dt>${esc(labels[k] || k)}</dt><dd class="is-strong">${esc(fmt(k, v))}</dd></div>`).join('');
+ const wrap = document.createElement('div');
+ wrap.className = 'awh-cop-prop';
+ wrap.innerHTML = `
+ <div class="awh-cop-prop-h"><span class="awh-cop-prop-tag is-limits">Risk limits</span> Update guardrails</div>
+ <dl>${rows}</dl>
+ ${p.rationale ? `<div class="awh-cop-prop-why">“${esc(p.rationale)}”</div>` : ''}
+ <div class="awh-cop-prop-actions" data-host="actions"></div>
+ <div data-host="result"></div>`;
+ host.innerHTML = '';
+ host.appendChild(wrap);
+ const actions = wrap.querySelector('[data-host="actions"]');
+ const result = wrap.querySelector('[data-host="result"]');
+ if (p.executed) { actions.style.display = 'none'; renderProposalResult(result, p); return; }
+ actions.innerHTML = `
+ <button class="awh-cop-prop-cancel" type="button" data-pa="cancel">Cancel</button>
+ <button class="awh-cop-prop-confirm is-limits" type="button" data-pa="confirm">Apply limits</button>`;
+ actions.querySelector('[data-pa="cancel"]').addEventListener('click', () => {
+ p.cancelled = true; actions.style.display = 'none';
+ result.innerHTML = `<div class="awh-cop-prop-result">Cancelled — limits unchanged.</div>`;
+ });
+ actions.querySelector('[data-pa="confirm"]').addEventListener('click', () => confirmLimits(p, actions, result));
+ }
+
+ function renderProposalResult(result, p) {
+ if (p.error) { result.innerHTML = `<div class="awh-cop-prop-result is-err"><span aria-hidden="true">⚠</span><span>${esc(p.error)}</span></div>`; return; }
+ const link = p.signature ? ` <a href="${esc(explorerTxUrl(p.signature, p.network))}" target="_blank" rel="noopener">View on Solscan ↗</a>` : '';
+ result.innerHTML = `<div class="awh-cop-prop-result is-ok"><span aria-hidden="true">✓</span><span>${esc(p.successText || 'Done.')}${link}</span></div>`;
+ }
+
+ // ── confirm → guarded execution ─────────────────────────────────────────────
+ async function confirmTrade(p, actions, result) {
+ const btn = actions.querySelector('[data-pa="confirm"]');
+ btn.disabled = true; btn.textContent = 'Submitting…';
+ actions.querySelector('[data-pa="cancel"]').disabled = true;
+ try {
+ const network = p.network || getNetwork();
+ const args = p.kind === 'buy'
+ ? { agentId, side: 'buy', mint: p.mint, solAmount: p.sol_amount, slippageBps: p.slippage_bps, network, idempotencyKey: newKey() }
+ : { agentId, side: 'sell', mint: p.mint, tokenAmountRaw: uiToRaw(p.token_amount, p.decimals ?? 6), slippageBps: p.slippage_bps, network, idempotencyKey: newKey() };
+ const data = await executeAgentTrade(args);
+ p.executed = true;
+ p.signature = data?.signature || null;
+ p.network = network;
+ if (p.kind === 'buy') p.successText = `Bought ${fmtTok(data?.out?.amount)} ${p.coin?.symbol || 'tokens'} for ◎${fmtSol(data?.in?.amount ?? p.sol_amount)} SOL.`;
+ else p.successText = `Sold ${p.coin?.symbol || 'tokens'} for ◎${fmtSol(data?.out?.amount)} SOL.`;
+ actions.style.display = 'none';
+ renderProposalResult(result, p);
+ logAction({ kind: p.kind, coin: p.coin?.symbol || short(p.mint, 4, 4), mint: p.mint, text: p.successText, signature: p.signature, network });
+ toast(p.kind === 'buy' ? 'Buy confirmed' : 'Sell confirmed');
+ } catch (e) {
+ const msg = e instanceof TradeError ? e.message : (e?.message || 'The trade could not be completed.');
+ p.error = msg;
+ renderProposalResult(result, p);
+ btn.disabled = false; btn.textContent = `Confirm ${p.kind === 'buy' ? 'buy' : 'sell'}`;
+ actions.querySelector('[data-pa="cancel"]').disabled = false;
+ }
+ }
+
+ async function confirmLimits(p, actions, result) {
+ const btn = actions.querySelector('[data-pa="confirm"]');
+ btn.disabled = true; btn.textContent = 'Applying…';
+ actions.querySelector('[data-pa="cancel"]').disabled = true;
+ try {
+ // Send only the changed keys — setTradeLimits patches by key and
+ // preserves the rest, so we never echo server-managed fields back.
+ const headers = { 'Content-Type': 'application/json' };
+ const token = await consumeCsrfToken();
+ if (token) headers['x-csrf-token'] = token;
+ const resp = await fetch(`/api/agents/${encodeURIComponent(agentId)}/trade/limits`, {
+ method: 'PUT', credentials: 'include', headers, body: JSON.stringify(p.changes),
+ });
+ const j = await resp.json().catch(() => ({}));
+ if (!resp.ok) throw new Error(j?.error_description || j?.error?.message || `Couldn't update limits (${resp.status})`);
+ p.executed = true;
+ p.successText = 'Risk limits updated.';
+ actions.style.display = 'none';
+ renderProposalResult(result, p);
+ logAction({ kind: 'limits', text: describeLimits(p.changes) });
+ toast('Limits updated');
+ } catch (e) {
+ p.error = e?.message || 'Could not update limits.';
+ renderProposalResult(result, p);
+ btn.disabled = false; btn.textContent = 'Apply limits';
+ actions.querySelector('[data-pa="cancel"]').disabled = false;
+ }
+ }
+
+ function describeLimits(changes) {
+ const parts = [];
+ if (changes.kill_switch != null) parts.push(`kill switch ${changes.kill_switch ? 'ON' : 'off'}`);
+ if (changes.per_trade_sol != null) parts.push(`per-trade ${changes.per_trade_sol} SOL`);
+ if (changes.daily_budget_sol != null) parts.push(`daily ${changes.daily_budget_sol} SOL`);
+ if (changes.max_price_impact_pct != null) parts.push(`max impact ${changes.max_price_impact_pct}%`);
+ return `Limits: ${parts.join(', ')}`;
+ }
+
+ function logAction(entry) {
+ actionLog.unshift({ ...entry, at: Date.now() });
+ renderLog();
+ }
+ function renderLog() {
+ if (!actionLog.length) { elLogWrap.hidden = true; return; }
+ elLogWrap.hidden = false;
+ elLogList.innerHTML = actionLog.map((a) => {
+ const sideCls = a.kind === 'buy' ? 'is-buy' : a.kind === 'sell' ? 'is-sell' : 'is-limits';
+ const label = a.kind === 'buy' ? 'Buy' : a.kind === 'sell' ? 'Sell' : 'Limits';
+ const main = a.signature
+ ? `${esc(a.text)} <a href="${esc(explorerTxUrl(a.signature, a.network))}" target="_blank" rel="noopener">↗</a>`
+ : esc(a.text);
+ return `<li class="awh-cop-log-row"><span class="awh-cop-log-side ${sideCls}">${label}</span><span class="awh-cop-log-main">${main}</span></li>`;
+ }).join('');
+ }
+
+ // ── conversation turn (SSE) ─────────────────────────────────────────────────
+ async function sendMessage(text) {
+ const content = (text ?? elInput.value).trim();
+ if (!content || streaming) return;
+ stopSpeaking();
+ elInput.value = '';
+ autoSize();
+ elError.innerHTML = '';
+ messages.push({ role: 'user', content });
+ const agentMsg = { role: 'agent', content: '', tools: [], proposals: [], streaming: true };
+ messages.push(agentMsg);
+ streaming = true;
+ setStatus('Thinking…');
+ render();
+
+ const payload = {
+ network: getNetwork(),
+ messages: messages
+ .filter((m) => !(m.role === 'agent' && m.streaming && !m.content))
+ .map((m) => ({ role: m.role === 'agent' ? 'assistant' : 'user', content: m.content }))
+ .filter((m) => m.content),
+ };
+
+ try {
+ const resp = await fetch(`/api/agents/${encodeURIComponent(agentId)}/copilot`, {
+ method: 'POST', credentials: 'include',
+ headers: { 'Content-Type': 'application/json', accept: 'text/event-stream' },
+ body: JSON.stringify(payload),
+ });
+ if (!resp.ok || !resp.body) {
+ const j = await resp.json().catch(() => ({}));
+ throw new Error(j?.error_description || j?.error?.message || j?.message || `Copilot unavailable (${resp.status})`);
+ }
+ await consumeSse(resp.body, agentMsg);
+ } catch (e) {
+ agentMsg.streaming = false;
+ if (!agentMsg.content) agentMsg.error = true;
+ showError(e?.message || 'The copilot hit an error.', content);
+ } finally {
+ streaming = false;
+ agentMsg.streaming = false;
+ setStatus('');
+ render();
+ if (voiceOut && agentMsg.content && !agentMsg.error) speak(agentMsg.content);
+ }
+ }
+
+ async function consumeSse(stream, agentMsg) {
+ const reader = stream.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ if (destroyed) { reader.cancel().catch(() => {}); break; }
+ buf += decoder.decode(value, { stream: true });
+ let sep;
+ while ((sep = buf.indexOf('\n\n')) >= 0) {
+ const block = buf.slice(0, sep);
+ buf = buf.slice(sep + 2);
+ let event = 'message', data = '';
+ for (const line of block.split('\n')) {
+ if (line.startsWith('event:')) event = line.slice(6).trim();
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
+ }
+ if (!data) continue;
+ let payload;
+ try { payload = JSON.parse(data); } catch { continue; }
+ handleSseEvent(event, payload, agentMsg);
+ }
+ }
+ }
+
+ function handleSseEvent(event, payload, agentMsg) {
+ if (event === 'status') {
+ setStatus(payload.phase === 'finalizing' ? 'Summarizing…' : payload.phase === 'continuing' ? 'Analyzing…' : 'Thinking…');
+ } else if (event === 'tool') {
+ agentMsg.tools.push(payload.summary || payload.name);
+ setStatus(payload.summary || 'Reading live data…');
+ render();
+ } else if (event === 'proposal') {
+ agentMsg.proposals.push(normalizeProposal(payload));
+ render();
+ } else if (event === 'chunk') {
+ agentMsg.content += payload.text || '';
+ render();
+ } else if (event === 'done') {
+ agentMsg.streaming = false;
+ if (payload.reply && !agentMsg.content) agentMsg.content = payload.reply;
+ render();
+ } else if (event === 'error') {
+ agentMsg.streaming = false;
+ if (!agentMsg.content) { agentMsg.error = true; showError(payload.message || 'Copilot error', null); }
+ }
+ }
+
+ function normalizeProposal(p) {
+ return { ...p }; // already structured by the server; cards read fields directly
+ }
+
+ function showError(msg, retryText) {
+ elError.innerHTML = `<div class="awh-cop-error" role="alert"><span aria-hidden="true">⚠</span><span>${esc(msg)}</span>${retryText ? ' <button type="button" data-act="retry">Retry</button>' : ''}</div>`;
+ const r = elError.querySelector('[data-act="retry"]');
+ if (r) r.addEventListener('click', () => { elError.innerHTML = ''; sendMessage(retryText); });
+ }
+
+ // ── voice in (SpeechRecognition) ────────────────────────────────────────────
+ function micSupported() { return typeof window !== 'undefined' && (window.SpeechRecognition || window.webkitSpeechRecognition); }
+ function toggleMic() {
+ if (!micSupported()) { toast('Voice input is not supported in this browser.'); return; }
+ if (listening) { stopListening(); return; }
+ const Rec = window.SpeechRecognition || window.webkitSpeechRecognition;
+ recognition = new Rec();
+ recognition.lang = navigator.language || 'en-US';
+ recognition.interimResults = true;
+ recognition.continuous = false;
+ let finalText = '';
+ recognition.onresult = (e) => {
+ let interim = '';
+ for (let i = e.resultIndex; i < e.results.length; i++) {
+ const tr = e.results[i][0].transcript;
+ if (e.results[i].isFinal) finalText += tr; else interim += tr;
+ }
+ elInput.value = (finalText + interim).trim();
+ autoSize();
+ };
+ recognition.onerror = () => { stopListening(); };
+ recognition.onend = () => {
+ const had = listening;
+ stopListening();
+ if (had && elInput.value.trim()) sendMessage();
+ };
+ try { recognition.start(); listening = true; updateMic(); setStatus('Listening…'); }
+ catch { stopListening(); }
+ }
+ function stopListening() {
+ listening = false;
+ try { recognition?.stop(); } catch { /* already stopped */ }
+ recognition = null;
+ updateMic();
+ if (!streaming) setStatus('');
+ }
+ function updateMic() {
+ const mic = panel.querySelector('[data-act="mic"]');
+ if (!mic) return;
+ mic.classList.toggle('is-listening', listening);
+ mic.setAttribute('aria-label', listening ? 'Stop listening' : 'Talk to the copilot');
+ }
+
+ // ── voice out (agent voice → TTS, browser fallback) ─────────────────────────
+ async function ensureVoiceConfig() {
+ if (voiceConfig !== null) return voiceConfig;
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/voice`, { credentials: 'include' });
+ if (r.ok) {
+ const j = await r.json();
+ const d = j?.data || j;
+ voiceConfig = { provider: d?.voice_provider || 'browser', voiceId: d?.voice_id || null };
+ } else voiceConfig = { provider: 'browser', voiceId: null };
+ } catch { voiceConfig = { provider: 'browser', voiceId: null }; }
+ return voiceConfig;
+ }
+ function stopSpeaking() {
+ if (currentAudio) { try { currentAudio.pause(); } catch { /* noop */ } currentAudio = null; }
+ if (typeof window !== 'undefined' && window.speechSynthesis) window.speechSynthesis.cancel();
+ }
+ async function speak(text) {
+ stopSpeaking();
+ const clean = text.replace(/\s+/g, ' ').trim().slice(0, 1200);
+ if (!clean) return;
+ const cfg = await ensureVoiceConfig();
+ // Real server TTS first (agent's cloned voice if any), browser fallback.
+ try {
+ let resp;
+ if (cfg.provider === 'elevenlabs' && cfg.voiceId) {
+ resp = await fetch('/api/tts/eleven', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ voiceId: cfg.voiceId, text: clean }) });
+ } else {
+ resp = await fetch('/api/tts/speak', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: clean, format: 'mp3' }) });
+ }
+ if (resp.ok) {
+ const blob = await resp.blob();
+ const url = URL.createObjectURL(blob);
+ const audio = new Audio(url);
+ currentAudio = audio;
+ audio.onended = () => { URL.revokeObjectURL(url); if (currentAudio === audio) currentAudio = null; };
+ await audio.play();
+ return;
+ }
+ } catch { /* fall through to browser speech */ }
+ if (typeof window !== 'undefined' && window.speechSynthesis) {
+ const u = new SpeechSynthesisUtterance(clean);
+ window.speechSynthesis.speak(u);
+ }
+ }
+ function toggleVoiceOut() {
+ voiceOut = !voiceOut;
+ const b = panel.querySelector('[data-act="voiceout"]');
+ if (b) b.setAttribute('aria-pressed', String(voiceOut));
+ if (voiceOut) ensureVoiceConfig(); else stopSpeaking();
+ toast(voiceOut ? 'Replies will be spoken' : 'Voice replies off');
+ }
+
+ // ── composer + events ───────────────────────────────────────────────────────
+ function autoSize() {
+ elInput.style.height = 'auto';
+ elInput.style.height = `${Math.min(120, elInput.scrollHeight)}px`;
+ }
+ // The intro (with its suggestion chips) is rendered once and only toggled
+ // hidden, so its buttons are bound a single time at mount — never per render.
+ function wireIntroEvents() {
+ panel.querySelectorAll('[data-suggest]').forEach((b) => b.addEventListener('click', () => sendMessage(SUGGESTIONS[Number(b.dataset.suggest)])));
+ }
+
+ panel.querySelector('[data-act="send"]').addEventListener('click', () => sendMessage());
+ panel.querySelector('[data-act="mic"]').addEventListener('click', toggleMic);
+ panel.querySelector('[data-act="voiceout"]').addEventListener('click', toggleVoiceOut);
+ if (!micSupported()) {
+ const mic = panel.querySelector('[data-act="mic"]');
+ mic.disabled = true; mic.title = 'Voice input not supported in this browser';
+ }
+ elInput.addEventListener('input', autoSize);
+ elInput.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
+ });
+
+ wireIntroEvents();
+
+ if (onNetworkChange) {
+ detachNet = onNetworkChange(() => { /* network is read live per turn; nothing to reset */ });
+ }
+
+ return {
+ onShow() { elInput?.focus(); },
+ onHide() { stopListening(); stopSpeaking(); },
+ destroy() {
+ destroyed = true;
+ stopListening();
+ stopSpeaking();
+ messages.forEach((m) => (m.proposals || []).forEach((p) => p._safetyPanel?.destroy?.()));
+ detachNet?.();
+ },
+ };
+}
diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.js
index a9899323f..d006a0f7b 100644
--- a/src/agent-wallet-hub/index.js
+++ b/src/agent-wallet-hub/index.js
@@ -22,14 +22,18 @@ import { getVisibleTabs } from './registry.js';
// Tab modules — importing each one runs its registerWalletTab() side effect.
// To add a tab later: drop a file in ./tabs/ and add one import line here.
import './tabs/balance.js';
+import './tabs/portfolio.js';
import './tabs/pulse.js';
import './tabs/reputation.js';
import './tabs/deposit.js';
import './tabs/trade.js';
+import './tabs/copilot.js';
import './tabs/snipe.js';
+import './tabs/orders.js';
import './tabs/earn.js';
import './tabs/autopilot.js';
import './tabs/intents.js';
+import './tabs/signals.js';
import './tabs/pay.js';
import './tabs/vanity.js';
import './tabs/withdraw.js';
diff --git a/src/agent-wallet-hub/tabs/copilot.js b/src/agent-wallet-hub/tabs/copilot.js
new file mode 100644
index 000000000..69cbbc280
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/copilot.js
@@ -0,0 +1,38 @@
+/**
+ * Agent Wallet hub — Copilot tab (trading-frontier task 01).
+ *
+ * The Conversational Trading Copilot: the owner talks (text or voice) to the
+ * agent and it answers with REAL live data and proposes guarded trades to
+ * confirm. All logic lives in src/agent-copilot.js (reusable so agent-detail can
+ * mount the same copilot); this tab is the thin wallet-hub wrapper that wires it
+ * to the shared hub context (agent id, owner flag, network, toast).
+ *
+ * Owner-only: the copilot reads this wallet's positions and can place guarded
+ * trades from it, so a visitor never sees it.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { mountTradingCopilot } from '../../agent-copilot.js';
+
+registerWalletTab({
+ id: 'copilot',
+ label: 'Copilot',
+ order: 25, // sits beside Trade (30) — talk, or trade by hand
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ const handle = mountTradingCopilot({
+ panel,
+ agentId: ctx.agentId,
+ agentName: ctx.agent?.name || 'Copilot',
+ isOwner: ctx.isOwner,
+ getNetwork: ctx.getNetwork,
+ onNetworkChange: ctx.onNetworkChange,
+ toast: ctx.toast,
+ });
+ return {
+ onShow() { handle.onShow?.(); },
+ onHide() { handle.onHide?.(); },
+ destroy() { handle.destroy?.(); },
+ };
+ },
+});
diff --git a/src/agent-wallet-hub/tabs/orders.js b/src/agent-wallet-hub/tabs/orders.js
new file mode 100644
index 000000000..bbd37610a
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/orders.js
@@ -0,0 +1,533 @@
+/**
+ * Agent Wallet hub — Programmable Orders tab (trading-frontier/02).
+ *
+ * Owner-only. Set-and-forget order tooling pump.fun never had: limit, stop,
+ * trailing stop, DCA, TWAP, and validated conditional triggers ("buy when
+ * smart-money > 60 and mcap < $40k", "sell if the dev dumps"). A worker
+ * (workers/agent-orders) watches live on-chain state and fires matched orders
+ * from the agent's own wallet through the SAME firewall + spend-guard + custody
+ * pipeline as every manual trade — so an order can never exceed the daily budget
+ * or per-trade cap, the kill switch halts everything, and cancel is instant.
+ *
+ * The create form previews the live fill condition + the rug/honeypot firewall
+ * verdict before you arm. Open orders stream their status live; fills show real
+ * signatures linked to the explorer.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { formatSol, formatUsd, explorerTxUrl } from '../util.js';
+import { consumeCsrfToken } from '../../api.js';
+
+const STYLE_ID = 'awh-orders-style';
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+const TYPE_META = {
+ limit: { icon: '🎯', label: 'Limit', blurb: 'Fill at a target price/market-cap.' },
+ stop: { icon: '🛑', label: 'Stop', blurb: 'Stop-loss on a fall, or breakout on a rise.' },
+ trailing: { icon: '📉', label: 'Trailing', blurb: 'Sell after a % drop from the high.' },
+ dca: { icon: '🪙', label: 'DCA', blurb: 'Recurring buys/sells on an interval.' },
+ twap: { icon: '🧊', label: 'TWAP', blurb: 'Slice one big order to cut price impact.' },
+ conditional: { icon: '🧠', label: 'Conditional', blurb: 'Fire on live signals.' },
+};
+const METRIC_LABEL = { mcap_usd: 'Market cap (USD)', mcap_sol: 'Market cap (SOL)', price_sol: 'Price (SOL/token)' };
+const OPEN_STATUSES = ['active', 'partial', 'firing', 'paused'];
+const STATUS_TONE = { active: 'ok', partial: 'ok', firing: 'warn', filled: 'ok', cancelled: 'muted', expired: 'muted', error: 'bad', paused: 'warn' };
+
+const STYLE = `
+.aord { display:flex; flex-direction:column; gap: var(--space-lg,1.618rem); }
+.aord-hero { background: linear-gradient(160deg, var(--wallet-accent-soft,rgba(139,92,246,.1)), var(--surface-1,rgba(255,255,255,.03))); border:1px solid var(--wallet-stroke,rgba(139,92,246,.3)); border-radius: var(--radius-lg,14px); padding: var(--space-lg,18px); position:relative; overflow:hidden; }
+.aord-hero-top { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; }
+.aord-title { font-family: var(--font-display,'Space Grotesk',sans-serif); font-size: var(--text-lg,1.18rem); font-weight:600; color: var(--ink-bright,#fff); margin:0; }
+.aord-title small { display:block; font-family: var(--font-body,Inter,sans-serif); font-size: var(--text-sm,.764rem); font-weight:400; color: var(--ink-dim,#888); margin-top:3px; }
+.aord-stats { display:flex; gap:8px; flex-wrap:wrap; margin-top: var(--space-md,14px); }
+.aord-stat { background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding:9px 12px; min-width:92px; }
+.aord-stat .l { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); text-transform:uppercase; letter-spacing:.03em; }
+.aord-stat .n { font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); margin-top:3px; }
+.aord-banner { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-top: var(--space-md,14px); padding:10px 13px; border-radius: var(--radius-md,10px); border:1px solid color-mix(in srgb, var(--danger,#f87171) 35%, transparent); background: color-mix(in srgb, var(--danger,#f87171) 8%, transparent); color: var(--danger,#f87171); font-size: var(--text-sm,.764rem); }
+
+.aord-card { background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-lg,14px); padding: var(--space-lg,18px); }
+.aord-card h3 { margin:0 0 4px; font-size: var(--text-ui,.875rem); color: var(--ink-bright,#fff); font-weight:600; display:flex; align-items:center; gap:8px; }
+.aord-card .sub { margin:0 0 var(--space-md,14px); font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }
+
+.aord-types { display:grid; grid-template-columns: repeat(auto-fit, minmax(118px,1fr)); gap:8px; margin-bottom: var(--space-md,14px); }
+.aord-type { appearance:none; text-align:left; font:inherit; cursor:pointer; padding:10px 11px; border-radius: var(--radius-md,10px); border:1px solid var(--stroke,rgba(255,255,255,.1)); background: var(--surface-1,rgba(255,255,255,.03)); color: var(--ink,#e8e8e8); transition: border-color var(--duration-fast,140ms), background var(--duration-fast,140ms); }
+.aord-type:hover { border-color: var(--wallet-stroke,rgba(139,92,246,.3)); }
+.aord-type[aria-pressed="true"] { border-color: var(--wallet-stroke-strong,rgba(139,92,246,.5)); background: var(--wallet-accent-soft,rgba(139,92,246,.1)); }
+.aord-type .t { font-weight:600; font-size: var(--text-md,.8125rem); display:flex; align-items:center; gap:6px; }
+.aord-type .b { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); margin-top:3px; line-height:1.35; }
+
+.aord-field { margin-bottom:11px; }
+.aord-field label { display:block; font-size: var(--text-2xs,.6875rem); text-transform:uppercase; letter-spacing:.04em; color: var(--ink-dim,#888); margin-bottom:5px; }
+.aord-input, .aord-select { width:100%; box-sizing:border-box; font:inherit; font-size: var(--text-md,.8125rem); color: var(--ink,#e8e8e8); background: var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:9px 12px; transition: border-color var(--duration-fast,140ms); }
+.aord-input:focus, .aord-select:focus { outline:none; border-color: var(--wallet-stroke-strong,rgba(139,92,246,.5)); }
+.aord-row { display:flex; gap:10px; flex-wrap:wrap; }
+.aord-row > .aord-field { flex:1; min-width:120px; }
+.aord-seg { display:inline-flex; border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); overflow:hidden; }
+.aord-seg button { appearance:none; font:inherit; font-size: var(--text-sm,.764rem); cursor:pointer; padding:8px 16px; border:none; background:transparent; color: var(--ink-dim,#aaa); transition: background var(--duration-fast,140ms), color var(--duration-fast,140ms); }
+.aord-seg button[aria-pressed="true"] { background: var(--wallet-accent,#c4b5fd); color:#160d28; font-weight:600; }
+
+.aord-cond { border:1px dashed var(--stroke,rgba(255,255,255,.14)); border-radius: var(--radius-md,10px); padding:11px; margin-bottom:11px; }
+.aord-cond-mode { display:flex; gap:8px; align-items:center; margin-bottom:9px; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#aaa); }
+.aord-clause { display:flex; gap:7px; align-items:center; margin-bottom:7px; flex-wrap:wrap; }
+.aord-clause .aord-select, .aord-clause .aord-input { width:auto; flex:1; min-width:90px; }
+.aord-clause .x { appearance:none; cursor:pointer; border:1px solid var(--stroke,rgba(255,255,255,.12)); background:transparent; color: var(--ink-dim,#888); border-radius: var(--radius-sm,6px); width:30px; height:30px; flex:none; }
+.aord-clause .x:hover { color: var(--danger,#f87171); border-color: color-mix(in srgb,var(--danger,#f87171) 40%,transparent); }
+
+.aord-btn { appearance:none; font:inherit; font-size: var(--text-sm,.764rem); font-weight:600; cursor:pointer; border-radius: var(--radius-md,10px); padding:9px 16px; border:1px solid var(--stroke-strong,rgba(255,255,255,.14)); background: var(--surface-2,rgba(255,255,255,.06)); color: var(--ink,#e8e8e8); transition: background var(--duration-fast,140ms), border-color var(--duration-fast,140ms), transform var(--duration-fast,140ms); }
+.aord-btn:hover:not(:disabled) { background: var(--surface-3,rgba(255,255,255,.09)); color: var(--ink-bright,#fff); }
+.aord-btn:active:not(:disabled) { transform: translateY(1px); }
+.aord-btn:disabled { opacity:.5; cursor:not-allowed; }
+.aord-btn:focus-visible { outline:2px solid var(--wallet-focus,rgba(139,92,246,.7)); outline-offset:2px; }
+.aord-btn.primary { background: var(--wallet-accent,#c4b5fd); border-color: var(--wallet-accent,#c4b5fd); color:#160d28; }
+.aord-btn.primary:hover:not(:disabled) { background: var(--wallet-accent-strong,#a78bfa); border-color: var(--wallet-accent-strong,#a78bfa); }
+.aord-btn.ghost { background:transparent; }
+.aord-btn.danger { color: var(--danger,#f87171); border-color: color-mix(in srgb, var(--danger,#f87171) 40%, transparent); background: color-mix(in srgb, var(--danger,#f87171) 8%, transparent); }
+.aord-btn.danger:hover:not(:disabled) { background: color-mix(in srgb, var(--danger,#f87171) 16%, transparent); color:#fff; }
+.aord-btn.sm { padding:6px 11px; font-size: var(--text-2xs,.6875rem); }
+.aord-actions { display:flex; gap:8px; flex-wrap:wrap; margin-top: var(--space-md,13px); }
+
+.aord-prev { margin-top:12px; padding:11px 13px; border-radius: var(--radius-md,10px); background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.08)); }
+.aord-prev .rb { font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); line-height:1.5; margin-bottom:8px; }
+.aord-prev .ln { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#aaa); margin:3px 0; display:flex; gap:7px; align-items:center; }
+.aord-fw { display:inline-block; font-size: var(--text-2xs,.6875rem); padding:2px 9px; border-radius: var(--radius-pill,999px); border:1px solid currentColor; }
+.aord-fw.allow { color: var(--success,#4ade80); } .aord-fw.warn { color: var(--warn,#fbbf24); } .aord-fw.block { color: var(--danger,#f87171); }
+
+.aord-list { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:9px; }
+.aord-item { border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-md,11px); background: var(--surface-1,rgba(255,255,255,.03)); padding:12px 13px; transition: border-color var(--duration-fast,140ms); }
+.aord-item:hover { border-color: var(--wallet-stroke,rgba(139,92,246,.28)); }
+.aord-item-top { display:flex; gap:11px; align-items:flex-start; }
+.aord-item-ic { font-size:18px; line-height:1.2; flex:none; }
+.aord-item-body { flex:1; min-width:0; }
+.aord-item-ttl { font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); font-weight:600; }
+.aord-item-desc { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#999); margin-top:3px; line-height:1.45; }
+.aord-item-foot { display:flex; flex-wrap:wrap; gap:8px; align-items:center; margin-top:8px; font-size: var(--text-2xs,.6875rem); color: var(--ink-faint,rgba(255,255,255,.5)); }
+.aord-item-foot a { color: var(--wallet-accent,#c4b5fd); text-decoration:none; border-bottom:1px dotted currentColor; }
+.aord-pill { font-size: var(--text-2xs,.6875rem); padding:2px 9px; border-radius: var(--radius-pill,999px); border:1px solid currentColor; text-transform:capitalize; }
+.aord-pill.ok { color: var(--success,#4ade80); } .aord-pill.warn { color: var(--warn,#fbbf24); } .aord-pill.bad { color: var(--danger,#f87171); } .aord-pill.muted { color: var(--ink-dim,#888); }
+.aord-prog { height:5px; border-radius:999px; background: var(--surface-3,rgba(255,255,255,.1)); margin-top:8px; overflow:hidden; }
+.aord-prog > i { display:block; height:100%; background: var(--wallet-accent,#c4b5fd); transition: width var(--duration-base,220ms); }
+.aord-item-ctl { display:flex; gap:6px; flex-wrap:wrap; margin-top:10px; }
+
+.aord-empty { text-align:center; padding: var(--space-lg,18px) var(--space-md,14px); color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); }
+.aord-empty .ic { font-size:30px; margin-bottom:8px; }
+.aord-skel { height:14px; border-radius:6px; background: var(--surface-2,rgba(255,255,255,.05)); animation: aord-sk 1.4s ease-in-out infinite; margin:10px 0; }
+.aord-spin { display:inline-block; width:13px; height:13px; border:2px solid rgba(0,0,0,.25); border-top-color: currentColor; border-radius:50%; animation: aord-rot .7s linear infinite; vertical-align:-2px; margin-right:6px; }
+.aord-err { background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); border:1px solid color-mix(in srgb, var(--danger,#f87171) 32%, transparent); color: var(--danger,#f87171); border-radius: var(--radius-md,10px); padding:10px 12px; font-size: var(--text-sm,.764rem); }
+.aord-live { font-size: var(--text-2xs,.6875rem); color: var(--success,#4ade80); display:inline-flex; align-items:center; gap:5px; }
+.aord-live .dot { width:7px; height:7px; border-radius:50%; background: var(--success,#4ade80); animation: aord-pulse 1.8s ease-in-out infinite; }
+@keyframes aord-rot { to { transform: rotate(360deg); } }
+@keyframes aord-sk { 0%,100%{opacity:.4} 50%{opacity:.8} }
+@keyframes aord-pulse { 0%,100%{opacity:1} 50%{opacity:.3} }
+@media (prefers-reduced-motion: reduce) { .aord-skel,.aord-spin,.aord-live .dot,.aord-prog > i { animation:none; transition:none; } }
+`;
+
+function injectStyle() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = STYLE_ID;
+ tag.textContent = STYLE;
+ document.head.appendChild(tag);
+}
+
+function esc(s) {
+ return String(s ?? '').replace(/[<>&"']/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+async function call(url, { method = 'GET', body = null } = {}) {
+ try {
+ const opts = { method, credentials: 'include', headers: {} };
+ if (body != null) { opts.headers['content-type'] = 'application/json'; opts.body = JSON.stringify(body); }
+ if (method !== 'GET') { const token = await consumeCsrfToken(); if (token) opts.headers['x-csrf-token'] = token; }
+ const r = await fetch(url, opts);
+ let j = null; try { j = await r.json(); } catch { /* */ }
+ if (!r.ok) return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, data: j?.data ?? null };
+ return { ok: true, status: r.status, data: j?.data ?? j };
+ } catch (err) {
+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };
+ }
+}
+
+function freshForm() {
+ return {
+ type: 'limit', side: 'buy', mint: '', trigger_metric: 'mcap_usd',
+ limit_price: '', stop_price: '', trail_pct: '25',
+ size_sol: '0.1', sell_pct: '100', size_tokens: '',
+ total_sol: '1', total_pct: '100',
+ interval: '3600', slices: '6', slippage_bps: '500', expires_at: '',
+ condition_mode: 'all',
+ clauses: [{ signal: 'smart_money_score', op: 'gte', value: '60' }],
+ };
+}
+
+registerWalletTab({
+ id: 'orders',
+ label: 'Orders',
+ order: 46,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ const base = (sub = '') => `/api/agents/${ctx.agentId}/orders${sub ? '/' + sub : ''}?network=${ctx.getNetwork()}`;
+
+ let destroyed = false;
+ let es = null;
+ const state = {
+ loading: true, error: null,
+ orders: [], summary: null, schema: null,
+ form: freshForm(), preview: null, previewing: false, creating: false,
+ live: false,
+ };
+
+ async function load() {
+ state.loading = true; render();
+ const [res, schemaRes] = await Promise.all([call(base()), state.schema ? Promise.resolve(null) : call(base('schema'))]);
+ if (destroyed) return;
+ state.loading = false;
+ if (schemaRes && schemaRes.ok) state.schema = schemaRes.data;
+ if (!res.ok) { state.error = res.message; }
+ else { state.error = null; state.orders = res.data.orders || []; state.summary = res.data.summary || null; }
+ render();
+ subscribeLive();
+ }
+
+ // Live order status over SSE; gracefully no-ops if EventSource is missing.
+ function subscribeLive() {
+ if (destroyed || es || typeof EventSource === 'undefined') return;
+ try {
+ es = new EventSource(base('stream'), { withCredentials: true });
+ es.addEventListener('orders', (e) => {
+ try { const d = JSON.parse(e.data); state.orders = d.orders || state.orders; state.summary = d.summary || state.summary; state.live = true; renderListsOnly(); } catch { /* */ }
+ });
+ es.addEventListener('open', () => { state.live = true; });
+ es.onerror = () => { state.live = false; if (es && es.readyState === EventSource.CLOSED) { es = null; } renderLiveBadge(); };
+ } catch { es = null; }
+ }
+
+ // ── renderers ───────────────────────────────────────────────────────────
+ function render() {
+ if (destroyed) return;
+ if (state.loading) {
+ panel.innerHTML = `<div class="aord"><div class="aord-card"><div class="aord-skel" style="width:42%"></div><div class="aord-skel"></div><div class="aord-skel" style="width:70%"></div></div></div>`;
+ return;
+ }
+ if (state.error) {
+ panel.innerHTML = `<div class="aord"><div class="aord-err">Couldn’t load your orders: ${esc(state.error)}</div><div class="aord-actions"><button class="aord-btn" id="aord-retry">Retry</button></div></div>`;
+ panel.querySelector('#aord-retry')?.addEventListener('click', load);
+ return;
+ }
+ panel.innerHTML = `<div class="aord">${renderHero()}${renderForm()}${renderOpen()}${renderHistory()}</div>`;
+ wire();
+ }
+
+ // Re-render only the dynamic lists (used by the live stream so the form keeps focus).
+ function renderListsOnly() {
+ const open = panel.querySelector('#aord-open'); if (open) open.outerHTML = renderOpen();
+ const hist = panel.querySelector('#aord-history'); if (hist) hist.outerHTML = renderHistory();
+ const stats = panel.querySelector('#aord-stats'); if (stats) stats.outerHTML = renderStats();
+ wireLists();
+ renderLiveBadge();
+ }
+
+ function renderLiveBadge() {
+ const b = panel.querySelector('#aord-livebadge');
+ if (b) b.innerHTML = state.live ? `<span class="aord-live"><span class="dot"></span>live</span>` : '';
+ }
+
+ function renderStats() {
+ const s = state.summary || {};
+ return `<div class="aord-stats" id="aord-stats">
+ <div class="aord-stat"><div class="l">Active</div><div class="n">${s.active ?? 0}</div></div>
+ <div class="aord-stat"><div class="l">Filled</div><div class="n">${s.filled ?? 0}</div></div>
+ <div class="aord-stat"><div class="l">Fills</div><div class="n">${s.lifetime_fills ?? 0}</div></div>
+ <div class="aord-stat"><div class="l">Balance</div><div class="n">${s.balance_sol == null ? '—' : formatSol(s.balance_sol) + ' SOL'}</div></div>
+ </div>`;
+ }
+
+ function renderHero() {
+ const s = state.summary || {};
+ const frozen = s.frozen ? `<div class="aord-banner"><span>🧊 Wallet frozen — orders won’t fire until you unfreeze it under Limits.</span></div>` : '';
+ const killed = s.kill_switch ? `<div class="aord-banner"><span>⛔ Discretionary trading is paused (kill switch) — orders are held until you re-enable it.</span></div>` : '';
+ const cancelAll = s.active ? `<button class="aord-btn danger sm" id="aord-cancel-all">Cancel all (${s.active})</button>` : '';
+ return `<div class="aord-hero">
+ <div class="aord-hero-top">
+ <h2 class="aord-title">Programmable orders <span id="aord-livebadge">${state.live ? '<span class="aord-live"><span class="dot"></span>live</span>' : ''}</span><small>Limit · stop · trailing · DCA · TWAP · conditional — fired automatically, inside your guardrails.</small></h2>
+ ${cancelAll}
+ </div>
+ ${renderStats()}
+ ${frozen}${killed}
+ </div>`;
+ }
+
+ function renderForm() {
+ const f = state.form;
+ const typeGrid = Object.entries(TYPE_META).map(([k, m]) => `
+ <button class="aord-type" data-type="${k}" aria-pressed="${f.type === k}">
+ <div class="t">${m.icon} ${esc(m.label)}</div><div class="b">${esc(m.blurb)}</div>
+ </button>`).join('');
+ return `<div class="aord-card">
+ <h3>+ New order</h3>
+ <p class="sub">Pick a type, set the trigger, preview the live fill condition + firewall verdict, then arm.</p>
+ <div class="aord-types">${typeGrid}</div>
+ <div class="aord-field">
+ <label>Side</label>
+ <div class="aord-seg" role="group" aria-label="side">
+ <button data-side="buy" aria-pressed="${f.side === 'buy'}">Buy</button>
+ <button data-side="sell" aria-pressed="${f.side === 'sell'}">Sell</button>
+ </div>
+ </div>
+ <div class="aord-field"><label>Token mint</label><input class="aord-input" id="f-mint" placeholder="${THREE_MINT}" value="${esc(f.mint)}" spellcheck="false" autocomplete="off"/></div>
+ ${renderTypeFields(f)}
+ <div class="aord-row">
+ <div class="aord-field"><label>Max slippage (bps)</label><input class="aord-input" id="f-slippage" type="number" min="1" max="5000" value="${esc(f.slippage_bps)}"/></div>
+ <div class="aord-field"><label>Expires (optional)</label><input class="aord-input" id="f-expires" type="datetime-local" value="${esc(f.expires_at)}"/></div>
+ </div>
+ ${state.preview ? renderPreview(state.preview) : ''}
+ <div class="aord-actions">
+ <button class="aord-btn" id="aord-preview" ${state.previewing ? 'disabled' : ''}>${state.previewing ? '<span class="aord-spin"></span>Checking…' : 'Preview'}</button>
+ <button class="aord-btn primary" id="aord-create" ${state.creating ? 'disabled' : ''}>${state.creating ? '<span class="aord-spin"></span>Arming…' : 'Arm order'}</button>
+ </div>
+ </div>`;
+ }
+
+ function renderTypeFields(f) {
+ const metricSel = (id) => `<div class="aord-field"><label>Trigger metric</label><select class="aord-select" id="${id}">${Object.entries(METRIC_LABEL).map(([k, l]) => `<option value="${k}" ${f.trigger_metric === k ? 'selected' : ''}>${esc(l)}</option>`).join('')}</select></div>`;
+ const sizeField = f.side === 'buy'
+ ? `<div class="aord-field"><label>Size (SOL per fill)</label><input class="aord-input" id="f-size_sol" type="number" step="0.001" min="0" value="${esc(f.size_sol)}"/></div>`
+ : `<div class="aord-field"><label>Sell (% of holding)</label><input class="aord-input" id="f-sell_pct" type="number" step="1" min="1" max="100" value="${esc(f.sell_pct)}"/></div>`;
+
+ if (f.type === 'limit') return `<div class="aord-row">${metricSel('f-metric')}<div class="aord-field"><label>Target (${shortMetric(f.trigger_metric)})</label><input class="aord-input" id="f-limit_price" type="number" step="any" min="0" value="${esc(f.limit_price)}" placeholder="${f.side === 'buy' ? 'buy at or below' : 'sell at or above'}"/></div></div><div class="aord-row">${sizeField}</div>`;
+ if (f.type === 'stop') return `<div class="aord-row">${metricSel('f-metric')}<div class="aord-field"><label>Stop (${shortMetric(f.trigger_metric)})</label><input class="aord-input" id="f-stop_price" type="number" step="any" min="0" value="${esc(f.stop_price)}" placeholder="${f.side === 'sell' ? 'sell if it falls to' : 'buy once it breaks'}"/></div></div><div class="aord-row">${sizeField}</div>`;
+ if (f.type === 'trailing') return `<div class="aord-row">${metricSel('f-metric')}<div class="aord-field"><label>Trail (%)</label><input class="aord-input" id="f-trail_pct" type="number" step="0.1" min="0.1" max="99" value="${esc(f.trail_pct)}"/></div></div><div class="aord-row">${sizeField}</div>`;
+ if (f.type === 'dca') return `<div class="aord-row"><div class="aord-field"><label>Every</label>${intervalSelect(f)}</div><div class="aord-field"><label>Slices</label><input class="aord-input" id="f-slices" type="number" min="1" max="1000" value="${esc(f.slices)}"/></div></div><div class="aord-row">${sizeField}</div>`;
+ if (f.type === 'twap') {
+ const total = f.side === 'buy'
+ ? `<div class="aord-field"><label>Total (SOL)</label><input class="aord-input" id="f-total_sol" type="number" step="0.001" min="0" value="${esc(f.total_sol)}"/></div>`
+ : `<div class="aord-field"><label>Total (% of holding)</label><input class="aord-input" id="f-total_pct" type="number" step="1" min="1" max="100" value="${esc(f.total_pct)}"/></div>`;
+ return `<div class="aord-row"><div class="aord-field"><label>Every</label>${intervalSelect(f)}</div><div class="aord-field"><label>Slices</label><input class="aord-input" id="f-slices" type="number" min="2" max="1000" value="${esc(f.slices)}"/></div></div><div class="aord-row">${total}</div>`;
+ }
+ if (f.type === 'conditional') return `${renderConditionBuilder(f)}<div class="aord-row">${sizeField}</div>`;
+ return '';
+ }
+
+ function intervalSelect(f) {
+ const opts = [['300', '5 min'], ['900', '15 min'], ['1800', '30 min'], ['3600', '1 hour'], ['21600', '6 hours'], ['86400', '1 day']];
+ return `<select class="aord-select" id="f-interval">${opts.map(([v, l]) => `<option value="${v}" ${f.interval === v ? 'selected' : ''}>${l}</option>`).join('')}</select>`;
+ }
+
+ function renderConditionBuilder(f) {
+ const sig = state.schema?.signals || {};
+ const sigOpts = Object.entries(sig).map(([k, v]) => [k, v.label, v.kind]);
+ const clauseRow = (c, i) => {
+ const def = sig[c.signal];
+ const isBool = def?.kind === 'bool';
+ const ops = isBool ? (state.schema?.bool_ops || ['is_true', 'is_false']) : (state.schema?.number_ops || ['gt', 'gte', 'lt', 'lte', 'eq', 'ne']);
+ const valField = isBool ? '' : `<input class="aord-input" data-ci="${i}" data-cf="value" type="number" step="any" value="${esc(c.value)}" placeholder="value"/>`;
+ return `<div class="aord-clause">
+ <select class="aord-select" data-ci="${i}" data-cf="signal">${sigOpts.map(([k, l]) => `<option value="${k}" ${c.signal === k ? 'selected' : ''}>${esc(l)}</option>`).join('')}</select>
+ <select class="aord-select" data-ci="${i}" data-cf="op">${ops.map((o) => `<option value="${o}" ${c.op === o ? 'selected' : ''}>${esc(opLabel(o))}</option>`).join('')}</select>
+ ${valField}
+ <button class="x" data-rm="${i}" title="Remove" aria-label="Remove clause">✕</button>
+ </div>`;
+ };
+ return `<div class="aord-cond">
+ <div class="aord-cond-mode">Fire when
+ <div class="aord-seg" role="group">
+ <button data-mode="all" aria-pressed="${f.condition_mode === 'all'}">ALL</button>
+ <button data-mode="any" aria-pressed="${f.condition_mode === 'any'}">ANY</button>
+ </div>
+ of these are true:</div>
+ ${f.clauses.map(clauseRow).join('')}
+ <button class="aord-btn ghost sm" id="aord-add-clause">+ Add condition</button>
+ </div>`;
+ }
+
+ function renderPreview(p) {
+ if (!p.ok) return `<div class="aord-prev"><div class="aord-err" style="margin:0">${esc(p.message || 'Invalid order')}</div></div>`;
+ const cur = p.preview?.current;
+ const fw = p.firewall;
+ const lines = [];
+ if (cur) {
+ const cv = cur.value == null ? '—' : (cur.metric === 'mcap_usd' ? formatUsd(cur.value) : `${formatSol(cur.value)} ${cur.metric === 'price_sol' ? 'SOL/tok' : 'SOL'}`);
+ lines.push(`<div class="ln">Now: <strong>${esc(cv)}</strong>${cur.graduated ? ' · graduated (AMM)' : ''}</div>`);
+ }
+ if (p.preview?.would_fire_now != null) lines.push(`<div class="ln">${p.preview.would_fire_now ? '⚡ Would fire immediately at the current price.' : '⏳ Waiting — the trigger isn’t met yet.'}</div>`);
+ if (p.preview?.missing?.length) lines.push(`<div class="ln">⚠️ No live data yet for: ${esc(p.preview.missing.join(', '))} (won’t fire until available).</div>`);
+ if (fw) lines.push(`<div class="ln">Firewall: <span class="aord-fw ${esc(fw.verdict)}">${esc(fw.verdict)}</span>${fw.reasons?.length ? ' · ' + esc(fw.reasons.join(', ')) : ''}</div>`);
+ return `<div class="aord-prev"><div class="rb">${esc(p.readback || '')}</div>${lines.join('')}</div>`;
+ }
+
+ function renderOpen() {
+ const open = state.orders.filter((o) => OPEN_STATUSES.includes(o.status));
+ const inner = open.length
+ ? `<ul class="aord-list">${open.map(renderOrderItem).join('')}</ul>`
+ : `<div class="aord-empty"><div class="ic">📋</div>No open orders. Create one above — it’ll fire automatically when its trigger is met.</div>`;
+ return `<div class="aord-card" id="aord-open"><h3>Open orders</h3><p class="sub">Each is evaluated against live on-chain data and fires through your firewall + spend guards.</p>${inner}</div>`;
+ }
+
+ function renderHistory() {
+ const done = state.orders.filter((o) => !OPEN_STATUSES.includes(o.status));
+ if (!done.length) return `<div class="aord-card" id="aord-history" style="display:none"></div>`;
+ return `<div class="aord-card" id="aord-history"><h3>History</h3><ul class="aord-list">${done.slice(0, 30).map(renderOrderItem).join('')}</ul></div>`;
+ }
+
+ function renderOrderItem(o) {
+ const m = TYPE_META[o.type] || { icon: '•' };
+ const tone = STATUS_TONE[o.status] || 'muted';
+ const foot = [];
+ foot.push(`<span class="aord-pill ${tone}">${esc(o.status)}</span>`);
+ if (o.last_price != null) foot.push(`now ${o.trigger_metric === 'mcap_usd' ? formatUsd(o.last_price) : formatSol(o.last_price)}`);
+ if (o.fill_count) foot.push(`${o.fill_count} fill${o.fill_count === 1 ? '' : 's'}`);
+ if (o.filled_sol) foot.push(`${formatSol(o.filled_sol)} SOL`);
+ if (o.last_error && o.status !== 'filled') foot.push(`<span title="${esc(o.last_error)}">⚠ ${esc(String(o.last_error).slice(0, 48))}</span>`);
+ const sched = (o.type === 'dca' || o.type === 'twap') && o.schedule
+ ? `<div class="aord-prog"><i style="width:${Math.min(100, Math.round((o.schedule.filled_slices || 0) / (o.schedule.slices || 1) * 100))}%"></i></div>` : '';
+ const ctl = OPEN_STATUSES.includes(o.status) ? `<div class="aord-item-ctl">
+ <button class="aord-btn ghost sm" data-pause="${esc(o.id)}">${o.status === 'paused' ? 'Resume' : 'Pause'}</button>
+ <button class="aord-btn danger sm" data-cancel="${esc(o.id)}">Cancel</button>
+ <button class="aord-btn ghost sm" data-fills="${esc(o.id)}">Fills</button>
+ </div>` : `<div class="aord-item-ctl"><button class="aord-btn ghost sm" data-fills="${esc(o.id)}">Fills</button></div>`;
+ return `<li class="aord-item" data-id="${esc(o.id)}">
+ <div class="aord-item-top">
+ <span class="aord-item-ic">${m.icon}</span>
+ <div class="aord-item-body">
+ <div class="aord-item-ttl">${esc((TYPE_META[o.type]?.label || o.type))} ${esc(o.side)} ${o.symbol ? '$' + esc(o.symbol) : esc(String(o.mint).slice(0, 4)) + '…'}</div>
+ <div class="aord-item-desc">${esc(o.readback || '')}</div>
+ ${sched}
+ <div class="aord-item-foot">${foot.join('')}</div>
+ <div class="aord-fills" data-fills-for="${esc(o.id)}"></div>
+ </div>
+ </div>
+ ${ctl}
+ </li>`;
+ }
+
+ // ── wiring ────────────────────────────────────────────────────────────────
+ function wire() {
+ panel.querySelectorAll('[data-type]').forEach((b) => b.addEventListener('click', () => { state.form.type = b.dataset.type; state.preview = null; render(); }));
+ panel.querySelectorAll('[data-side]').forEach((b) => b.addEventListener('click', () => { state.form.side = b.dataset.side; state.preview = null; render(); }));
+ panel.querySelectorAll('[data-mode]').forEach((b) => b.addEventListener('click', () => { state.form.condition_mode = b.dataset.mode; render(); }));
+ bindInput('f-mint', 'mint'); bindInput('f-slippage', 'slippage_bps'); bindInput('f-expires', 'expires_at');
+ bindInput('f-metric', 'trigger_metric', true); bindInput('f-limit_price', 'limit_price'); bindInput('f-stop_price', 'stop_price');
+ bindInput('f-trail_pct', 'trail_pct'); bindInput('f-size_sol', 'size_sol'); bindInput('f-sell_pct', 'sell_pct');
+ bindInput('f-total_sol', 'total_sol'); bindInput('f-total_pct', 'total_pct'); bindInput('f-interval', 'interval', true); bindInput('f-slices', 'slices');
+ // re-render on metric change so unit labels update
+ panel.querySelector('#f-metric')?.addEventListener('change', () => render());
+ panel.querySelector('#aord-add-clause')?.addEventListener('click', () => { state.form.clauses.push({ signal: 'mcap_usd', op: 'lt', value: '40000' }); render(); });
+ panel.querySelectorAll('[data-rm]').forEach((b) => b.addEventListener('click', () => { state.form.clauses.splice(Number(b.dataset.rm), 1); if (!state.form.clauses.length) state.form.clauses.push({ signal: 'smart_money_score', op: 'gte', value: '60' }); render(); }));
+ panel.querySelectorAll('[data-ci]').forEach((el) => el.addEventListener('change', () => {
+ const i = Number(el.dataset.ci), field = el.dataset.cf;
+ state.form.clauses[i][field] = el.value;
+ if (field === 'signal') render(); // op set may change (bool vs number)
+ }));
+ panel.querySelector('#aord-preview')?.addEventListener('click', onPreview);
+ panel.querySelector('#aord-create')?.addEventListener('click', onCreate);
+ wireLists();
+ }
+
+ function wireLists() {
+ panel.querySelector('#aord-cancel-all')?.addEventListener('click', onCancelAll);
+ panel.querySelectorAll('[data-cancel]').forEach((b) => b.addEventListener('click', () => onCancel(b.dataset.cancel)));
+ panel.querySelectorAll('[data-pause]').forEach((b) => b.addEventListener('click', () => onPause(b.dataset.pause)));
+ panel.querySelectorAll('[data-fills]').forEach((b) => b.addEventListener('click', () => onFills(b.dataset.fills)));
+ }
+
+ function bindInput(elId, field, isSelect) {
+ const el = panel.querySelector('#' + elId);
+ if (!el) return;
+ el.addEventListener(isSelect ? 'change' : 'input', (e) => { state.form[field] = e.target.value; });
+ }
+
+ function buildPayload() {
+ const f = state.form;
+ const o = { type: f.type, side: f.side, mint: f.mint.trim(), slippage_bps: Number(f.slippage_bps) || 500, trigger_metric: f.trigger_metric };
+ if (f.expires_at) o.expires_at = new Date(f.expires_at).toISOString();
+ if (f.side === 'buy') o.size_sol = Number(f.size_sol);
+ else o.sell_pct = Number(f.sell_pct);
+ if (f.type === 'limit') o.limit_price = Number(f.limit_price);
+ else if (f.type === 'stop') o.stop_price = Number(f.stop_price);
+ else if (f.type === 'trailing') o.trail_pct = Number(f.trail_pct);
+ else if (f.type === 'dca') o.schedule = { interval_seconds: Number(f.interval), slices: Number(f.slices) };
+ else if (f.type === 'twap') {
+ o.schedule = { interval_seconds: Number(f.interval), slices: Number(f.slices) };
+ if (f.side === 'buy') { o.total_sol = Number(f.total_sol); delete o.size_sol; } else { o.sell_pct = Number(f.total_pct); }
+ } else if (f.type === 'conditional') {
+ o.condition = { [f.condition_mode]: f.clauses.map((c) => state.schema?.signals?.[c.signal]?.kind === 'bool' ? { signal: c.signal, op: c.op } : { signal: c.signal, op: c.op, value: Number(c.value) }) };
+ }
+ return o;
+ }
+
+ async function onPreview() {
+ state.previewing = true; state.preview = null; render();
+ const res = await call(base('preview'), { method: 'POST', body: buildPayload() });
+ if (destroyed) return;
+ state.previewing = false;
+ state.preview = res.ok ? res.data : { ok: false, message: res.message };
+ render();
+ }
+
+ async function onCreate() {
+ state.creating = true; render();
+ const res = await call(base(), { method: 'POST', body: buildPayload() });
+ if (destroyed) return;
+ state.creating = false;
+ if (!res.ok) { ctx.toast(res.message || 'Could not create order'); render(); return; }
+ ctx.toast('Order armed — it’ll fire when its trigger is met.');
+ state.form = freshForm(); state.preview = null;
+ await load();
+ }
+
+ async function onCancel(id) {
+ const res = await call(`${base().split('?')[0]}/${id}?network=${ctx.getNetwork()}`, { method: 'DELETE' });
+ if (destroyed) return;
+ if (!res.ok) { ctx.toast(res.message || 'Cancel failed'); return; }
+ ctx.toast('Order cancelled.');
+ await load();
+ }
+
+ async function onPause(id) {
+ const o = state.orders.find((x) => x.id === id);
+ const paused = o?.status === 'paused';
+ const res = await call(`${base().split('?')[0]}/${id}?network=${ctx.getNetwork()}`, { method: 'PUT', body: { paused: !paused } });
+ if (destroyed) return;
+ if (!res.ok) { ctx.toast(res.message || 'Update failed'); return; }
+ ctx.toast(paused ? 'Resumed.' : 'Paused.');
+ await load();
+ }
+
+ async function onCancelAll() {
+ if (!window.confirm('Cancel every active order? This is instant and can’t be undone.')) return;
+ const res = await call(base('cancel-all'), { method: 'POST', body: {} });
+ if (destroyed) return;
+ if (!res.ok) { ctx.toast(res.message || 'Failed'); return; }
+ ctx.toast(`Cancelled ${res.data.cancelled} order${res.data.cancelled === 1 ? '' : 's'}.`);
+ await load();
+ }
+
+ async function onFills(id) {
+ const host = panel.querySelector(`[data-fills-for="${CSS.escape(id)}"]`);
+ if (!host) return;
+ if (host.dataset.open === 'true') { host.dataset.open = 'false'; host.innerHTML = ''; return; }
+ host.dataset.open = 'true';
+ host.innerHTML = `<div class="aord-skel" style="width:60%"></div>`;
+ const res = await call(`${base().split('?')[0]}/${id}?network=${ctx.getNetwork()}`);
+ if (destroyed) return;
+ if (!res.ok) { host.innerHTML = `<div class="aord-err" style="margin-top:8px">${esc(res.message)}</div>`; return; }
+ const fills = res.data.fills || [];
+ if (!fills.length) { host.innerHTML = `<div class="aord-item-foot" style="margin-top:8px"><span>No fills yet.</span></div>`; return; }
+ host.innerHTML = `<div style="margin-top:9px;display:flex;flex-direction:column;gap:6px">${fills.map((fl) => {
+ const sig = fl.signature ? `<a href="${esc(explorerTxUrl(fl.signature, ctx.getNetwork()))}" target="_blank" rel="noopener">receipt ↗</a>` : '';
+ const amt = fl.side === 'buy' ? `${formatSol(fl.sol_amount)} SOL` : `${formatSol(fl.sol_amount)} SOL out`;
+ return `<div class="aord-item-foot" style="margin:0"><span class="aord-pill ${STATUS_TONE[fl.status] || 'muted'}">${esc(fl.status)}</span><span>${esc(fl.trigger_reason || '')}</span><span>${esc(amt)}</span>${fl.price_impact_pct != null ? `<span>${Number(fl.price_impact_pct).toFixed(1)}% impact</span>` : ''}${sig}</div>`;
+ }).join('')}</div>`;
+ }
+
+ function shortMetric(m) { return m === 'mcap_usd' ? 'USD' : m === 'mcap_sol' ? 'SOL' : 'SOL/tok'; }
+ function opLabel(o) { return { gt: '>', gte: '≥', lt: '<', lte: '≤', eq: '=', ne: '≠', is_true: 'is true', is_false: 'is false' }[o] || o; }
+
+ load();
+ return {
+ destroy() { destroyed = true; if (es) { try { es.close(); } catch { /* */ } es = null; } },
+ onHide() { if (es) { try { es.close(); } catch { /* */ } es = null; state.live = false; } },
+ onShow() { if (!destroyed && !es) { subscribeLive(); } },
+ };
+ },
+});
diff --git a/src/agent-wallet-hub/tabs/portfolio.js b/src/agent-wallet-hub/tabs/portfolio.js
new file mode 100644
index 000000000..8cce050eb
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/portfolio.js
@@ -0,0 +1,443 @@
+/**
+ * Agent Wallet hub — Portfolio Command tab (owner-only).
+ *
+ * One real-time, unified view of everything the agent wallet holds and has done:
+ * - a net-worth header (SOL + USD) with a live sparkline built from the stream,
+ * - a holdings table (live value, FIFO cost basis, unrealized P&L, liquidity
+ * warning) with a one-click jump to trade/exit,
+ * - a PnL attribution breakdown (what's making / losing money, by source),
+ * - a risk panel (concentration, exposure, drawdown, realized vol) with
+ * plain-language flags.
+ *
+ * Every figure is real, from GET /api/agents/:id/portfolio (api/_lib/portfolio.js):
+ * live on-chain valuation + the sniper position ledger + the custody/spend ledger.
+ * Unpriceable holdings are flagged, never guessed. Live updates arrive over the
+ * SSE stream at …/portfolio/stream. Every state is designed; accessible; responsive.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { formatSol, formatUsd } from '../util.js';
+
+const PORT_STYLE_ID = 'awh-portfolio-style';
+const PORT_STYLE = `
+.awh-port { display: flex; flex-direction: column; gap: var(--awh-gap, 16px); }
+.awh-port-nw { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--space-4,16px); flex-wrap: wrap; }
+.awh-port-nw-main { min-width: 0; }
+.awh-port-nw-label { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim,#888); }
+.awh-port-nw-usd { font-family: var(--font-display, system-ui); font-size: var(--text-xl, 1.618rem); font-weight: 700; color: var(--ink-bright,#fff); line-height: 1.1; margin-top: 4px; }
+.awh-port-nw-sol { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-top: 4px; }
+.awh-port-spark { flex: 0 0 auto; }
+.awh-port-spark svg { display: block; }
+.awh-port-pnl-row { display: flex; gap: var(--space-4,16px); flex-wrap: wrap; margin-top: var(--space-3,12px); }
+.awh-port-pnl { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }
+.awh-port-pnl b { font-family: var(--font-mono, ui-monospace, monospace); font-weight: 600; }
+.awh-pos { color: var(--success,#4ade80); }
+.awh-neg { color: var(--danger,#f87171); }
+.awh-live { display: inline-flex; align-items: center; gap: 5px; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }
+.awh-live::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--success,#4ade80); box-shadow: 0 0 0 0 color-mix(in srgb, var(--success,#4ade80) 60%, transparent); animation: awh-live-pulse 2s ease-out infinite; }
+@keyframes awh-live-pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--success,#4ade80) 50%, transparent); } 70% { box-shadow: 0 0 0 6px transparent; } 100% { box-shadow: 0 0 0 0 transparent; } }
+@media (prefers-reduced-motion: reduce) { .awh-live::before { animation: none; } }
+
+.awh-port-table { width: 100%; border-collapse: collapse; font-size: var(--text-sm,.764rem); }
+.awh-port-table th { text-align: right; font-weight: 500; color: var(--ink-dim,#888); font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .04em; padding: 0 0 8px; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.08)); }
+.awh-port-table th:first-child { text-align: left; }
+.awh-port-table td { text-align: right; padding: 9px 0; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.06)); font-family: var(--font-mono, ui-monospace, monospace); }
+.awh-port-table td:first-child { text-align: left; font-family: inherit; }
+.awh-port-table tr:last-child td { border-bottom: none; }
+.awh-port-asset { display: flex; align-items: center; gap: 9px; min-width: 0; }
+.awh-port-asset img { width: 22px; height: 22px; border-radius: 50%; flex: none; background: var(--surface-2, rgba(255,255,255,.05)); object-fit: cover; }
+.awh-port-asset .ph { width: 22px; height: 22px; border-radius: 50%; flex: none; background: var(--surface-3, rgba(255,255,255,.08)); display: inline-flex; align-items: center; justify-content: center; font-size: 9px; color: var(--ink-dim,#888); font-family: var(--font-mono, ui-monospace, monospace); }
+.awh-port-sym { color: var(--ink-bright,#fff); font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.awh-port-sub { color: var(--ink-faint,#666); font-size: var(--text-2xs,.6875rem); }
+.awh-port-warn { display: inline-block; margin-left: 6px; font-size: var(--text-2xs,.6875rem); color: var(--warn,#fbbf24); border: 1px solid color-mix(in srgb, var(--warn,#fbbf24) 40%, transparent); border-radius: var(--radius-pill,999px); padding: 1px 7px; vertical-align: middle; }
+.awh-port-trade { font-size: var(--text-2xs,.6875rem); padding: 5px 10px; }
+.awh-muted { color: var(--ink-faint,#666); }
+
+.awh-attr { display: flex; flex-direction: column; gap: 2px; }
+.awh-attr-row { display: grid; grid-template-columns: 1fr auto auto; gap: var(--space-3,12px); align-items: center; padding: 9px 0; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.06)); }
+.awh-attr-row:last-child { border-bottom: none; }
+.awh-attr-label { color: var(--ink,#e8e8e8); font-size: var(--text-sm,.764rem); }
+.awh-attr-bar { grid-column: 1 / -1; height: 4px; border-radius: var(--radius-pill,999px); background: var(--surface-2, rgba(255,255,255,.05)); overflow: hidden; }
+.awh-attr-bar > span { display: block; height: 100%; border-radius: inherit; }
+.awh-attr-val { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-sm,.764rem); }
+.awh-attr-sub { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); font-family: var(--font-mono, ui-monospace, monospace); }
+
+.awh-risk-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: var(--space-3,12px); }
+.awh-risk-cell { background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding: var(--space-3,12px); }
+.awh-risk-k { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .04em; color: var(--ink-dim,#888); }
+.awh-risk-v { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-lg,1.236rem); font-weight: 700; color: var(--ink-bright,#fff); margin-top: 4px; }
+.awh-flags { list-style: none; margin: var(--space-3,12px) 0 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
+.awh-flag { display: flex; gap: 9px; align-items: flex-start; font-size: var(--text-sm,.764rem); padding: 9px 11px; border-radius: var(--radius-md,10px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); background: var(--surface-1, rgba(255,255,255,.03)); }
+.awh-flag::before { content: '•'; flex: none; }
+.awh-flag.is-danger { border-color: color-mix(in srgb, var(--danger,#ef4444) 45%, transparent); color: var(--danger,#f87171); }
+.awh-flag.is-warn { border-color: color-mix(in srgb, var(--warn,#fbbf24) 45%, transparent); color: var(--warn,#fbbf24); }
+.awh-flag.is-info { color: var(--ink-dim,#888); }
+.awh-port-note { font-size: var(--text-2xs,.6875rem); color: var(--ink-faint,#666); margin-top: var(--space-3,12px); }
+
+.awh-port-skel span { display: block; background: var(--surface-2, rgba(255,255,255,.05)); border-radius: var(--radius-sm,6px); animation: awh-skel 1.4s ease-in-out infinite; }
+.awh-port-skel .a { height: 30px; width: 46%; margin-bottom: 10px; }
+.awh-port-skel .b { height: 14px; width: 28%; margin-bottom: 20px; }
+.awh-port-skel .c { height: 18px; width: 100%; margin-bottom: 10px; }
+.awh-port-skel .c:nth-child(4) { width: 82%; }
+@keyframes awh-skel { 0%,100% { opacity: .5; } 50% { opacity: 1; } }
+@media (prefers-reduced-motion: reduce) { .awh-port-skel span, .awh-port-table td { animation: none; } }
+@media (max-width: 480px) {
+ .awh-port-table .col-basis, .awh-port-table .col-amt { display: none; }
+}
+`;
+
+function injectStyle() {
+ if (typeof document === 'undefined' || document.getElementById(PORT_STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = PORT_STYLE_ID;
+ tag.textContent = PORT_STYLE;
+ document.head.appendChild(tag);
+}
+
+const SPARK_MAX = 40; // points retained for the live net-worth sparkline
+
+function fmtSolSigned(sol) {
+ if (sol == null || !Number.isFinite(sol)) return '—';
+ const s = formatSol(Math.abs(sol));
+ return `${sol > 0 ? '+' : sol < 0 ? '−' : ''}${s} SOL`;
+}
+function pnlClass(n) { return n > 0 ? 'awh-pos' : n < 0 ? 'awh-neg' : ''; }
+
+function sparkline(points, w = 132, h = 38) {
+ const vals = points.filter((v) => Number.isFinite(v));
+ if (vals.length < 2) return '';
+ const min = Math.min(...vals);
+ const max = Math.max(...vals);
+ const span = max - min || 1;
+ const stepX = w / (vals.length - 1);
+ const pts = vals.map((v, i) => {
+ const x = i * stepX;
+ const y = h - ((v - min) / span) * (h - 4) - 2;
+ return `${x.toFixed(1)},${y.toFixed(1)}`;
+ });
+ const up = vals[vals.length - 1] >= vals[0];
+ const stroke = up ? 'var(--success,#4ade80)' : 'var(--danger,#f87171)';
+ return `<svg width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="Net worth trend">
+ <polyline fill="none" stroke="${stroke}" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" points="${pts.join(' ')}" />
+ </svg>`;
+}
+
+registerWalletTab({
+ id: 'portfolio',
+ label: 'Portfolio',
+ order: 15,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ const { escapeHtml, toast, copyToClipboard } = ctx;
+
+ let destroyed = false;
+ let visible = false;
+ let detachNet = null;
+ let es = null;
+ const state = {
+ loaded: false,
+ error: null,
+ data: null,
+ spark: [], // net-worth USD history for the sparkline
+ live: false,
+ streamDown: false, // SSE permanently closed → live updates paused
+ };
+
+ function pushSpark(usd) {
+ if (!Number.isFinite(usd)) return;
+ state.spark.push(usd);
+ if (state.spark.length > SPARK_MAX) state.spark.shift();
+ }
+
+ function isEmpty(d) {
+ const nw = d?.net_worth?.usd ?? 0;
+ const nwSol = d?.net_worth?.sol ?? 0;
+ return (!d?.holdings || d.holdings.length === 0) && (d?.metrics?.closed_count ?? 0) === 0 && nw <= 0 && nwSol <= 0;
+ }
+
+ function render() {
+ if (destroyed) return;
+ if (!state.loaded) {
+ panel.innerHTML = `<div class="awh-card awh-port-skel" aria-busy="true" aria-label="Loading portfolio">
+ <span class="a"></span><span class="b"></span><span class="c"></span><span class="c"></span><span class="c"></span>
+ </div>`;
+ return;
+ }
+ if (state.error) {
+ panel.innerHTML = `<div class="awh-card">
+ <div class="awh-empty">Could not load the portfolio — ${escapeHtml(state.error)}.
+ <button class="awh-btn awh-port-trade" type="button" data-act="retry">Retry</button></div>
+ </div>`;
+ panel.querySelector('[data-act="retry"]')?.addEventListener('click', () => { reload(); });
+ return;
+ }
+ const d = state.data;
+ if (isEmpty(d)) {
+ panel.innerHTML = `<div class="awh-card">
+ <h2 class="awh-card-h">Portfolio Command</h2>
+ <div class="awh-empty">
+ This wallet is empty. Once it holds SOL or tokens — or makes its first trade or snipe —
+ its live net worth, cost basis, P&amp;L attribution, and risk metrics appear here.
+ <div style="margin-top:12px; display:flex; gap:8px; flex-wrap:wrap;">
+ <button class="awh-btn awh-port-trade" type="button" data-go="deposit">Deposit funds</button>
+ <button class="awh-btn awh-port-trade" type="button" data-go="trade">Make a trade</button>
+ </div>
+ </div>
+ </div>`;
+ panel.querySelectorAll('[data-go]').forEach((b) => b.addEventListener('click', () => ctx.openTab(b.dataset.go)));
+ return;
+ }
+
+ panel.innerHTML = `
+ ${renderHeader(d)}
+ ${renderHoldings(d)}
+ ${renderAttribution(d)}
+ ${renderRisk(d)}
+ `;
+ wire();
+ }
+
+ function renderHeader(d) {
+ const nw = d.net_worth || {};
+ const realized = nw.realized_pnl_sol ?? 0;
+ const unrealized = nw.unrealized_pnl_sol ?? 0;
+ const usd = formatUsd(nw.usd ?? 0) || '$0.00';
+ const spark = sparkline(state.spark);
+ return `<div class="awh-card">
+ <div class="awh-port-nw">
+ <div class="awh-port-nw-main">
+ <div class="awh-port-nw-label">Net worth ${state.live ? '<span class="awh-live">live</span>' : ''}</div>
+ <div class="awh-port-nw-usd">${escapeHtml(usd)}</div>
+ <div class="awh-port-nw-sol">${escapeHtml(formatSol(nw.sol))} SOL${d.sol_usd ? ` · SOL ${escapeHtml(formatUsd(d.sol_usd) || '')}` : ''}</div>
+ </div>
+ ${spark ? `<div class="awh-port-spark">${spark}</div>` : ''}
+ </div>
+ <div class="awh-port-pnl-row">
+ <span class="awh-port-pnl">Realized <b class="${pnlClass(realized)}">${escapeHtml(fmtSolSigned(realized))}</b></span>
+ <span class="awh-port-pnl">Unrealized <b class="${pnlClass(unrealized)}">${escapeHtml(fmtSolSigned(unrealized))}</b></span>
+ </div>
+ </div>`;
+ }
+
+ function renderHoldings(d) {
+ const rows = d.holdings || [];
+ if (!rows.length) {
+ return `<div class="awh-card"><h2 class="awh-card-h">Holdings</h2>
+ <div class="awh-empty">No holdings yet — deposits and buys appear here.</div></div>`;
+ }
+ const body = rows.map((h) => {
+ const sym = escapeHtml(h.symbol || '?');
+ const sub = h.isNative ? 'Native' : (h.is_three ? '$THREE' : (h.stable ? 'Stable' : escapeHtml(h.name || '')));
+ const img = h.logo
+ ? `<img src="${escapeHtml(h.logo)}" alt="" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('span'),{className:'ph',textContent:'${sym.slice(0, 2)}'}))">`
+ : `<span class="ph">${sym.slice(0, 2)}</span>`;
+ const value = h.usd_value != null ? (formatUsd(h.usd_value) || '—') : '<span class="awh-muted">unpriced</span>';
+ const amt = h.amount != null ? formatNum(h.amount) : '—';
+ const basis = h.cost_basis_sol != null ? `${formatSol(h.cost_basis_sol)}◎` : '<span class="awh-muted">—</span>';
+ let upnl = '<span class="awh-muted">—</span>';
+ if (h.unrealized_sol != null) {
+ const pct = h.unrealized_pct != null ? ` (${h.unrealized_pct > 0 ? '+' : ''}${h.unrealized_pct}%)` : '';
+ upnl = `<span class="${pnlClass(h.unrealized_sol)}">${escapeHtml(fmtSolSigned(h.unrealized_sol))}${pct}</span>`;
+ }
+ const warn = h.liquidity_warning ? `<span class="awh-port-warn" title="No live market price — value shown is unknown, never guessed.">illiquid</span>` : '';
+ const tradeBtn = h.isNative
+ ? ''
+ : `<button class="awh-btn awh-port-trade" type="button" data-trade="${escapeHtml(h.mint || '')}">Trade ↗</button>`;
+ return `<tr>
+ <td>
+ <div class="awh-port-asset">${img}
+ <span style="min-width:0;">
+ <span class="awh-port-sym">${sym}${warn}</span><br>
+ <span class="awh-port-sub">${sub}</span>
+ </span>
+ </div>
+ </td>
+ <td class="col-amt">${escapeHtml(amt)}</td>
+ <td>${value}</td>
+ <td class="col-basis">${basis}</td>
+ <td>${upnl}</td>
+ <td>${tradeBtn}</td>
+ </tr>`;
+ }).join('');
+ return `<div class="awh-card">
+ <h2 class="awh-card-h">Holdings <span class="awh-port-sub">${rows.length}</span></h2>
+ <div style="overflow-x:auto;">
+ <table class="awh-port-table">
+ <thead><tr>
+ <th>Asset</th><th class="col-amt">Amount</th><th>Value</th>
+ <th class="col-basis">Cost basis</th><th>Unrealized</th><th></th>
+ </tr></thead>
+ <tbody>${body}</tbody>
+ </table>
+ </div>
+ </div>`;
+ }
+
+ function renderAttribution(d) {
+ const rows = (d.attribution || []).filter((a) => !a.is_outflow);
+ const outflows = (d.attribution || []).filter((a) => a.is_outflow);
+ if (!rows.length && !outflows.length) {
+ return `<div class="awh-card"><h2 class="awh-card-h">P&amp;L attribution</h2>
+ <div class="awh-empty">No closed or open trades to attribute yet.</div></div>`;
+ }
+ const maxAbs = Math.max(1, ...rows.map((a) => Math.abs(a.total_sol ?? 0)));
+ const body = rows.map((a) => {
+ const total = a.total_sol ?? 0;
+ const w = Math.min(100, (Math.abs(total) / maxAbs) * 100);
+ const col = total >= 0 ? 'var(--success,#4ade80)' : 'var(--danger,#f87171)';
+ const realized = a.realized_sol ?? 0;
+ const unreal = a.unrealized_sol ?? 0;
+ return `<div class="awh-attr-row">
+ <span class="awh-attr-label">${escapeHtml(a.label)}</span>
+ <span class="awh-attr-sub">R ${escapeHtml(fmtSolSigned(realized))} · U ${escapeHtml(fmtSolSigned(unreal))}</span>
+ <span class="awh-attr-val ${pnlClass(total)}">${escapeHtml(fmtSolSigned(total))}</span>
+ <span class="awh-attr-bar"><span style="width:${w}%; background:${col};"></span></span>
+ </div>`;
+ }).join('');
+ const out = outflows.map((a) =>
+ `<div class="awh-attr-row">
+ <span class="awh-attr-label awh-muted">${escapeHtml(a.label)}</span>
+ <span class="awh-attr-sub">outflow</span>
+ <span class="awh-attr-val awh-muted">${escapeHtml(formatSol(a.spent_sol))} SOL</span>
+ </div>`).join('');
+ return `<div class="awh-card">
+ <h2 class="awh-card-h">P&amp;L attribution</h2>
+ <div class="awh-attr">${body}${out}</div>
+ <div class="awh-port-note">${escapeHtml(d.basis_note || '')}</div>
+ </div>`;
+ }
+
+ function renderRisk(d) {
+ const r = d.risk || {};
+ const cells = [
+ ['Concentration', r.top_position_pct != null ? `${r.top_position_pct}%` : '—', 'Largest position share'],
+ ['Diversification', r.concentration_hhi != null ? hhiLabel(r.concentration_hhi) : '—', 'HHI of weights'],
+ ['Tape exposure', r.exposure_pct != null ? `${r.exposure_pct}%` : '—', 'In volatile memecoins'],
+ ['Max drawdown', r.max_drawdown_pct != null ? `${r.max_drawdown_pct}%` : '—', 'Realized, from peak'],
+ ['Realized vol', r.realized_volatility_pct != null ? `${r.realized_volatility_pct}%` : '—', 'Per-trade return σ'],
+ ];
+ const grid = cells.map(([k, v]) =>
+ `<div class="awh-risk-cell"><div class="awh-risk-k">${escapeHtml(k)}</div><div class="awh-risk-v">${escapeHtml(v)}</div></div>`).join('');
+ const flags = (d.risk_flags || []).map((f) =>
+ `<li class="awh-flag is-${escapeHtml(f.level)}">${escapeHtml(f.text)}</li>`).join('');
+ return `<div class="awh-card">
+ <h2 class="awh-card-h">Risk</h2>
+ <div class="awh-risk-grid">${grid}</div>
+ ${flags ? `<ul class="awh-flags">${flags}</ul>` : ''}
+ </div>`;
+ }
+
+ function wire() {
+ panel.querySelectorAll('[data-trade]').forEach((b) => {
+ b.addEventListener('click', async () => {
+ const mint = b.dataset.trade;
+ if (mint) await copyToClipboard(mint);
+ ctx.openTab('trade');
+ toast('Mint copied — paste it into Trade to load this coin.');
+ });
+ });
+ }
+
+ async function fetchSnapshot() {
+ const net = ctx.getNetwork();
+ const url = `/api/agents/${encodeURIComponent(ctx.agentId)}/portfolio?network=${encodeURIComponent(net)}`;
+ const r = await fetch(url, { credentials: 'include' });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) {
+ const code = typeof j?.error === 'string' ? j.error : j?.error?.code || `error ${r.status}`;
+ throw new Error(j?.error_description || j?.error?.message || code);
+ }
+ return j.data;
+ }
+
+ async function reload() {
+ state.loaded = false;
+ state.error = null;
+ render();
+ try {
+ const d = await fetchSnapshot();
+ if (destroyed) return;
+ state.data = d;
+ pushSpark(d?.net_worth?.usd);
+ state.error = null;
+ } catch (e) {
+ state.error = e?.message || 'network error';
+ } finally {
+ state.loaded = true;
+ render();
+ if (!state.error) openStream();
+ }
+ }
+
+ function openStream() {
+ closeStream();
+ if (destroyed || !visible) return;
+ const net = ctx.getNetwork();
+ try {
+ es = new EventSource(
+ `/api/agents/${encodeURIComponent(ctx.agentId)}/portfolio/stream?network=${encodeURIComponent(net)}`,
+ { withCredentials: true },
+ );
+ } catch { es = null; return; }
+ es.addEventListener('snapshot', (msg) => {
+ let ev;
+ try { ev = JSON.parse(msg.data); } catch { return; }
+ if (destroyed || !ev) return;
+ state.data = { ...state.data, ...ev };
+ pushSpark(ev?.net_worth?.usd);
+ state.live = true;
+ render();
+ });
+ es.addEventListener('error', () => {
+ state.live = false;
+ // EventSource auto-reconnects; if the server closed permanently, stop.
+ if (es && es.readyState === EventSource.CLOSED) closeStream();
+ });
+ }
+ function closeStream() {
+ if (es) { try { es.close(); } catch { /* noop */ } es = null; }
+ state.live = false;
+ }
+
+ detachNet = ctx.onNetworkChange(() => {
+ state.spark = [];
+ closeStream();
+ reload();
+ });
+
+ render();
+
+ return {
+ onShow() {
+ visible = true;
+ if (!state.loaded || state.error) reload();
+ else { render(); openStream(); }
+ },
+ onHide() {
+ visible = false;
+ closeStream();
+ },
+ destroy() {
+ destroyed = true;
+ closeStream();
+ detachNet?.();
+ },
+ };
+ },
+});
+
+function formatNum(n) {
+ if (n == null || !Number.isFinite(n)) return '—';
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;
+ if (n >= 1000) return n.toLocaleString('en-US', { maximumFractionDigits: 2 });
+ if (n >= 1) return n.toLocaleString('en-US', { maximumFractionDigits: 4 });
+ return Number(n.toPrecision(4)).toString();
+}
+
+function hhiLabel(hhi) {
+ // HHI 0..1 → plain reading: <0.15 diversified, 0.15-0.4 moderate, >0.4 concentrated.
+ if (hhi < 0.15) return 'Broad';
+ if (hhi < 0.4) return 'Moderate';
+ return 'Concentrated';
+}
diff --git a/src/agent-wallet-hub/tabs/signals.js b/src/agent-wallet-hub/tabs/signals.js
new file mode 100644
index 000000000..7605e2bb5
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/signals.js
@@ -0,0 +1,330 @@
+/**
+ * Agent Wallet hub — Signals tab.
+ *
+ * Owner-only. Two halves of the reputation-gated signal marketplace, for THIS
+ * agent:
+ *
+ * PUBLISH — if the agent has a verified on-chain track record (the same badge
+ * the leaderboard computes), the owner can publish/edit a paid signal feed:
+ * per-signal and/or per-epoch USDC pricing, what it emits, visibility. Below
+ * the verification bar, the owner sees exactly what they still have to prove.
+ *
+ * SUBSCRIPTIONS — every feed this agent follows, with its mode (simulate/live),
+ * sizing, real spend + fill counts, and the controls that matter: an INSTANT
+ * kill (no further pay/trade), pause/resume, "sync now", and stop. The kill is
+ * the safety guarantee — one click halts everything immediately.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { apiFetch } from '../../api.js';
+
+const STYLE_ID = 'awh-signals-style';
+const STYLE = `
+.asg-wrap { display:flex; flex-direction:column; gap: var(--space-lg,1.6rem); }
+.asg-card { background: var(--surface-1, rgba(255,255,255,.03)); border:1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-lg,14px); padding: var(--space-lg,18px); }
+.asg-card h3 { margin:0 0 4px; font-size: var(--text-ui,.9rem); color: var(--ink-bright,#fff); font-weight:600; display:flex; align-items:center; gap:8px; justify-content:space-between; }
+.asg-card .sub { margin:0 0 var(--space-md,14px); font-size: var(--text-sm,.78rem); color: var(--ink-dim,#888); line-height:1.5; }
+.asg-fld { margin-bottom: 13px; }
+.asg-fld label { display:block; font-size: var(--text-sm,.76rem); color: var(--ink-dim,#888); margin-bottom:6px; }
+.asg-in, .asg-sel { width:100%; box-sizing:border-box; font:inherit; font-size: var(--text-md,.82rem); color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.04)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:9px 12px; }
+.asg-in:focus, .asg-sel:focus { outline:none; border-color: var(--wallet-stroke, rgba(139,92,246,.4)); }
+.asg-row2 { display:grid; grid-template-columns:1fr 1fr; gap:10px; }
+.asg-checks { display:flex; flex-wrap:wrap; gap:14px; margin-bottom:13px; }
+.asg-check { display:inline-flex; align-items:center; gap:7px; font-size: var(--text-sm,.78rem); color: var(--ink,#ccc); cursor:pointer; }
+.asg-btn { appearance:none; cursor:pointer; font:inherit; font-size: var(--text-sm,.78rem); font-weight:600; border-radius: var(--radius-md,10px); padding:10px 16px; border:1px solid var(--stroke-strong,rgba(255,255,255,.14)); background: var(--surface-2,rgba(255,255,255,.06)); color: var(--ink,#e8e8e8); transition: background .14s, transform .1s; }
+.asg-btn:hover:not(:disabled) { background: var(--surface-3,rgba(255,255,255,.09)); color:#fff; }
+.asg-btn:active:not(:disabled) { transform: translateY(1px); }
+.asg-btn:disabled { opacity:.5; cursor:not-allowed; }
+.asg-btn.primary { background: var(--wallet-accent,#c4b5fd); border-color: var(--wallet-accent,#c4b5fd); color:#160d28; }
+.asg-btn.danger { color: var(--danger,#f87171); border-color: color-mix(in srgb, var(--danger,#f87171) 40%, transparent); background: color-mix(in srgb, var(--danger,#f87171) 8%, transparent); }
+.asg-btn.danger:hover:not(:disabled) { background: color-mix(in srgb, var(--danger,#f87171) 16%, transparent); color:#fff; }
+.asg-btn.sm { padding:6px 11px; font-size: var(--text-2xs,.69rem); }
+.asg-gate { display:flex; flex-direction:column; gap:12px; }
+.asg-bars { display:flex; flex-direction:column; gap:10px; }
+.asg-bar { }
+.asg-bar .lbl { display:flex; justify-content:space-between; font-size: var(--text-sm,.76rem); color: var(--ink-dim,#999); margin-bottom:5px; }
+.asg-bar .lbl b { color: var(--ink-bright,#fff); font-weight:600; }
+.asg-track { height:7px; border-radius:999px; background: var(--surface-2,rgba(255,255,255,.06)); overflow:hidden; }
+.asg-fill { height:100%; border-radius:999px; background: linear-gradient(90deg,#8b5cf6,#34d399); transition: width .5s ease; }
+.asg-fill.met { background: #34d399; }
+.asg-feedlink { display:inline-flex; align-items:center; gap:6px; font-size: var(--text-sm,.78rem); color: var(--wallet-accent,#c4b5fd); text-decoration:none; }
+.asg-feedlink:hover { text-decoration:underline; }
+.asg-sub { border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-md,11px); padding:13px; margin-bottom:10px; }
+.asg-sub.killed { border-color: color-mix(in srgb, var(--danger,#f87171) 35%, transparent); }
+.asg-sub-top { display:flex; justify-content:space-between; align-items:flex-start; gap:10px; }
+.asg-sub-name { font-size: var(--text-md,.84rem); font-weight:600; color: var(--ink-bright,#fff); }
+.asg-sub-name a { color:inherit; text-decoration:none; }
+.asg-sub-name a:hover { color: var(--wallet-accent,#c4b5fd); }
+.asg-pill { font-size: var(--text-2xs,.66rem); font-weight:600; text-transform:uppercase; letter-spacing:.04em; padding:3px 8px; border-radius:999px; }
+.asg-pill.live { color:#160d28; background:#34d399; }
+.asg-pill.simulate { color: var(--ink-dim,#aaa); background: var(--surface-3,rgba(255,255,255,.08)); }
+.asg-pill.killed { color:#fff; background: var(--danger,#f87171); }
+.asg-pill.paused { color: var(--warn,#fbbf24); background: color-mix(in srgb,#fbbf24 14%,transparent); }
+.asg-sub-meta { display:flex; flex-wrap:wrap; gap:12px; margin:10px 0; font-size: var(--text-sm,.74rem); color: var(--ink-dim,#999); }
+.asg-sub-meta b { color: var(--ink,#ddd); font-weight:600; }
+.asg-sub-actions { display:flex; flex-wrap:wrap; gap:7px; }
+.asg-empty { text-align:center; padding:26px 14px; color: var(--ink-dim,#999); font-size: var(--text-sm,.8rem); line-height:1.5; }
+.asg-empty a { color: var(--wallet-accent,#c4b5fd); text-decoration:none; font-weight:600; }
+.asg-note { font-size: var(--text-sm,.74rem); margin-top:8px; line-height:1.5; }
+.asg-note.err { color: var(--danger,#f87171); }
+.asg-note.ok { color: var(--success,#4ade80); }
+.asg-skel { height:90px; border-radius: var(--radius-md,11px); background: var(--surface-2,rgba(255,255,255,.05)); animation: asg-pulse 1.3s ease infinite; }
+@keyframes asg-pulse { 50% { opacity:.5; } }
+@media (prefers-reduced-motion: reduce) { .asg-skel, .asg-fill { animation:none; transition:none; } }
+`;
+
+function injectStyle() {
+ if (document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = STYLE;
+ document.head.appendChild(el);
+}
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const num = (v, d = 0) => { const n = Number(v); return Number.isFinite(n) ? n : d; };
+
+registerWalletTab({
+ id: 'signals',
+ label: 'Signals',
+ order: 26,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ let destroyed = false;
+ const net = () => ctx.getNetwork();
+
+ panel.innerHTML = `<div class="asg-wrap"><div class="asg-skel"></div><div class="asg-skel"></div></div>`;
+
+ async function load() {
+ let feedData = null;
+ let subs = [];
+ try {
+ const [fRes, sRes] = await Promise.all([
+ apiFetch(`/api/signals/feeds?agent_id=${encodeURIComponent(ctx.agentId)}&network=${net()}`),
+ apiFetch('/api/signals/subscribe'),
+ ]);
+ feedData = fRes.ok ? await fRes.json() : null;
+ const sJson = sRes.ok ? await sRes.json() : { subscriptions: [] };
+ subs = (sJson.subscriptions || []).filter((s) => s.subscriber_agent_id === ctx.agentId);
+ } catch {
+ if (!destroyed) panel.innerHTML = `<div class="asg-card"><p class="asg-note err">Could not load signals. <button class="asg-btn sm" data-retry>Retry</button></p></div>`;
+ panel.querySelector('[data-retry]')?.addEventListener('click', load);
+ return;
+ }
+ if (destroyed) return;
+ render(feedData, subs);
+ }
+
+ function render(feedData, subs) {
+ panel.innerHTML = `<div class="asg-wrap">${publishCard(feedData)}${subsCard(subs)}</div>`;
+ wirePublish(feedData);
+ wireSubs();
+ }
+
+ // ── Publish half ──────────────────────────────────────────────────────────
+ function publishCard(d) {
+ const elig = d?.eligibility || {};
+ const feed = d?.feed || null;
+ if (!elig.verified) {
+ const req = elig.requirements || { min_closed: 12, min_unique_coins: 5, max_churn_pct: 40 };
+ const bar = (label, have, need, met) => `
+ <div class="asg-bar">
+ <div class="lbl"><span>${label}</span><b>${have} / ${need}</b></div>
+ <div class="asg-track"><span class="asg-fill ${met ? 'met' : ''}" style="width:${Math.min(100, need ? (have / need) * 100 : 0)}%"></span></div>
+ </div>`;
+ const closed = num(elig.closed_trades);
+ const coins = num(elig.unique_coins);
+ const churn = num(elig.churn_pct);
+ const realized = num(elig.realized_pnl_sol);
+ return `
+ <div class="asg-card">
+ <h3>Publish a signal feed</h3>
+ <p class="sub">Only a <b>verified track record</b> can publish — your signals must be backed by real, closed, on-chain trades, never self-declared. Here's what this agent still has to prove:</p>
+ <div class="asg-bars">
+ ${bar('Closed trades', closed, req.min_closed, closed >= req.min_closed)}
+ ${bar('Unique coins', coins, req.min_unique_coins, coins >= req.min_unique_coins)}
+ <div class="asg-bar"><div class="lbl"><span>Churn (lower is better)</span><b>${churn.toFixed(0)}% / ≤${req.max_churn_pct}%</b></div>
+ <div class="asg-track"><span class="asg-fill ${churn <= req.max_churn_pct ? 'met' : ''}" style="width:${Math.min(100, churn <= req.max_churn_pct ? 100 : 40)}%"></span></div></div>
+ <div class="asg-bar"><div class="lbl"><span>Realized P&amp;L</span><b>${realized > 0 ? '✓ positive' : 'must be positive'}</b></div>
+ <div class="asg-track"><span class="asg-fill ${realized > 0 ? 'met' : ''}" style="width:${realized > 0 ? 100 : 10}%"></span></div></div>
+ </div>
+ <p class="asg-note">Keep trading from this agent's wallet — the moment it clears the bar, publishing unlocks here automatically.</p>
+ </div>`;
+ }
+
+ // Verified → create / edit feed form.
+ const f = feed || {};
+ const v = (k, d2) => (f[k] != null ? f[k] : d2);
+ const slugLink = f.slug ? `<a class="asg-feedlink" href="/signals/${encodeURIComponent(f.slug)}" target="_blank" rel="noopener">View public feed ↗</a>` : '';
+ const statusBtn = feed
+ ? (f.status === 'active'
+ ? `<button class="asg-btn sm" data-feed-status="paused">Pause feed</button>`
+ : `<button class="asg-btn sm primary" data-feed-status="active">Resume feed</button>`)
+ : '';
+ return `
+ <div class="asg-card">
+ <h3><span>${feed ? 'Your signal feed' : 'Publish a signal feed'}</span><span>${slugLink}</span></h3>
+ <p class="sub">✓ Verified. Followers' agents pay USDC per signal (or per epoch) and auto-mirror your real entries/exits, fully spend-guarded. You earn real USDC; your feed ranks by proven accuracy.</p>
+ <div class="asg-fld"><label for="asg-title">Feed title</label>
+ <input class="asg-in" id="asg-title" maxlength="80" value="${esc(v('title', ''))}" placeholder="${esc(d?.feed?.title || 'My alpha')}" /></div>
+ <div class="asg-row2">
+ <div class="asg-fld"><label for="asg-ps">Price / signal (USDC)</label><input class="asg-in" id="asg-ps" type="number" min="0" step="0.05" value="${num(v('price_per_signal_usdc', 0.25))}" /></div>
+ <div class="asg-fld"><label for="asg-pe">Price / epoch (USDC)</label><input class="asg-in" id="asg-pe" type="number" min="0" step="0.5" value="${num(v('price_per_epoch_usdc', 0))}" /></div>
+ </div>
+ <div class="asg-fld"><label for="asg-epoch">Epoch length</label>
+ <select class="asg-sel" id="asg-epoch">
+ ${[['3600', '1 hour'], ['21600', '6 hours'], ['86400', '1 day'], ['604800', '1 week']].map(([s, l]) => `<option value="${s}" ${num(v('epoch_seconds', 86400)) === Number(s) ? 'selected' : ''}>${l}</option>`).join('')}
+ </select></div>
+ <div class="asg-checks">
+ <label class="asg-check"><input type="checkbox" id="asg-entries" ${v('emit_entries', true) !== false ? 'checked' : ''} /> Emit entries</label>
+ <label class="asg-check"><input type="checkbox" id="asg-exits" ${v('emit_exits', true) !== false ? 'checked' : ''} /> Emit exits</label>
+ <label class="asg-check"><input type="checkbox" id="asg-sizing" ${v('reveal_sizing', true) !== false ? 'checked' : ''} /> Reveal sizing</label>
+ </div>
+ <div class="asg-row2">
+ <div class="asg-fld"><label for="asg-conv">Min conviction (0–1)</label><input class="asg-in" id="asg-conv" type="number" min="0" max="1" step="0.1" value="${num(v('min_conviction', 0))}" /></div>
+ <div class="asg-fld"><label for="asg-vis">Visibility</label>
+ <select class="asg-sel" id="asg-vis"><option value="public" ${v('visibility', 'public') === 'public' ? 'selected' : ''}>Public (in directory)</option><option value="unlisted" ${v('visibility') === 'unlisted' ? 'selected' : ''}>Unlisted</option></select></div>
+ </div>
+ <div style="display:flex; gap:8px; flex-wrap:wrap;">
+ <button class="asg-btn primary" id="asg-publish">${feed ? 'Save changes' : 'Publish feed'}</button>
+ ${statusBtn}
+ </div>
+ <p class="asg-note" id="asg-pub-note"></p>
+ </div>`;
+ }
+
+ function wirePublish(d) {
+ const btn = panel.querySelector('#asg-publish');
+ if (btn) {
+ btn.addEventListener('click', async () => {
+ const note = panel.querySelector('#asg-pub-note');
+ note.className = 'asg-note';
+ btn.disabled = true;
+ try {
+ const res = await apiFetch('/api/signals/feeds', {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ agent_id: ctx.agentId, network: net(),
+ title: panel.querySelector('#asg-title').value,
+ price_per_signal_usdc: Number(panel.querySelector('#asg-ps').value) || 0,
+ price_per_epoch_usdc: Number(panel.querySelector('#asg-pe').value) || 0,
+ epoch_seconds: Number(panel.querySelector('#asg-epoch').value) || 86400,
+ emit_entries: panel.querySelector('#asg-entries').checked,
+ emit_exits: panel.querySelector('#asg-exits').checked,
+ reveal_sizing: panel.querySelector('#asg-sizing').checked,
+ min_conviction: Number(panel.querySelector('#asg-conv').value) || 0,
+ visibility: panel.querySelector('#asg-vis').value,
+ }),
+ });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(j.message || j.error || `HTTP ${res.status}`);
+ ctx.toast('Feed published');
+ load();
+ } catch (e) {
+ note.textContent = e.message;
+ note.classList.add('err');
+ btn.disabled = false;
+ }
+ });
+ }
+ const statusBtn = panel.querySelector('[data-feed-status]');
+ if (statusBtn && d?.feed) {
+ statusBtn.addEventListener('click', async () => {
+ statusBtn.disabled = true;
+ try {
+ await apiFetch('/api/signals/feeds', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: d.feed.id, status: statusBtn.dataset.feedStatus }) });
+ load();
+ } catch { statusBtn.disabled = false; }
+ });
+ }
+ }
+
+ // ── Subscriptions half ──────────────────────────────────────────────────────
+ function subsCard(subs) {
+ if (!subs.length) {
+ return `
+ <div class="asg-card">
+ <h3>Following</h3>
+ <div class="asg-empty">This agent isn't following any feeds yet.<br /><a href="/signals">Browse the marketplace →</a></div>
+ </div>`;
+ }
+ return `
+ <div class="asg-card">
+ <h3><span>Following</span><a class="asg-feedlink" href="/signals">Find more →</a></h3>
+ <p class="sub">Each subscription pays USDC from this agent's wallet and auto-mirrors within its spend policy. <b>Kill</b> halts pay + trade instantly.</p>
+ ${subs.map(subRow).join('')}
+ </div>`;
+ }
+
+ function subRow(s) {
+ const f = s.feed || {};
+ const modePill = s.killed ? `<span class="asg-pill killed">Killed</span>`
+ : s.status === 'paused' ? `<span class="asg-pill paused">Paused</span>`
+ : `<span class="asg-pill ${s.mode}">${s.mode}</span>`;
+ const price = s.billing === 'per_epoch'
+ ? `$${num(f.price_per_epoch_usdc)}/epoch`
+ : `$${num(f.price_per_signal_usdc)}/signal`;
+ return `
+ <div class="asg-sub ${s.killed ? 'killed' : ''}" data-sub="${s.id}">
+ <div class="asg-sub-top">
+ <div class="asg-sub-name"><a href="/signals/${encodeURIComponent(f.slug || '')}">${esc(f.title || 'Feed')}</a><div style="font-size:.7rem;color:var(--ink-dim,#888);margin-top:2px">by ${esc(f.publisher_name || '')}</div></div>
+ ${modePill}
+ </div>
+ <div class="asg-sub-meta">
+ <span><b>${price}</b></span>
+ <span>base <b>${num(s.base_sol)} SOL</b> · ${num(s.size_scaling)}×</span>
+ <span>max <b>${num(s.max_per_trade_sol)} SOL</b></span>
+ <span><b>${num(s.stats?.executed)}</b> fills</span>
+ <span>spent <b>$${num(s.stats?.usdc_spent).toFixed(2)}</b></span>
+ </div>
+ <div class="asg-sub-actions">
+ ${s.killed
+ ? `<button class="asg-btn sm primary" data-act="resume">Resume</button>`
+ : `<button class="asg-btn sm danger" data-act="kill">Kill now</button>`}
+ ${!s.killed && s.status === 'active' ? `<button class="asg-btn sm" data-act="pause">Pause</button>` : ''}
+ ${!s.killed && s.status === 'paused' ? `<button class="asg-btn sm" data-act="resume">Resume</button>` : ''}
+ <button class="asg-btn sm" data-act="sync">Sync now</button>
+ <button class="asg-btn sm" data-act="stop">Stop</button>
+ </div>
+ </div>`;
+ }
+
+ function wireSubs() {
+ panel.querySelectorAll('.asg-sub').forEach((row) => {
+ const id = row.dataset.sub;
+ row.querySelectorAll('[data-act]').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ const act = btn.dataset.act;
+ btn.disabled = true;
+ try {
+ let body;
+ if (act === 'kill') body = { id, killed: true };
+ else if (act === 'resume') body = { id, killed: false };
+ else if (act === 'pause') body = { id, status: 'paused' };
+ else if (act === 'sync') body = { id, action: 'sync' };
+ else if (act === 'stop') body = { id, status: 'stopped' };
+ const res = await apiFetch('/api/signals/subscribe', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(j.message || j.error || 'failed');
+ if (act === 'sync') ctx.toast(`Synced — ${j.delivered || 0} delivered`);
+ else if (act === 'kill') ctx.toast('Killed — no further pay or trade');
+ load();
+ } catch (e) {
+ ctx.toast(e.message || 'Action failed');
+ btn.disabled = false;
+ }
+ });
+ });
+ });
+ }
+
+ load();
+ const off = ctx.onNetworkChange ? ctx.onNetworkChange(() => load()) : null;
+
+ return {
+ destroy() { destroyed = true; if (typeof off === 'function') off(); },
+ onShow() { if (!destroyed) load(); },
+ };
+ },
+});
diff --git a/src/agent-wallet-hub/tabs/snipe.js b/src/agent-wallet-hub/tabs/snipe.js
index f0850049a..1141e4467 100644
--- a/src/agent-wallet-hub/tabs/snipe.js
+++ b/src/agent-wallet-hub/tabs/snipe.js
@@ -64,6 +64,9 @@ registerWalletTab({
<a class="awh-btn awh-btn--primary awh-snipe-cta" href="${escapeHtml(dashUrl)}">
Open the Sniper dashboard
</a>
+ <a class="awh-btn awh-snipe-cta" href="/terminal" style="margin-top:6px">
+ Trade live in Mission Control
+ </a>
</div>
</div>
`;
diff --git a/src/arena/arena.css b/src/arena/arena.css
new file mode 100644
index 000000000..12c76dda0
--- /dev/null
+++ b/src/arena/arena.css
@@ -0,0 +1,844 @@
+/* The Arena — Social Trading Arena. Tournament list, live competition, results.
+ * Token-driven (public/tokens.css via nav.css), dark-first, responsive, a11y, and
+ * reduced-motion friendly. No hardcoded palette — everything resolves to a var. */
+
+.arena {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: clamp(1rem, 3vw, 2.2rem) clamp(0.9rem, 3vw, 1.6rem) 5rem;
+ min-height: 70vh;
+}
+
+/* ── Hero ─────────────────────────────────────────────────────────────── */
+.arena-hero {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: var(--space-md, 1rem);
+ margin-bottom: var(--space-lg, 1.6rem);
+}
+.arena-hero h1 {
+ font-size: clamp(1.7rem, 4vw, 2.6rem);
+ line-height: 1.05;
+ letter-spacing: -0.02em;
+ margin: 0 0 0.35rem;
+}
+.arena-hero .lede {
+ color: var(--text-2, #a8a8a8);
+ max-width: 56ch;
+ margin: 0;
+ font-size: var(--text-ui, 0.9rem);
+ line-height: 1.5;
+}
+.arena-hero .hero-actions {
+ display: flex;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+}
+
+/* ── Buttons ──────────────────────────────────────────────────────────── */
+.btn {
+ appearance: none;
+ border: 1px solid var(--border, #2a2a2a);
+ background: var(--surface-2, #181818);
+ color: var(--ink, #f6f6f6);
+ font: inherit;
+ font-size: var(--text-md, 0.82rem);
+ font-weight: 600;
+ padding: 0.55rem 0.95rem;
+ border-radius: var(--radius-md, 10px);
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.45rem;
+ transition: background 0.16s ease, border-color 0.16s ease, transform 0.12s ease;
+ text-decoration: none;
+ white-space: nowrap;
+}
+.btn:hover {
+ background: var(--surface-3, #202020);
+ border-color: var(--border-strong, #3a3a3a);
+}
+.btn:active {
+ transform: translateY(1px);
+}
+.btn:focus-visible {
+ outline: 2px solid var(--accent, #fff);
+ outline-offset: 2px;
+}
+.btn-primary {
+ background: var(--ink, #f6f6f6);
+ color: var(--bg, #050505);
+ border-color: var(--ink, #f6f6f6);
+}
+.btn-primary:hover {
+ background: #fff;
+ filter: brightness(1.02);
+}
+.btn-primary:disabled,
+.btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+.btn-ghost {
+ background: transparent;
+}
+
+/* ── Tabs ─────────────────────────────────────────────────────────────── */
+.arena-tabs {
+ display: flex;
+ gap: 0.25rem;
+ border-bottom: 1px solid var(--border, #2a2a2a);
+ margin-bottom: var(--space-md, 1rem);
+ overflow-x: auto;
+ scrollbar-width: none;
+}
+.arena-tabs::-webkit-scrollbar {
+ display: none;
+}
+.arena-tab {
+ appearance: none;
+ background: none;
+ border: none;
+ color: var(--text-2, #a8a8a8);
+ font: inherit;
+ font-size: var(--text-ui, 0.9rem);
+ font-weight: 600;
+ padding: 0.6rem 0.9rem;
+ cursor: pointer;
+ position: relative;
+ border-bottom: 2px solid transparent;
+ white-space: nowrap;
+ transition: color 0.15s ease;
+}
+.arena-tab:hover {
+ color: var(--ink, #f6f6f6);
+}
+.arena-tab[aria-selected='true'] {
+ color: var(--ink, #f6f6f6);
+ border-bottom-color: var(--ink, #f6f6f6);
+}
+.arena-tab .count {
+ font-size: var(--text-2xs, 0.69rem);
+ color: var(--text-3, #777);
+ margin-left: 0.3rem;
+}
+
+/* ── Tournament card grid ─────────────────────────────────────────────── */
+.tourn-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
+ gap: var(--space-md, 1rem);
+}
+.tourn-card {
+ border: 1px solid var(--border, #2a2a2a);
+ background: var(--surface-1, #111);
+ border-radius: var(--radius-lg, 16px);
+ padding: 1.1rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.7rem;
+ cursor: pointer;
+ transition: border-color 0.18s ease, transform 0.18s ease, box-shadow 0.18s ease;
+ text-align: left;
+ color: inherit;
+ font: inherit;
+}
+.tourn-card:hover {
+ border-color: var(--border-strong, #3a3a3a);
+ transform: translateY(-2px);
+ box-shadow: var(--shadow, 0 10px 40px rgba(0, 0, 0, 0.4));
+}
+.tourn-card:focus-visible {
+ outline: 2px solid var(--accent, #fff);
+ outline-offset: 2px;
+}
+.tourn-card .card-top {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.5rem;
+}
+.tourn-card h3 {
+ margin: 0;
+ font-size: var(--text-base, 1rem);
+ line-height: 1.2;
+ letter-spacing: -0.01em;
+}
+.tourn-card .desc {
+ color: var(--text-2, #a8a8a8);
+ font-size: var(--text-md, 0.82rem);
+ line-height: 1.45;
+ margin: 0;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.tourn-card .card-meta {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.4rem 0.9rem;
+ margin-top: auto;
+ font-size: var(--text-sm, 0.76rem);
+ color: var(--text-2, #a8a8a8);
+}
+.tourn-card .card-meta b {
+ color: var(--ink, #f6f6f6);
+ font-weight: 600;
+}
+
+/* ── Status / badges ──────────────────────────────────────────────────── */
+.badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3rem;
+ font-size: var(--text-2xs, 0.69rem);
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ padding: 0.2rem 0.5rem;
+ border-radius: 999px;
+ border: 1px solid var(--border, #2a2a2a);
+ color: var(--text-2, #a8a8a8);
+ white-space: nowrap;
+}
+.badge .dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: currentColor;
+}
+.badge-live {
+ color: var(--success, #34d399);
+ border-color: color-mix(in srgb, var(--success, #34d399) 40%, transparent);
+ background: color-mix(in srgb, var(--success, #34d399) 12%, transparent);
+}
+.badge-live .dot {
+ animation: arena-pulse 1.4s ease-in-out infinite;
+}
+.badge-upcoming {
+ color: var(--accent-2, #7c8bff);
+ border-color: color-mix(in srgb, var(--accent-2, #7c8bff) 40%, transparent);
+}
+.badge-finished {
+ color: var(--text-3, #888);
+}
+.badge-practice {
+ color: var(--warn, #fbbf24);
+ border-color: color-mix(in srgb, var(--warn, #fbbf24) 40%, transparent);
+}
+.badge-verified {
+ color: var(--success, #34d399);
+ border-color: color-mix(in srgb, var(--success, #34d399) 40%, transparent);
+}
+.badge-warn {
+ color: var(--danger, #f87171);
+ border-color: color-mix(in srgb, var(--danger, #f87171) 40%, transparent);
+}
+@keyframes arena-pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ transform: scale(1);
+ }
+ 50% {
+ opacity: 0.4;
+ transform: scale(0.7);
+ }
+}
+
+.prize-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ font-weight: 700;
+ color: var(--ink, #f6f6f6);
+ background: linear-gradient(
+ 120deg,
+ color-mix(in srgb, var(--warn, #fbbf24) 22%, transparent),
+ color-mix(in srgb, var(--accent-2, #7c8bff) 18%, transparent)
+ );
+ border: 1px solid color-mix(in srgb, var(--warn, #fbbf24) 35%, transparent);
+ padding: 0.22rem 0.55rem;
+ border-radius: 999px;
+ font-size: var(--text-sm, 0.76rem);
+}
+
+/* ── Detail view ──────────────────────────────────────────────────────── */
+.arena-back {
+ background: none;
+ border: none;
+ color: var(--text-2, #a8a8a8);
+ font: inherit;
+ font-size: var(--text-md, 0.82rem);
+ cursor: pointer;
+ padding: 0.3rem 0;
+ margin-bottom: 0.8rem;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+}
+.arena-back:hover {
+ color: var(--ink, #f6f6f6);
+}
+
+.detail-head {
+ display: grid;
+ grid-template-columns: 1fr;
+ gap: var(--space-md, 1rem);
+ margin-bottom: var(--space-lg, 1.6rem);
+}
+.detail-head .title-row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.6rem;
+}
+.detail-head h1 {
+ margin: 0;
+ font-size: clamp(1.5rem, 3.5vw, 2.2rem);
+ letter-spacing: -0.02em;
+}
+.detail-head .desc {
+ color: var(--text-2, #a8a8a8);
+ margin: 0;
+ max-width: 70ch;
+ line-height: 1.5;
+}
+.detail-stats {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem 1.6rem;
+}
+.stat {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+}
+.stat .k {
+ font-size: var(--text-2xs, 0.69rem);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--text-3, #888);
+}
+.stat .v {
+ font-size: var(--text-base, 1rem);
+ font-weight: 700;
+ font-variant-numeric: tabular-nums;
+}
+.countdown {
+ font-variant-numeric: tabular-nums;
+}
+
+/* Two-column: spotlight + board on wide screens */
+.detail-body {
+ display: grid;
+ grid-template-columns: 320px 1fr;
+ gap: var(--space-lg, 1.6rem);
+ align-items: start;
+}
+@media (max-width: 860px) {
+ .detail-body {
+ grid-template-columns: 1fr;
+ }
+}
+
+.spotlight {
+ position: sticky;
+ top: 1rem;
+ border: 1px solid var(--border, #2a2a2a);
+ border-radius: var(--radius-lg, 16px);
+ background: radial-gradient(120% 80% at 50% 0%, var(--surface-2, #181818), var(--surface-1, #111));
+ padding: 1rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.6rem;
+}
+.spotlight .crown {
+ font-size: var(--text-2xs, 0.69rem);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--warn, #fbbf24);
+ font-weight: 700;
+}
+.spotlight agent-3d,
+.spotlight .spot-fallback {
+ width: 100%;
+ height: 280px;
+ border-radius: var(--radius-md, 10px);
+ overflow: hidden;
+ background: var(--surface-0, #0a0a0a);
+ display: block;
+}
+.spotlight .spot-fallback {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--text-3, #888);
+}
+.spotlight .spot-fallback img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.spotlight .spot-name {
+ font-weight: 700;
+ font-size: var(--text-base, 1rem);
+ display: flex;
+ align-items: center;
+ gap: 0.4rem;
+}
+.spotlight .spot-metric {
+ color: var(--text-2, #a8a8a8);
+ font-size: var(--text-md, 0.82rem);
+ font-variant-numeric: tabular-nums;
+}
+
+/* ── Ranking board ────────────────────────────────────────────────────── */
+.board {
+ display: flex;
+ flex-direction: column;
+ gap: 0.4rem;
+ position: relative;
+}
+.board-head,
+.row {
+ display: grid;
+ grid-template-columns: 2.2rem 1fr 5.5rem 5rem 4rem;
+ align-items: center;
+ gap: 0.6rem;
+}
+.board-head {
+ padding: 0 0.8rem 0.4rem;
+ font-size: var(--text-2xs, 0.69rem);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--text-3, #888);
+}
+.board-head .num,
+.row .num {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+.row {
+ border: 1px solid var(--border, #2a2a2a);
+ background: var(--surface-1, #111);
+ border-radius: var(--radius-md, 10px);
+ padding: 0.6rem 0.8rem;
+ transition: transform 0.45s cubic-bezier(0.2, 0.9, 0.25, 1), border-color 0.2s ease, background 0.2s ease;
+ cursor: pointer;
+}
+.row:hover {
+ border-color: var(--border-strong, #3a3a3a);
+ background: var(--surface-2, #181818);
+}
+.row:focus-visible {
+ outline: 2px solid var(--accent, #fff);
+ outline-offset: 1px;
+}
+.row.rank-1 {
+ border-color: color-mix(in srgb, var(--warn, #fbbf24) 45%, transparent);
+ background: linear-gradient(90deg, color-mix(in srgb, var(--warn, #fbbf24) 8%, transparent), var(--surface-1, #111));
+}
+.row.flash {
+ animation: arena-flash 0.7s ease;
+}
+@keyframes arena-flash {
+ 0% {
+ background: color-mix(in srgb, var(--success, #34d399) 22%, var(--surface-1, #111));
+ }
+ 100% {
+ background: var(--surface-1, #111);
+ }
+}
+.row .rank {
+ font-weight: 800;
+ font-variant-numeric: tabular-nums;
+ color: var(--text-2, #a8a8a8);
+ text-align: center;
+}
+.row.rank-1 .rank {
+ color: var(--warn, #fbbf24);
+}
+.row .who {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ min-width: 0;
+}
+.row .who img,
+.row .who .ph {
+ width: 34px;
+ height: 34px;
+ border-radius: 50%;
+ object-fit: cover;
+ background: var(--surface-3, #202020);
+ flex-shrink: 0;
+}
+.row .who .ph {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-weight: 700;
+ color: var(--text-2, #a8a8a8);
+ font-size: var(--text-md, 0.82rem);
+}
+.row .who .nm {
+ min-width: 0;
+}
+.row .who .nm .name {
+ font-weight: 600;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: flex;
+ align-items: center;
+ gap: 0.35rem;
+}
+.row .who .nm .sub {
+ font-size: var(--text-2xs, 0.69rem);
+ color: var(--text-3, #888);
+ display: flex;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+}
+.row .score {
+ font-weight: 700;
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+}
+.row .pnl-pos {
+ color: var(--success, #34d399);
+}
+.row .pnl-neg {
+ color: var(--danger, #f87171);
+}
+.row .prize {
+ text-align: right;
+ font-size: var(--text-sm, 0.76rem);
+ color: var(--warn, #fbbf24);
+ font-weight: 700;
+ font-variant-numeric: tabular-nums;
+}
+.row .mini-badge {
+ font-size: 0.6rem;
+ padding: 0.05rem 0.3rem;
+}
+
+/* Expanded trade proof under a row */
+.row-proof {
+ grid-column: 1 / -1;
+ margin-top: 0.5rem;
+ padding-top: 0.5rem;
+ border-top: 1px dashed var(--border, #2a2a2a);
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.4rem;
+}
+.proof-pill {
+ font-size: var(--text-2xs, 0.69rem);
+ border: 1px solid var(--border, #2a2a2a);
+ border-radius: 999px;
+ padding: 0.18rem 0.5rem;
+ color: var(--text-2, #a8a8a8);
+ text-decoration: none;
+ display: inline-flex;
+ gap: 0.3rem;
+ font-variant-numeric: tabular-nums;
+}
+.proof-pill:hover {
+ border-color: var(--border-strong, #3a3a3a);
+ color: var(--ink, #f6f6f6);
+}
+
+/* ── Trades ticker ────────────────────────────────────────────────────── */
+.ticker {
+ margin-top: var(--space-lg, 1.6rem);
+ border: 1px solid var(--border, #2a2a2a);
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, #111);
+ overflow: hidden;
+}
+.ticker h4 {
+ margin: 0;
+ padding: 0.6rem 0.8rem;
+ font-size: var(--text-2xs, 0.69rem);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--text-3, #888);
+ border-bottom: 1px solid var(--border, #2a2a2a);
+}
+.ticker-list {
+ display: flex;
+ flex-direction: column;
+ max-height: 240px;
+ overflow-y: auto;
+}
+.ticker-item {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ padding: 0.45rem 0.8rem;
+ font-size: var(--text-sm, 0.76rem);
+ border-bottom: 1px solid var(--border, #2a2a2a);
+ font-variant-numeric: tabular-nums;
+}
+.ticker-item:last-child {
+ border-bottom: none;
+}
+.ticker-item .tk-agent {
+ font-weight: 600;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.ticker-item .tk-mint {
+ color: var(--text-3, #888);
+}
+.ticker-item .tk-pnl {
+ margin-left: auto;
+ font-weight: 700;
+}
+
+/* ── Results / settlement ─────────────────────────────────────────────── */
+.results-banner {
+ border: 1px solid var(--border, #2a2a2a);
+ border-radius: var(--radius-md, 10px);
+ padding: 0.9rem 1rem;
+ background: var(--surface-1, #111);
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.6rem 1rem;
+ margin-bottom: var(--space-md, 1rem);
+}
+.results-banner .att-link {
+ color: var(--accent-2, #7c8bff);
+ font-weight: 600;
+ text-decoration: none;
+}
+.results-banner .att-link:hover {
+ text-decoration: underline;
+}
+.settle-note {
+ font-size: var(--text-sm, 0.76rem);
+ color: var(--text-2, #a8a8a8);
+}
+.settle-note code {
+ background: var(--surface-3, #202020);
+ padding: 0.05rem 0.3rem;
+ border-radius: 4px;
+ font-size: 0.92em;
+}
+
+/* ── States: loading / empty / error ──────────────────────────────────── */
+.skeleton {
+ background: linear-gradient(90deg, var(--surface-1, #111) 25%, var(--surface-2, #181818) 50%, var(--surface-1, #111) 75%);
+ background-size: 200% 100%;
+ animation: arena-shimmer 1.4s ease infinite;
+ border-radius: var(--radius-md, 10px);
+}
+@keyframes arena-shimmer {
+ 0% {
+ background-position: 200% 0;
+ }
+ 100% {
+ background-position: -200% 0;
+ }
+}
+.sk-card {
+ height: 168px;
+}
+.state {
+ text-align: center;
+ padding: clamp(2rem, 8vw, 4.5rem) 1rem;
+ border: 1px dashed var(--border, #2a2a2a);
+ border-radius: var(--radius-lg, 16px);
+ color: var(--text-2, #a8a8a8);
+}
+.state h3 {
+ margin: 0 0 0.4rem;
+ color: var(--ink, #f6f6f6);
+ font-size: var(--text-base, 1rem);
+}
+.state p {
+ margin: 0 auto 1rem;
+ max-width: 46ch;
+ line-height: 1.5;
+ font-size: var(--text-md, 0.82rem);
+}
+
+/* ── Modal ────────────────────────────────────────────────────────────── */
+.arena-modal {
+ position: fixed;
+ inset: 0;
+ background: color-mix(in srgb, #000 62%, transparent);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 1rem;
+ z-index: 1000;
+ animation: arena-fade 0.18s ease;
+}
+@keyframes arena-fade {
+ from {
+ opacity: 0;
+ }
+}
+.arena-modal .sheet {
+ background: var(--surface-1, #111);
+ border: 1px solid var(--border, #2a2a2a);
+ border-radius: var(--radius-lg, 16px);
+ width: min(560px, 100%);
+ max-height: 90vh;
+ overflow-y: auto;
+ padding: 1.3rem;
+ box-shadow: var(--shadow, 0 10px 40px rgba(0, 0, 0, 0.5));
+}
+.arena-modal h2 {
+ margin: 0 0 0.3rem;
+ font-size: var(--text-lg, 1.1rem);
+}
+.arena-modal .sub {
+ color: var(--text-2, #a8a8a8);
+ font-size: var(--text-md, 0.82rem);
+ margin: 0 0 1rem;
+}
+.field {
+ display: flex;
+ flex-direction: column;
+ gap: 0.3rem;
+ margin-bottom: 0.85rem;
+}
+.field label {
+ font-size: var(--text-sm, 0.76rem);
+ font-weight: 600;
+ color: var(--text-2, #a8a8a8);
+}
+.field input,
+.field select,
+.field textarea {
+ background: var(--surface-0, #0a0a0a);
+ border: 1px solid var(--border, #2a2a2a);
+ border-radius: var(--radius-sm, 6px);
+ color: var(--ink, #f6f6f6);
+ font: inherit;
+ font-size: var(--text-md, 0.82rem);
+ padding: 0.5rem 0.6rem;
+}
+.field input:focus,
+.field select:focus,
+.field textarea:focus {
+ outline: none;
+ border-color: var(--accent, #fff);
+}
+.field .hint {
+ font-size: var(--text-2xs, 0.69rem);
+ color: var(--text-3, #888);
+}
+.field-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.6rem;
+}
+.agent-pick {
+ display: flex;
+ flex-direction: column;
+ gap: 0.4rem;
+ max-height: 260px;
+ overflow-y: auto;
+}
+.agent-opt {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ border: 1px solid var(--border, #2a2a2a);
+ border-radius: var(--radius-md, 10px);
+ padding: 0.5rem 0.6rem;
+ cursor: pointer;
+ background: var(--surface-0, #0a0a0a);
+ text-align: left;
+ color: inherit;
+ font: inherit;
+}
+.agent-opt:hover {
+ border-color: var(--border-strong, #3a3a3a);
+}
+.agent-opt[aria-pressed='true'] {
+ border-color: var(--accent, #fff);
+ background: var(--surface-2, #181818);
+}
+.agent-opt img,
+.agent-opt .ph {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ object-fit: cover;
+ background: var(--surface-3, #202020);
+}
+.modal-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.5rem;
+ margin-top: 1rem;
+}
+.form-error {
+ color: var(--danger, #f87171);
+ font-size: var(--text-sm, 0.76rem);
+ margin: 0.4rem 0 0;
+ min-height: 1em;
+}
+
+/* Toast */
+.arena-toast {
+ position: fixed;
+ bottom: 1.2rem;
+ left: 50%;
+ transform: translateX(-50%);
+ background: var(--surface-2, #181818);
+ border: 1px solid var(--border-strong, #3a3a3a);
+ color: var(--ink, #f6f6f6);
+ padding: 0.65rem 1rem;
+ border-radius: var(--radius-md, 10px);
+ font-size: var(--text-md, 0.82rem);
+ z-index: 1100;
+ box-shadow: var(--shadow, 0 10px 40px rgba(0, 0, 0, 0.5));
+ animation: arena-toast-in 0.2s ease;
+}
+.arena-toast.err {
+ border-color: var(--danger, #f87171);
+}
+@keyframes arena-toast-in {
+ from {
+ opacity: 0;
+ transform: translate(-50%, 8px);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .row,
+ .tourn-card,
+ .btn,
+ .badge-live .dot,
+ .skeleton,
+ .row.flash,
+ .arena-modal,
+ .arena-toast {
+ animation: none !important;
+ transition: none !important;
+ }
+}
+
+@media (max-width: 560px) {
+ .board-head,
+ .row {
+ grid-template-columns: 1.8rem 1fr 4.4rem 3.6rem;
+ }
+ .board-head .col-prize,
+ .row .prize {
+ display: none;
+ }
+}
diff --git a/src/arena/arena.js b/src/arena/arena.js
new file mode 100644
index 000000000..73ee3b1ea
--- /dev/null
+++ b/src/arena/arena.js
@@ -0,0 +1,948 @@
+/**
+ * The Arena — Social Trading Arena front-end.
+ *
+ * A single-page surface with two views, hash-routed:
+ * #/ → tournament list (Live / Upcoming / Finished tabs + create)
+ * #/t/<uuid> → live competition view (spotlight 3D avatar, animated ranking
+ * board, trades ticker, join) → results (attestation + prize
+ * distribution) once finished.
+ *
+ * Everything is real: it reads /api/tournaments[/...] and live-streams rank changes
+ * over SSE. No mock data, no fake loading. Every state (loading, empty, error,
+ * populated) is designed, and the whole thing is keyboard- and reduced-motion
+ * friendly.
+ */
+
+const root = document.getElementById('arena');
+const NETWORK = 'mainnet';
+
+// ── tiny DOM + format helpers ─────────────────────────────────────────────
+const h = (tag, attrs = {}, ...kids) => {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'html') node.innerHTML = v;
+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
+ else if (k === 'dataset') Object.assign(node.dataset, v);
+ else node.setAttribute(k, v === true ? '' : String(v));
+ }
+ for (const kid of kids.flat()) {
+ if (kid == null || kid === false) continue;
+ node.append(kid.nodeType ? kid : document.createTextNode(String(kid)));
+ }
+ return node;
+};
+const esc = (s) => String(s ?? '');
+const fmtSol = (n) => (n == null ? '—' : `${n > 0 ? '+' : ''}${Number(n).toFixed(n && Math.abs(n) < 1 ? 3 : 2)} ◎`);
+const fmtPct = (n) => (n == null ? '—' : `${n > 0 ? '+' : ''}${Number(n).toFixed(1)}%`);
+const fmtThree = (n) => {
+ const v = Number(n || 0);
+ if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(2)}M`;
+ if (v >= 1000) return `${(v / 1000).toFixed(1)}K`;
+ return v.toLocaleString(undefined, { maximumFractionDigits: 2 });
+};
+const initialsOf = (name) =>
+ esc(name)
+ .split(/\s+/)
+ .slice(0, 2)
+ .map((w) => w[0] || '')
+ .join('')
+ .toUpperCase() || '··';
+
+async function fetchJSON(url, opts) {
+ const res = await fetch(url, { credentials: 'include', ...opts });
+ let body = null;
+ try {
+ body = await res.json();
+ } catch {
+ /* non-JSON */
+ }
+ if (!res.ok) {
+ const err = new Error(body?.error_description || body?.error || `HTTP ${res.status}`);
+ err.status = res.status;
+ err.code = body?.error;
+ throw err;
+ }
+ return body;
+}
+
+function toast(msg, isErr = false) {
+ document.querySelectorAll('.arena-toast').forEach((t) => t.remove());
+ const t = h('div', { class: `arena-toast${isErr ? ' err' : ''}`, role: 'status' }, msg);
+ document.body.append(t);
+ setTimeout(() => t.remove(), 4200);
+}
+
+// ── countdown ──────────────────────────────────────────────────────────────
+function relTime(iso, now = Date.now()) {
+ const d = new Date(iso).getTime() - now;
+ const abs = Math.abs(d);
+ const m = Math.floor(abs / 60000);
+ const hrs = Math.floor(m / 60);
+ const days = Math.floor(hrs / 24);
+ let label;
+ if (days >= 1) label = `${days}d ${hrs % 24}h`;
+ else if (hrs >= 1) label = `${hrs}h ${m % 60}m`;
+ else label = `${m}m ${Math.floor((abs % 60000) / 1000)}s`;
+ return { label, future: d > 0 };
+}
+
+let countdownTimer = null;
+function startCountdowns() {
+ stopCountdowns();
+ const tick = () => {
+ document.querySelectorAll('[data-countdown]').forEach((node) => {
+ const { label, future } = relTime(node.dataset.countdown);
+ const prefix = node.dataset.prefix || '';
+ node.textContent = future ? `${prefix}${label}` : node.dataset.doneLabel || 'ended';
+ });
+ };
+ tick();
+ countdownTimer = setInterval(tick, 1000);
+}
+function stopCountdowns() {
+ if (countdownTimer) clearInterval(countdownTimer);
+ countdownTimer = null;
+}
+
+// ── status helpers ───────────────────────────────────────────────────────
+function statusBadge(t) {
+ const d = t.derived_status || t.status;
+ if (d === 'live') return h('span', { class: 'badge badge-live' }, h('span', { class: 'dot' }), 'Live');
+ if (d === 'upcoming' || d === 'draft')
+ return h('span', { class: 'badge badge-upcoming' }, h('span', { class: 'dot' }), 'Upcoming');
+ return h('span', { class: 'badge badge-finished' }, h('span', { class: 'dot' }), prettyFinished(d));
+}
+function prettyFinished(d) {
+ if (d === 'settled') return 'Settled';
+ if (d === 'closed') return 'Final';
+ if (d === 'cancelled') return 'Cancelled';
+ return 'Finished';
+}
+const scoringLabel = { score: 'TraderScore', realized_pnl: 'Realized P&L', roi_pct: 'ROI %' };
+
+// ───────────────────────────────────────────────────────────────────────────
+// LIST VIEW
+// ───────────────────────────────────────────────────────────────────────────
+let listCache = null;
+const listState = { tab: 'live' };
+
+async function renderList() {
+ stopStream();
+ root.replaceChildren(
+ h(
+ 'section',
+ { class: 'arena-hero' },
+ h(
+ 'div',
+ {},
+ h('h1', {}, 'The Arena'),
+ h(
+ 'p',
+ { class: 'lede' },
+ 'Time-boxed PvP trading tournaments where AI agents compete on real, verified pump.fun P&L. ',
+ 'Ranked live, settled and attested on-chain, with $THREE prizes for the winners.',
+ ),
+ ),
+ h(
+ 'div',
+ { class: 'hero-actions' },
+ h('a', { class: 'btn btn-ghost', href: '/leaderboard' }, 'Leaderboard'),
+ h('button', { class: 'btn btn-primary', type: 'button', onclick: openCreateModal }, '+ Create tournament'),
+ ),
+ ),
+ );
+
+ const tabsBar = h('div', { class: 'arena-tabs', role: 'tablist', 'aria-label': 'Tournament phase' });
+ root.append(tabsBar);
+ const body = h('div', { id: 'list-body' });
+ root.append(body);
+
+ // Loading skeletons.
+ body.replaceChildren(
+ h(
+ 'div',
+ { class: 'tourn-grid' },
+ ...Array.from({ length: 6 }, () => h('div', { class: 'skeleton sk-card' })),
+ ),
+ );
+
+ let data;
+ try {
+ data = await fetchJSON(`/api/tournaments?network=${NETWORK}`);
+ listCache = data.tournaments || [];
+ } catch (err) {
+ body.replaceChildren(
+ h(
+ 'div',
+ { class: 'state' },
+ h('h3', {}, 'Could not load tournaments'),
+ h('p', {}, err.message || 'Something went wrong reaching the Arena.'),
+ h('button', { class: 'btn', type: 'button', onclick: renderList }, 'Retry'),
+ ),
+ );
+ return;
+ }
+
+ const groups = {
+ live: listCache.filter((t) => t.phase === 'live'),
+ upcoming: listCache.filter((t) => t.phase === 'upcoming'),
+ finished: listCache.filter((t) => t.phase === 'finished'),
+ };
+ // If the preferred tab is empty, fall back to the first non-empty one.
+ if (!groups[listState.tab].length) {
+ listState.tab = ['live', 'upcoming', 'finished'].find((k) => groups[k].length) || 'live';
+ }
+
+ for (const key of ['live', 'upcoming', 'finished']) {
+ const label = key[0].toUpperCase() + key.slice(1);
+ tabsBar.append(
+ h(
+ 'button',
+ {
+ class: 'arena-tab',
+ role: 'tab',
+ type: 'button',
+ 'aria-selected': key === listState.tab ? 'true' : 'false',
+ onclick: () => {
+ listState.tab = key;
+ paintGroup(body, groups);
+ tabsBar.querySelectorAll('.arena-tab').forEach((b, i) => {
+ b.setAttribute('aria-selected', ['live', 'upcoming', 'finished'][i] === key ? 'true' : 'false');
+ });
+ },
+ },
+ label,
+ h('span', { class: 'count' }, String(groups[key].length)),
+ ),
+ );
+ }
+
+ paintGroup(body, groups);
+ startCountdowns();
+}
+
+function paintGroup(body, groups) {
+ const items = groups[listState.tab];
+ if (!items.length) {
+ body.replaceChildren(emptyForTab(listState.tab));
+ return;
+ }
+ body.replaceChildren(h('div', { class: 'tourn-grid' }, ...items.map(tournamentCard)));
+ startCountdowns();
+}
+
+function emptyForTab(tab) {
+ const copy = {
+ live: ['No live tournaments right now', 'Create one, or check the upcoming bracket — the next competition could be yours.'],
+ upcoming: ['Nothing scheduled yet', 'Be the first to host a competition. Set a window, a prize pool in $THREE, and open the gates.'],
+ finished: ['No finished tournaments yet', 'Completed competitions and their on-chain attested results will appear here.'],
+ }[tab];
+ return h(
+ 'div',
+ { class: 'state' },
+ h('h3', {}, copy[0]),
+ h('p', {}, copy[1]),
+ h('button', { class: 'btn btn-primary', type: 'button', onclick: openCreateModal }, '+ Create tournament'),
+ );
+}
+
+function tournamentCard(t) {
+ const prize =
+ Number(t.prize_pool_three) > 0
+ ? h('span', { class: 'prize-chip' }, '🏆', `${fmtThree(t.prize_pool_three)} $THREE`)
+ : t.bracket === 'practice'
+ ? h('span', { class: 'badge badge-practice' }, 'Practice')
+ : null;
+
+ const when =
+ t.phase === 'upcoming'
+ ? h('span', {}, 'Starts ', h('b', { dataset: { countdown: t.starts_at, prefix: 'in ' } }, '…'))
+ : t.phase === 'live'
+ ? h('span', {}, 'Ends ', h('b', { dataset: { countdown: t.ends_at, prefix: 'in ' } }, '…'))
+ : h('span', {}, 'Ended');
+
+ return h(
+ 'button',
+ {
+ class: 'tourn-card',
+ type: 'button',
+ onclick: () => {
+ location.hash = `#/t/${t.id}`;
+ },
+ },
+ h('div', { class: 'card-top' }, statusBadge(t), prize),
+ h('h3', {}, t.name),
+ t.description ? h('p', { class: 'desc' }, t.description) : null,
+ h(
+ 'div',
+ { class: 'card-meta' },
+ h('span', {}, h('b', {}, String(t.entrant_count)), ' entrants'),
+ h('span', {}, 'Scored on ', h('b', {}, scoringLabel[t.scoring] || t.scoring)),
+ when,
+ ),
+ );
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// DETAIL VIEW
+// ───────────────────────────────────────────────────────────────────────────
+let stream = null;
+let detailId = null;
+let lastRanks = new Map();
+let expandedAgent = null;
+
+function stopStream() {
+ if (stream) {
+ stream.close();
+ stream = null;
+ }
+ stopCountdowns();
+}
+
+async function renderDetail(id) {
+ stopStream();
+ detailId = id;
+ lastRanks = new Map();
+ root.replaceChildren(
+ h('button', { class: 'arena-back', type: 'button', onclick: () => (location.hash = '#/') }, '← All tournaments'),
+ h('div', { class: 'skeleton', style: 'height:120px;margin-bottom:1.2rem' }),
+ h('div', { class: 'skeleton', style: 'height:340px' }),
+ );
+
+ let data;
+ try {
+ data = await fetchJSON(`/api/tournaments/${id}`);
+ } catch (err) {
+ root.replaceChildren(
+ h('button', { class: 'arena-back', type: 'button', onclick: () => (location.hash = '#/') }, '← All tournaments'),
+ h(
+ 'div',
+ { class: 'state' },
+ h('h3', {}, err.status === 404 ? 'Tournament not found' : 'Could not load this tournament'),
+ h('p', {}, err.message || ''),
+ h('button', { class: 'btn', type: 'button', onclick: () => renderDetail(id) }, 'Retry'),
+ ),
+ );
+ return;
+ }
+
+ paintDetail(data);
+ const phase = phaseFromStatus(data.derived_status);
+ if (phase !== 'finished') connectStream(id);
+ startCountdowns();
+}
+
+function phaseFromStatus(d) {
+ if (d === 'live') return 'live';
+ if (d === 'upcoming' || d === 'draft') return 'upcoming';
+ return 'finished';
+}
+
+function paintDetail(data) {
+ const t = data.tournament;
+ const phase = phaseFromStatus(data.derived_status);
+ const standings = data.standings || [];
+ const leader = standings.find((s) => s.rank === 1);
+
+ // Cache the full board so the SSE stream can merge lean live rows into it and so
+ // row-proof toggles can re-render without a refetch.
+ currentStandings = standings;
+ currentTournament = t;
+ currentDerived = data.derived_status;
+ lastRanks = new Map(standings.filter((s) => s.rank != null).map((s) => [s.agent_id, s.rank]));
+
+ const head = h(
+ 'div',
+ { class: 'detail-head' },
+ h(
+ 'div',
+ { class: 'title-row' },
+ statusBadge({ derived_status: data.derived_status }),
+ h('h1', {}, t.name),
+ t.bracket === 'practice' ? h('span', { class: 'badge badge-practice' }, 'Practice — no prizes') : null,
+ ),
+ t.description ? h('p', { class: 'desc' }, t.description) : null,
+ detailStats(data, phase),
+ h(
+ 'div',
+ { class: 'hero-actions' },
+ phase !== 'finished'
+ ? h('button', { class: 'btn btn-primary', type: 'button', onclick: () => openJoinModal(t) }, 'Join with your agent')
+ : null,
+ t.attestation_url
+ ? h('a', { class: 'btn btn-ghost', href: t.attestation_url, target: '_blank', rel: 'noopener' }, '⛓ On-chain result')
+ : null,
+ ),
+ );
+
+ const board = h('div', { class: 'board', id: 'board' });
+ renderBoard(board, standings, t, phase);
+
+ const spotlight = h(
+ 'aside',
+ { class: 'spotlight', id: 'spotlight', dataset: leader ? { leader: leader.agent_id } : {} },
+ h('div', { class: 'crown' }, phase === 'finished' ? '🏆 Champion' : '🏆 Current leader'),
+ leaderVisual(leader),
+ );
+
+ const body = h(
+ 'div',
+ { class: 'detail-body' },
+ spotlight,
+ h(
+ 'div',
+ {},
+ phase === 'finished' ? resultsBanner(data) : null,
+ h(
+ 'div',
+ { class: 'board-head' },
+ h('span', {}, '#'),
+ h('span', {}, 'Agent'),
+ h('span', { class: 'num' }, scoringLabel[t.scoring] || 'Score'),
+ h('span', { class: 'num' }, 'P&L'),
+ h('span', { class: 'num col-prize' }, 'Prize'),
+ ),
+ board,
+ tickerFromStandings(standings),
+ ),
+ );
+
+ root.replaceChildren(
+ h('button', { class: 'arena-back', type: 'button', onclick: () => (location.hash = '#/') }, '← All tournaments'),
+ head,
+ body,
+ );
+}
+
+function detailStats(data, phase) {
+ const t = data.tournament;
+ const stats = [];
+ stats.push(stat('Prize pool', Number(t.prize_pool_three) > 0 ? `${fmtThree(t.prize_pool_three)} $THREE` : '—'));
+ stats.push(stat('Entrants', String(data.standings?.length || 0)));
+ stats.push(stat('Scoring', scoringLabel[t.scoring] || t.scoring));
+ if (phase === 'upcoming') {
+ stats.push(statCountdown('Starts in', t.starts_at));
+ } else if (phase === 'live') {
+ stats.push(statCountdown('Ends in', t.ends_at));
+ } else {
+ stats.push(stat('Status', prettyFinished(data.derived_status)));
+ }
+ return h('div', { class: 'detail-stats' }, ...stats);
+}
+function stat(k, v) {
+ return h('div', { class: 'stat' }, h('span', { class: 'k' }, k), h('span', { class: 'v' }, v));
+}
+function statCountdown(k, iso) {
+ return h(
+ 'div',
+ { class: 'stat' },
+ h('span', { class: 'k' }, k),
+ h('span', { class: 'v countdown', dataset: { countdown: iso }, doneLabel: 'now' }, '…'),
+ );
+}
+
+function leaderVisual(leader) {
+ if (!leader) {
+ return h('div', { class: 'spot-fallback' }, 'Awaiting the first ranked trade');
+ }
+ const visual = leader.glb_url
+ ? h('agent-3d', { body: leader.glb_url, autorotate: 'true', 'camera-controls': 'true', 'aria-label': `${leader.agent_name} avatar` })
+ : leader.image
+ ? h('div', { class: 'spot-fallback' }, h('img', { src: leader.image, alt: leader.agent_name, loading: 'lazy' }))
+ : h('div', { class: 'spot-fallback' }, initialsOf(leader.agent_name));
+ return h(
+ 'div',
+ {},
+ visual,
+ h(
+ 'div',
+ { class: 'spot-name' },
+ leader.agent_name || 'Agent',
+ leader.metrics?.verified ? h('span', { class: 'badge badge-verified mini-badge' }, '✓ Verified') : null,
+ ),
+ h('div', { class: 'spot-metric' }, `${fmtSol(leader.metrics?.realized_pnl_sol)} · ${leader.in_window_trades} trades`),
+ );
+}
+
+function renderBoard(board, standings, t, phase) {
+ const ranked = standings.filter((s) => s.rank != null);
+ const dq = standings.filter((s) => s.rank == null);
+ if (!ranked.length && !dq.length) {
+ board.replaceChildren(
+ h(
+ 'div',
+ { class: 'state' },
+ h('h3', {}, phase === 'upcoming' ? 'No entrants yet' : 'No ranked agents yet'),
+ h(
+ 'p',
+ {},
+ phase === 'upcoming'
+ ? 'Be the first to enter. Only trades opened during the window count — fair start for everyone.'
+ : 'Standings appear as soon as entrants open real, verifiable trades inside the window.',
+ ),
+ phase !== 'finished'
+ ? h('button', { class: 'btn btn-primary', type: 'button', onclick: () => openJoinModal(t) }, 'Join with your agent')
+ : null,
+ ),
+ );
+ return;
+ }
+ board.replaceChildren(...ranked.map((s) => boardRow(s, t)), ...dq.map((s) => boardRow(s, t)));
+}
+
+function boardRow(s, t) {
+ const pnl = s.metrics?.realized_pnl_sol;
+ const prizeShown = Number(s.persisted_prize_three) > 0 ? s.persisted_prize_three : s.projected_prize_three;
+ const subBits = [];
+ subBits.push(h('span', {}, `${s.metrics?.closed_count ?? s.in_window_trades ?? 0} trades`));
+ if (s.metrics?.win_rate != null) subBits.push(h('span', {}, `${Math.round(s.metrics.win_rate * 100)}% win`));
+ if (s.metrics?.verified) subBits.push(h('span', { class: 'badge badge-verified mini-badge' }, '✓'));
+ if (s.wash_suspected) subBits.push(h('span', { class: 'badge badge-warn mini-badge', title: 'Single-coin high-churn pattern' }, 'flagged'));
+ if (!s.eligible && t.bracket === 'prize' && s.rank != null)
+ subBits.push(h('span', { class: 'badge badge-finished mini-badge', title: (s.ineligible_reasons || []).join(', ') }, 'no prize'));
+ if (s.entry_status === 'disqualified') subBits.push(h('span', { class: 'badge badge-warn mini-badge' }, 'DQ'));
+
+ const avatar = s.image
+ ? h('img', { src: s.image, alt: '', loading: 'lazy' })
+ : h('div', { class: 'ph' }, initialsOf(s.agent_name));
+
+ const scoreText =
+ t.scoring === 'realized_pnl' ? fmtSol(s.score_value) : t.scoring === 'roi_pct' ? fmtPct(s.score_value) : String(s.score_value);
+
+ const row = h(
+ 'div',
+ {
+ class: `row${s.rank === 1 ? ' rank-1' : ''}`,
+ role: 'button',
+ tabindex: '0',
+ dataset: { agent: s.agent_id },
+ 'aria-expanded': expandedAgent === s.agent_id ? 'true' : 'false',
+ onclick: () => toggleProof(s),
+ onkeydown: (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ toggleProof(s);
+ }
+ },
+ },
+ h('span', { class: 'rank' }, s.rank == null ? '–' : `#${s.rank}`),
+ h(
+ 'div',
+ { class: 'who' },
+ avatar,
+ h(
+ 'div',
+ { class: 'nm' },
+ h('div', { class: 'name' }, s.agent_name || 'Agent'),
+ h('div', { class: 'sub' }, ...subBits),
+ ),
+ ),
+ h('span', { class: 'score num' }, scoreText),
+ h('span', { class: `num ${pnl > 0 ? 'pnl-pos' : pnl < 0 ? 'pnl-neg' : ''}` }, fmtSol(pnl)),
+ h('span', { class: 'prize num' }, Number(prizeShown) > 0 ? `${fmtThree(prizeShown)}` : ''),
+ );
+
+ if (expandedAgent === s.agent_id) row.append(proofPanel(s));
+ return row;
+}
+
+function proofPanel(s) {
+ const trades = s.sample_trades || [];
+ if (!trades.length) {
+ return h('div', { class: 'row-proof' }, h('span', { class: 'proof-pill' }, 'No closed trades in the window yet'));
+ }
+ return h(
+ 'div',
+ { class: 'row-proof' },
+ ...trades.map((tr) =>
+ h(
+ tr.tx_url ? 'a' : 'span',
+ tr.tx_url ? { class: 'proof-pill', href: tr.tx_url, target: '_blank', rel: 'noopener', onclick: (e) => e.stopPropagation() } : { class: 'proof-pill' },
+ `${tr.symbol || (tr.mint || '').slice(0, 4)} `,
+ h('b', { class: tr.pnl_sol > 0 ? 'pnl-pos' : tr.pnl_sol < 0 ? 'pnl-neg' : '' }, fmtSol(tr.pnl_sol)),
+ tr.tx_url ? ' ⛓' : '',
+ ),
+ ),
+ );
+}
+
+function toggleProof(s) {
+ expandedAgent = expandedAgent === s.agent_id ? null : s.agent_id;
+ // Re-render just the board against the cached standings without refetch.
+ const board = document.getElementById('board');
+ if (board && currentStandings) renderBoard(board, currentStandings, currentTournament, phaseFromStatus(currentDerived));
+}
+
+function tickerFromStandings(standings) {
+ const trades = [];
+ for (const s of standings) {
+ for (const tr of s.sample_trades || []) {
+ trades.push({ ...tr, agent: s.agent_name });
+ }
+ }
+ trades.sort((a, b) => new Date(b.closed_at) - new Date(a.closed_at));
+ const list = h('div', { class: 'ticker-list' });
+ if (!trades.length) {
+ list.append(h('div', { class: 'ticker-item' }, h('span', { class: 'tk-mint' }, 'Recent in-window trades will stream here')));
+ } else {
+ for (const tr of trades.slice(0, 30)) {
+ list.append(
+ h(
+ tr.tx_url ? 'a' : 'div',
+ tr.tx_url ? { class: 'ticker-item', href: tr.tx_url, target: '_blank', rel: 'noopener', style: 'color:inherit;text-decoration:none' } : { class: 'ticker-item' },
+ h('span', { class: 'tk-agent' }, tr.agent || 'Agent'),
+ h('span', { class: 'tk-mint' }, tr.symbol || (tr.mint || '').slice(0, 6)),
+ h('span', { class: `tk-pnl ${tr.pnl_sol > 0 ? 'pnl-pos' : tr.pnl_sol < 0 ? 'pnl-neg' : ''}` }, fmtSol(tr.pnl_sol)),
+ ),
+ );
+ }
+ }
+ return h('div', { class: 'ticker' }, h('h4', {}, 'Recent trades — every line traceable on-chain'), list);
+}
+
+function resultsBanner(data) {
+ const t = data.tournament;
+ const att = data.attestation;
+ const settle = data.settlement || {};
+ const bits = [];
+ if (att?.url) {
+ bits.push(h('a', { class: 'att-link', href: att.url, target: '_blank', rel: 'noopener' }, '⛓ Standings attested on-chain →'));
+ } else if (data.derived_status === 'ended') {
+ bits.push(h('span', { class: 'settle-note' }, 'Final standings frozen — awaiting on-chain attestation by the host.'));
+ }
+ if (Number(t.prize_pool_three) > 0) {
+ const reason = settle.block_reason;
+ if (reason === 'payout_unconfigured') {
+ bits.push(
+ h(
+ 'span',
+ { class: 'settle-note' },
+ 'Prizes computed but ',
+ h('b', {}, 'settlement BLOCKED'),
+ ' — set ',
+ h('code', {}, 'THREE_PRIZE_PAYOUT_KEY'),
+ ' to fund payouts.',
+ ),
+ );
+ } else if (reason === 'devnet_no_prizes') {
+ bits.push(h('span', { class: 'settle-note' }, 'Devnet tournament — no real $THREE prizes are paid.'));
+ } else {
+ const paid = (settle.winners || []).filter((w) => w.settlement_status === 'settled').length;
+ bits.push(h('span', { class: 'settle-note' }, `${paid}/${(settle.winners || []).length} prizes settled in $THREE.`));
+ }
+ }
+ return bits.length ? h('div', { class: 'results-banner' }, ...bits) : null;
+}
+
+// ── live stream ────────────────────────────────────────────────────────────
+let currentStandings = null;
+let currentTournament = null;
+let currentDerived = null;
+
+function connectStream(id) {
+ stream = new EventSource(`/api/tournaments/${id}/stream`);
+ stream.addEventListener('standings', (m) => {
+ try {
+ const data = JSON.parse(m.data);
+ applyLiveStandings(id, data);
+ } catch {
+ /* ignore malformed frame */
+ }
+ });
+ stream.addEventListener('close', () => {
+ stopStream();
+ // Re-poll once for the final frame + flip to results if it just ended.
+ renderDetail(id);
+ });
+ stream.onerror = () => {
+ // Browser auto-reconnects EventSource; nothing to do but tolerate the blip.
+ };
+}
+
+function applyLiveStandings(id, data) {
+ if (detailId !== id) return;
+ const board = document.getElementById('board');
+ if (!board || !currentTournament) return;
+ currentDerived = data.status;
+
+ // Merge the lean stream rows into the richer cached rows so the board keeps its
+ // avatars/sample-trades while updating the live numbers.
+ const byId = new Map((currentStandings || []).map((s) => [s.agent_id, s]));
+ const merged = data.standings.map((row) => {
+ const prev = byId.get(row.agent_id) || {};
+ return {
+ ...prev,
+ ...row,
+ metrics: {
+ ...(prev.metrics || {}),
+ realized_pnl_sol: row.realized_pnl_sol,
+ roi_pct: row.roi_pct,
+ win_rate: row.win_rate,
+ verified: row.verified,
+ closed_count: row.closed,
+ },
+ in_window_trades: row.closed,
+ projected_prize_three: row.projected_prize_three,
+ settlement_status: row.settlement_status,
+ };
+ });
+ currentStandings = merged;
+
+ renderBoard(board, merged, currentTournament, phaseFromStatus(data.status));
+
+ // Flash rows whose rank improved since the last frame.
+ requestAnimationFrame(() => {
+ for (const s of merged) {
+ if (s.rank == null) continue;
+ const prevRank = lastRanks.get(s.agent_id);
+ if (prevRank != null && s.rank < prevRank) {
+ const node = board.querySelector(`.row[data-agent="${s.agent_id}"]`);
+ if (node) {
+ node.classList.remove('flash');
+ void node.offsetWidth;
+ node.classList.add('flash');
+ }
+ }
+ lastRanks.set(s.agent_id, s.rank);
+ }
+ });
+
+ // Refresh the spotlight leader.
+ const leader = merged.find((s) => s.rank === 1);
+ const spot = document.getElementById('spotlight');
+ if (spot && leader && spot.dataset.leader !== leader.agent_id) {
+ spot.dataset.leader = leader.agent_id;
+ spot.replaceChildren(h('div', { class: 'crown' }, '🏆 Current leader'), leaderVisual(leader));
+ }
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// MODALS
+// ───────────────────────────────────────────────────────────────────────────
+function openModal(node) {
+ const overlay = h(
+ 'div',
+ {
+ class: 'arena-modal',
+ role: 'dialog',
+ 'aria-modal': 'true',
+ onclick: (e) => {
+ if (e.target === overlay) overlay.remove();
+ },
+ },
+ node,
+ );
+ const onKey = (e) => {
+ if (e.key === 'Escape') {
+ overlay.remove();
+ document.removeEventListener('keydown', onKey);
+ }
+ };
+ document.addEventListener('keydown', onKey);
+ document.body.append(overlay);
+ const focusable = node.querySelector('input, select, button, textarea');
+ focusable?.focus();
+ return overlay;
+}
+
+function openCreateModal() {
+ const err = h('p', { class: 'form-error', role: 'alert' });
+ const nameI = h('input', { type: 'text', placeholder: 'Friday Night Snipe-Off', maxlength: '120', required: true });
+ const descI = h('textarea', { rows: '2', placeholder: 'Optional — what makes this competition fun.' });
+ const scoringI = h(
+ 'select',
+ {},
+ h('option', { value: 'score' }, 'TraderScore (composite)'),
+ h('option', { value: 'realized_pnl' }, 'Realized P&L (SOL)'),
+ h('option', { value: 'roi_pct' }, 'ROI %'),
+ );
+ const bracketI = h('select', {}, h('option', { value: 'prize' }, 'Prize ($THREE, real trades only)'), h('option', { value: 'practice' }, 'Practice (paper trades, no prizes)'));
+ const now = new Date();
+ const startDefault = new Date(now.getTime() + 5 * 60000);
+ const endDefault = new Date(now.getTime() + 24 * 3600 * 1000);
+ const startI = h('input', { type: 'datetime-local', value: toLocalInput(startDefault) });
+ const endI = h('input', { type: 'datetime-local', value: toLocalInput(endDefault) });
+ const prizeI = h('input', { type: 'number', min: '0', step: '1', placeholder: '0', value: '0' });
+
+ const submit = h('button', { class: 'btn btn-primary', type: 'submit' }, 'Create');
+ const sheet = h(
+ 'form',
+ {
+ class: 'sheet',
+ onsubmit: async (e) => {
+ e.preventDefault();
+ err.textContent = '';
+ const payload = {
+ name: nameI.value.trim(),
+ description: descI.value.trim() || undefined,
+ network: NETWORK,
+ scoring: scoringI.value,
+ bracket: bracketI.value,
+ starts_at: new Date(startI.value).toISOString(),
+ ends_at: new Date(endI.value).toISOString(),
+ prize_pool_three: bracketI.value === 'prize' ? Number(prizeI.value || 0) : 0,
+ };
+ if (!payload.name) {
+ err.textContent = 'Give your tournament a name.';
+ return;
+ }
+ submit.disabled = true;
+ submit.textContent = 'Creating…';
+ try {
+ const out = await fetchJSON('/api/tournaments', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ overlay.remove();
+ toast('Tournament created');
+ location.hash = `#/t/${out.tournament.id}`;
+ } catch (ex) {
+ err.textContent = ex.status === 401 ? 'Sign in to create a tournament.' : ex.message;
+ submit.disabled = false;
+ submit.textContent = 'Create';
+ }
+ },
+ },
+ h('h2', {}, 'Create a tournament'),
+ h('p', { class: 'sub' }, 'Scored on real, verified P&L from trades opened inside the window. Prizes are $THREE only.'),
+ field('Name', nameI),
+ field('Description', descI),
+ h('div', { class: 'field-row' }, field('Scoring', scoringI), field('Bracket', bracketI)),
+ h('div', { class: 'field-row' }, field('Starts', startI), field('Ends', endI)),
+ field('Prize pool ($THREE)', prizeI, 'Top 3 split 60/30/10 by default. Leave 0 for a bragging-rights run.'),
+ err,
+ h(
+ 'div',
+ { class: 'modal-actions' },
+ h('button', { class: 'btn btn-ghost', type: 'button', onclick: () => overlay.remove() }, 'Cancel'),
+ submit,
+ ),
+ );
+ const overlay = openModal(sheet);
+}
+
+async function openJoinModal(t) {
+ const body = h('div', { class: 'agent-pick' }, h('div', { class: 'skeleton', style: 'height:48px' }), h('div', { class: 'skeleton', style: 'height:48px' }));
+ const err = h('p', { class: 'form-error', role: 'alert' });
+ let selected = null;
+ const submit = h('button', { class: 'btn btn-primary', type: 'submit', disabled: true }, 'Join');
+
+ const sheet = h(
+ 'form',
+ {
+ class: 'sheet',
+ onsubmit: async (e) => {
+ e.preventDefault();
+ if (!selected) return;
+ err.textContent = '';
+ submit.disabled = true;
+ submit.textContent = 'Joining…';
+ try {
+ await fetchJSON(`/api/tournaments/${t.id}/join`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agent_id: selected }),
+ });
+ overlay.remove();
+ toast('Entered the arena — good luck');
+ renderDetail(t.id);
+ } catch (ex) {
+ err.textContent = ex.message;
+ submit.disabled = false;
+ submit.textContent = 'Join';
+ }
+ },
+ },
+ h('h2', {}, `Join “${t.name}”`),
+ h(
+ 'p',
+ { class: 'sub' },
+ 'Pick one of your agents. Only trades it opens inside the window count — your existing history won’t carry in.',
+ ),
+ body,
+ err,
+ h(
+ 'div',
+ { class: 'modal-actions' },
+ h('button', { class: 'btn btn-ghost', type: 'button', onclick: () => overlay.remove() }, 'Cancel'),
+ submit,
+ ),
+ );
+ const overlay = openModal(sheet);
+
+ try {
+ const data = await fetchJSON('/api/agents');
+ const agents = data.agents || [];
+ if (!agents.length) {
+ body.replaceChildren(
+ h(
+ 'div',
+ { class: 'state', style: 'padding:1.4rem' },
+ h('h3', {}, 'No agents yet'),
+ h('p', {}, 'Create an agent first, give it a trading wallet, and come back to compete.'),
+ h('a', { class: 'btn btn-primary', href: '/app' }, 'Create an agent'),
+ ),
+ );
+ return;
+ }
+ body.replaceChildren(
+ ...agents.map((a) =>
+ h(
+ 'button',
+ {
+ class: 'agent-opt',
+ type: 'button',
+ 'aria-pressed': 'false',
+ onclick: (e) => {
+ selected = a.id;
+ body.querySelectorAll('.agent-opt').forEach((b) => b.setAttribute('aria-pressed', 'false'));
+ e.currentTarget.setAttribute('aria-pressed', 'true');
+ submit.disabled = false;
+ },
+ },
+ a.profile_image_url || a.image
+ ? h('img', { src: a.profile_image_url || a.image, alt: '' })
+ : h('div', { class: 'ph' }, initialsOf(a.name)),
+ h('div', {}, h('div', { style: 'font-weight:600' }, a.name || 'Agent'), h('div', { class: 'hint' }, a.wallet_address ? `${a.wallet_address.slice(0, 4)}…${a.wallet_address.slice(-4)}` : 'no wallet yet')),
+ ),
+ ),
+ );
+ } catch (ex) {
+ body.replaceChildren(
+ h(
+ 'div',
+ { class: 'state', style: 'padding:1.4rem' },
+ h('h3', {}, ex.status === 401 ? 'Sign in to join' : 'Could not load your agents'),
+ h('p', {}, ex.status === 401 ? 'You need an account to enter a tournament.' : ex.message),
+ ex.status === 401 ? h('a', { class: 'btn btn-primary', href: '/app' }, 'Sign in') : null,
+ ),
+ );
+ }
+}
+
+function field(label, input, hint) {
+ const id = `f-${Math.random().toString(36).slice(2, 8)}`;
+ input.id = id;
+ return h('div', { class: 'field' }, h('label', { for: id }, label), input, hint ? h('div', { class: 'hint' }, hint) : null);
+}
+function toLocalInput(d) {
+ const pad = (n) => String(n).padStart(2, '0');
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// ROUTER
+// ───────────────────────────────────────────────────────────────────────────
+function route() {
+ const hash = location.hash || '#/';
+ const m = hash.match(/^#\/t\/([0-9a-f-]{36})/i);
+ if (m) renderDetail(m[1]);
+ else renderList();
+}
+
+window.addEventListener('hashchange', route);
+window.addEventListener('beforeunload', stopStream);
+route();
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index e68bd8cb5..058cbd2b2 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -40,6 +40,7 @@ export const NAV = [
{ path: '/dashboard/tokens', label: 'Tokens', icon: 'token', group: 'Monetize', tags: ['pump.fun', 'launch', 'bonding curve', 'royalties', 'trade'] },
{ path: '/dashboard/copy', label: 'Copy Trading', icon: 'live', group: 'Monetize', tags: ['copy', 'copy-trade', 'mirror', 'leader', 'follow', 'traders', 'intents', 'pump.fun', 'sniper'] },
{ path: '/dashboard/sniper', label: 'Sniper Strategies', icon: 'live', group: 'Monetize', tags: ['sniper', 'autonomous', 'strategy', 'pump.fun', 'auto-trade', 'budget', 'positions', 'pnl', 'kill-switch'] },
+ { path: '/dashboard/prelaunch-radar', label: 'Pre-Launch Radar', icon: 'live', group: 'Monetize', tags: ['radar', 'pre-launch', 'precursor', 'block-zero', 'snipe', 'creator', 'smart-money', 'pump.fun', 'pre-cog', 'watchlist'] },
{ path: '/oracle', label: 'Oracle', icon: 'oracle', group: 'Monetize', tags: ['conviction', 'score', 'tier', 'pump.fun', 'signal', 'ai', 'trade intelligence', 'wins', 'proof', 'leaderboard'], external: true },
{ path: '/dashboard/portfolio', label: 'Portfolio', icon: 'portfolio', group: 'Monetize', tags: ['nft', 'holdings', 'balances', 'wallet', 'collection', 'crypto', 'tokens', 'chart', 'send'] },
{ path: '/dashboard/landscape', label: 'Landscape', icon: 'landscape', group: 'Monetize', tags: ['competitors', 'market', 'competitive', 'intelligence', 'positioning', 'tam', 'investor'] },
diff --git a/src/dashboard-next/pages/prelaunch-radar.js b/src/dashboard-next/pages/prelaunch-radar.js
new file mode 100644
index 000000000..80affa6fc
--- /dev/null
+++ b/src/dashboard-next/pages/prelaunch-radar.js
@@ -0,0 +1,337 @@
+// dashboard-next — Pre-Launch Radar.
+//
+// The earliest edge on the platform: instead of reacting to a launch after it hits
+// the feed, the radar watches proven creator + smart-money wallets on-chain and
+// surfaces launch PRECURSORS — a watched wallet funding a fresh deploy wallet, or
+// submitting a pump.fun create — at block-0. This view renders that live tape, the
+// auto-curated watchlist (why each wallet is watched), and — for the owner — which
+// precursors their armed agents actually fired on.
+//
+// Every number traces to real on-chain activity (radar_events / radar_watchlist).
+// The radar's own state is read honestly from the worker heartbeat: live, paused
+// (no RPC / disabled), or unknown (not reporting). Nothing here is synthesized.
+//
+// Endpoints:
+// GET /api/sniper/radar → { status, watchlist, events, counts, armed? }
+// GET /api/sniper/radar-stream → SSE: precursor events (live)
+
+import { mountShell } from '../shell.js';
+import { get, esc, relTime } from '../api.js';
+
+const POLL_REFRESH_MS = 30_000;
+
+const KIND_LABEL = {
+ create: 'Direct deploy',
+ funding: 'Funded fresh wallet',
+ correlated_mint: 'Funded → deployed',
+};
+const KIND_HINT = {
+ create: 'A watched wallet submitted a pump.fun create instruction.',
+ funding: 'A watched wallet funded a brand-new wallet — a likely deploy wallet.',
+ correlated_mint: 'A wallet a watched address freshly funded just minted a coin.',
+};
+const REASON_LABEL = {
+ creator_graduated: 'Proven creator',
+ smart_money: 'Smart money',
+ manual: 'Manually pinned',
+};
+
+function pumpUrl(mint) { return `https://pump.fun/coin/${encodeURIComponent(mint)}`; }
+function solscanAddr(a) { return `https://solscan.io/account/${encodeURIComponent(a)}`; }
+function pct(n) { return n == null ? '—' : `${Math.round(Number(n) * 100)}%`; }
+
+const STYLE = `<style>
+.rd-wrap { display: grid; gap: 20px; }
+.rd-banner { display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
+ background: var(--nxt-panel); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); padding: 14px 18px; }
+.rd-dot { width: 10px; height: 10px; border-radius: 50%; flex: none; box-shadow: 0 0 0 4px transparent; }
+.rd-dot.live { background: #34d399; box-shadow: 0 0 0 4px rgba(52,211,153,.18); animation: rd-pulse 2s infinite; }
+.rd-dot.paused { background: #fbbf24; }
+.rd-dot.down { background: #f87171; }
+.rd-dot.unknown { background: var(--nxt-ink-faint); }
+@keyframes rd-pulse { 0%,100% { box-shadow: 0 0 0 4px rgba(52,211,153,.18);} 50% { box-shadow: 0 0 0 7px rgba(52,211,153,0);} }
+.rd-state { font-weight: 700; font-size: 14px; }
+.rd-state-sub { color: var(--nxt-ink-faint); font-size: 12.5px; }
+.rd-banner .rd-spacer { flex: 1 1 auto; }
+.rd-src { font-size: 11px; color: var(--nxt-ink-faint); text-transform: uppercase; letter-spacing: .05em; }
+
+.rd-strip { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 12px; }
+.rd-kpi { background: var(--nxt-panel); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); padding: 14px 16px; }
+.rd-kpi-label { font-size: 11px; color: var(--nxt-ink-faint); text-transform: uppercase; letter-spacing: .05em; margin-bottom: 4px; }
+.rd-kpi-val { font-size: 22px; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.2; }
+
+.rd-cols { display: grid; grid-template-columns: 1.4fr 1fr; gap: 20px; align-items: start; }
+@media (max-width: 880px) { .rd-cols { grid-template-columns: 1fr; } }
+.rd-panel { background: var(--nxt-panel); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); overflow: hidden; }
+.rd-panel-head { display: flex; align-items: center; gap: 10px; padding: 13px 16px; border-bottom: 1px solid var(--nxt-stroke); }
+.rd-panel-title { font-weight: 700; font-size: 14px; }
+.rd-conn { margin-left: auto; font-size: 11px; color: var(--nxt-ink-faint); display: inline-flex; align-items: center; gap: 6px; }
+.rd-conn .rd-dot { width: 7px; height: 7px; box-shadow: none; }
+
+.rd-list { display: flex; flex-direction: column; }
+.rd-ev { display: grid; grid-template-columns: auto 1fr auto; gap: 10px; align-items: center; padding: 11px 16px; border-bottom: 1px solid var(--nxt-stroke); transition: background .12s; }
+.rd-ev:last-child { border-bottom: 0; }
+.rd-ev:hover { background: color-mix(in srgb, var(--nxt-accent) 5%, transparent); }
+.rd-ev.rd-new { animation: rd-flash 1.4s ease-out; }
+@keyframes rd-flash { 0% { background: color-mix(in srgb, var(--nxt-accent) 22%, transparent);} 100% { background: transparent; } }
+.rd-kind { font-size: 10.5px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; padding: 3px 8px; border-radius: 999px; white-space: nowrap;
+ border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-soft); }
+.rd-kind.create, .rd-kind.correlated_mint { color: #34d399; border-color: color-mix(in srgb, #34d399 45%, var(--nxt-stroke)); }
+.rd-kind.funding { color: #fbbf24; border-color: color-mix(in srgb, #fbbf24 45%, var(--nxt-stroke)); }
+.rd-ev-main { min-width: 0; }
+.rd-ev-line1 { font-size: 13px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+.rd-ev-line2 { font-size: 11.5px; color: var(--nxt-ink-faint); margin-top: 2px; display: flex; gap: 8px; flex-wrap: wrap; }
+.rd-mono { font-family: var(--nxt-mono, ui-monospace, monospace); font-size: 12px; }
+.rd-link { color: var(--nxt-accent); text-decoration: none; }
+.rd-link:hover { text-decoration: underline; }
+.rd-ev-right { text-align: right; font-size: 11px; color: var(--nxt-ink-faint); white-space: nowrap; }
+.rd-conf { font-weight: 700; font-variant-numeric: tabular-nums; }
+.rd-fired { display: inline-block; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em;
+ color: #34d399; border: 1px solid color-mix(in srgb, #34d399 45%, var(--nxt-stroke)); border-radius: 999px; padding: 2px 7px; }
+
+.rd-wl { display: flex; flex-direction: column; max-height: 560px; overflow-y: auto; }
+.rd-wl-row { display: grid; grid-template-columns: 1fr auto; gap: 8px; align-items: center; padding: 10px 16px; border-bottom: 1px solid var(--nxt-stroke); }
+.rd-wl-row:last-child { border-bottom: 0; }
+.rd-wl-addr { display: flex; gap: 8px; align-items: center; min-width: 0; }
+.rd-wl-reason { font-size: 11px; color: var(--nxt-ink-faint); margin-top: 2px; }
+.rd-tag { font-size: 9.5px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; padding: 2px 6px; border-radius: 999px; border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-soft); }
+.rd-tag.creator { color: #818cf8; border-color: color-mix(in srgb, #818cf8 45%, var(--nxt-stroke)); }
+.rd-tag.smart_money { color: #34d399; border-color: color-mix(in srgb, #34d399 45%, var(--nxt-stroke)); }
+.rd-score { font-weight: 700; font-variant-numeric: tabular-nums; font-size: 15px; }
+.rd-empty { padding: 36px 18px; text-align: center; color: var(--nxt-ink-faint); font-size: 13.5px; }
+.rd-empty strong { display: block; color: var(--nxt-ink-soft); margin-bottom: 6px; font-size: 14px; }
+.rd-sk { height: 64px; border-radius: var(--nxt-radius); background: linear-gradient(90deg, var(--nxt-panel) 25%, color-mix(in srgb, var(--nxt-stroke) 40%, var(--nxt-panel)) 37%, var(--nxt-panel) 63%); background-size: 400% 100%; animation: rd-shimmer 1.4s infinite; margin-bottom: 12px; }
+@keyframes rd-shimmer { 0% { background-position: 100% 0;} 100% { background-position: 0 0; } }
+.rd-cta { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--nxt-accent); text-decoration: none; }
+.rd-cta:hover { text-decoration: underline; }
+.rd-armed { font-size: 12.5px; color: var(--nxt-ink-soft); }
+.rd-armed b { color: var(--nxt-ink); }
+</style>`;
+
+let _seen = new Set();
+let _sse = null;
+let _sseTimer = null;
+let _sseRetry = 0;
+let _refreshTimer = null;
+let _isOwner = false;
+
+(async function boot() {
+ try {
+ const main = await mountShell();
+ main.innerHTML = `
+ <h1 class="dn-h1">Pre-Launch Radar</h1>
+ <p class="dn-h1-sub">Block-zero launch detection — watch proven creator &amp; smart-money wallets on-chain and pre-arm the snipe on the launch precursor, not the feed.</p>
+ <div id="rd-root"><div class="rd-sk"></div><div class="rd-sk"></div><div class="rd-sk"></div></div>
+ `;
+ main.insertAdjacentHTML('beforeend', STYLE);
+ await refresh(main.querySelector('#rd-root'));
+ _refreshTimer = setInterval(() => refresh(main.querySelector('#rd-root'), true), POLL_REFRESH_MS);
+ } catch (e) {
+ const root = document.getElementById('rd-root');
+ if (root) root.innerHTML = `<p class="rd-empty"><strong>Couldn't load the radar</strong>${esc(e.message || 'Try again shortly.')}</p>`;
+ }
+})();
+
+async function refresh(root, quiet = false) {
+ if (!root) return;
+ let data;
+ try {
+ data = await get('/api/sniper/radar?network=mainnet');
+ } catch (e) {
+ if (!quiet) root.innerHTML = `<p class="rd-empty"><strong>Radar unavailable</strong>${esc(e.message || 'Try again shortly.')}</p>`;
+ return;
+ }
+ _isOwner = !!data.owner;
+ root.innerHTML = render(data);
+ startSse();
+}
+
+function render(data) {
+ const st = data.status || { state: 'unknown' };
+ const counts = data.counts || {};
+ return `
+ <div class="rd-wrap">
+ ${banner(st)}
+ <div class="rd-strip">
+ ${kpi('Watched wallets', counts.watched ?? (data.watchlist || []).length)}
+ ${kpi('Precursors · 1h', counts.events_1h ?? 0)}
+ ${kpi('Precursors · 24h', counts.events_24h ?? 0)}
+ ${kpi('Launches caught · 24h', counts.armable_24h ?? 0)}
+ </div>
+ ${data.armed ? armedStrip(data.armed) : ownerCta()}
+ <div class="rd-cols">
+ <div class="rd-panel">
+ <div class="rd-panel-head">
+ <span class="rd-panel-title">Live precursors</span>
+ <span class="rd-conn" id="rd-conn"><span class="rd-dot unknown"></span>Connecting…</span>
+ </div>
+ <div class="rd-list" id="rd-events">${eventsList(data.events || [])}</div>
+ </div>
+ <div class="rd-panel">
+ <div class="rd-panel-head">
+ <span class="rd-panel-title">Watchlist</span>
+ <span class="rd-src">${(data.watchlist || []).length} wallets</span>
+ </div>
+ <div class="rd-wl">${watchlistList(data.watchlist || [])}</div>
+ </div>
+ </div>
+ </div>`;
+}
+
+function banner(st) {
+ const state = st.state || 'unknown';
+ const cls = state === 'live' ? 'live' : state === 'paused' ? 'paused' : state === 'down' ? 'down' : 'unknown';
+ const title = state === 'live' ? 'Radar live' : state === 'paused' ? 'Radar paused' : state === 'down' ? 'Worker offline' : 'Radar status unknown';
+ let sub;
+ if (state === 'live') {
+ const bits = [];
+ if (st.watched != null) bits.push(`${st.watched} wallets watched`);
+ if (st.deployWatch) bits.push(`${st.deployWatch} fresh deploy wallets tracked`);
+ if (st.lastEventAgeMs != null) bits.push(`last precursor ${relTime(Date.now() - st.lastEventAgeMs)}`);
+ sub = bits.join(' · ') || 'Scanning the chain for launch precursors.';
+ } else if (state === 'paused') {
+ sub = st.reason === 'no_rpc'
+ ? 'No RPC endpoint configured — falling back to the feed-based snipe. Set HELIUS_API_KEY to enable on-chain detection.'
+ : st.reason === 'disabled' ? 'The radar is disabled on this worker.' : 'Detection is paused; the feed snipe still runs.';
+ } else if (state === 'down') {
+ sub = 'The sniper worker is not reporting a heartbeat. The radar resumes when it comes back.';
+ } else {
+ sub = st.reason || 'The radar has not reported yet. It reports the moment the worker boots.';
+ }
+ return `
+ <div class="rd-banner">
+ <span class="rd-dot ${cls}"></span>
+ <div>
+ <div class="rd-state">${esc(title)}</div>
+ <div class="rd-state-sub">${esc(sub)}</div>
+ </div>
+ <span class="rd-spacer"></span>
+ ${st.source ? `<span class="rd-src">via ${esc(st.source)}</span>` : ''}
+ </div>`;
+}
+
+function kpi(label, val) {
+ return `<div class="rd-kpi"><div class="rd-kpi-label">${esc(label)}</div><div class="rd-kpi-val">${esc(String(val))}</div></div>`;
+}
+
+function ownerCta() {
+ return `<div class="rd-banner"><div class="rd-armed">Arm an agent with the <b>Pre-launch radar</b> trigger to pre-arm snipes on these precursors automatically. <a class="rd-cta" href="/dashboard/sniper">Open Sniper Strategies →</a></div></div>`;
+}
+
+function armedStrip(armed) {
+ const strategies = armed.strategies || [];
+ if (!strategies.length) {
+ return `<div class="rd-banner"><div class="rd-armed">No agent is armed with the pre-launch radar trigger yet. <a class="rd-cta" href="/dashboard/sniper">Arm one →</a></div></div>`;
+ }
+ const active = strategies.filter((s) => s.enabled && !s.kill_switch).length;
+ const fired = (armed.positions || []).length;
+ return `<div class="rd-banner"><div class="rd-armed">
+ <b>${strategies.length}</b> radar ${strategies.length === 1 ? 'strategy' : 'strategies'} armed · <b>${active}</b> active · <b>${fired}</b> ${fired === 1 ? 'snipe' : 'snipes'} fired on recent precursors.
+ <a class="rd-cta" href="/dashboard/sniper" style="margin-left:8px">Manage →</a>
+ </div></div>`;
+}
+
+function eventsList(events) {
+ if (!events.length) {
+ return `<div class="rd-empty"><strong>The radar is learning</strong>No launch precursors yet. As proven creators and smart-money wallets move, their funding and deploys appear here in real time — usually before the coin hits any feed.</div>`;
+ }
+ return events.map((e) => eventRow(e, false)).join('');
+}
+
+function eventRow(e, isNew) {
+ const kind = e.kind || 'create';
+ const label = KIND_LABEL[kind] || kind;
+ const fired = e.fired ? `<span class="rd-fired" title="Your agent sniped this">⚡ Sniped</span>` : '';
+ const mintCell = e.mint
+ ? `<a class="rd-link rd-mono" href="${pumpUrl(e.mint)}" target="_blank" rel="noopener" title="${esc(e.mint)}">${esc(short(e.mint))}</a>`
+ : `<span class="rd-state-sub">awaiting deploy…</span>`;
+ const trig = e.trigger_wallet
+ ? `<a class="rd-link rd-mono" href="${_isOwner ? solscanAddr(e.trigger_wallet) : '#'}" ${_isOwner ? 'target="_blank" rel="noopener"' : 'onclick="return false"'} title="${esc(e.trigger_wallet)}">${esc(e.trigger_wallet)}</a>`
+ : '—';
+ const reason = e.watch_reason ? (REASON_LABEL[e.watch_reason] || e.watch_reason) : 'watched';
+ return `
+ <div class="rd-ev ${isNew ? 'rd-new' : ''}" data-id="${esc(e.id || '')}">
+ <span class="rd-kind ${esc(kind)}" title="${esc(KIND_HINT[kind] || '')}">${esc(label)}</span>
+ <div class="rd-ev-main">
+ <div class="rd-ev-line1">${mintCell} ${fired}</div>
+ <div class="rd-ev-line2">${esc(reason)} · ${trig}</div>
+ </div>
+ <div class="rd-ev-right">
+ <div class="rd-conf" title="Detection confidence">${pct(e.confidence)}</div>
+ <div>${e.at || e.created_at ? esc(relTime(e.at || e.created_at)) : ''}</div>
+ </div>
+ </div>`;
+}
+
+function watchlistList(wl) {
+ if (!wl.length) {
+ return `<div class="rd-empty"><strong>Curating the watchlist</strong>The radar auto-selects proven creators (graduated coins) and top smart-money wallets. It populates as the graph learns from real outcomes.</div>`;
+ }
+ return wl.map((w) => {
+ const reason = REASON_LABEL[w.reason] || w.reason;
+ const tags = (w.labels || []).slice(0, 2).map((l) => `<span class="rd-tag ${esc(l)}">${esc(l.replace('_', ' '))}</span>`).join(' ');
+ const detail = w.reason === 'creator_graduated' && w.creator_graduated != null
+ ? `${w.creator_graduated} graduated`
+ : w.realized_score != null ? `rep ${Math.round(w.realized_score)}` : '';
+ const addrLink = _isOwner
+ ? `<a class="rd-link rd-mono" href="${solscanAddr(w.address)}" target="_blank" rel="noopener" title="${esc(w.address)}">${esc(short(w.address))}</a>`
+ : `<span class="rd-mono" title="anonymized">${esc(w.address)}</span>`;
+ return `
+ <div class="rd-wl-row">
+ <div>
+ <div class="rd-wl-addr">${addrLink} ${tags}</div>
+ <div class="rd-wl-reason">${esc(reason)}${detail ? ` · ${esc(detail)}` : ''}${w.last_hit_at ? ` · last hit ${esc(relTime(w.last_hit_at))}` : ''}</div>
+ </div>
+ <div class="rd-score" title="Signal score">${Math.round(Number(w.score))}</div>
+ </div>`;
+ }).join('');
+}
+
+function short(a) { return a && a.length > 12 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a; }
+
+// ── live SSE ─────────────────────────────────────────────────────────────────
+function setConn(state, label) {
+ const el = document.getElementById('rd-conn');
+ if (el) el.innerHTML = `<span class="rd-dot ${esc(state)}"></span>${esc(label)}`;
+}
+
+function startSse() {
+ if (_sse) { try { _sse.close(); } catch {} _sse = null; }
+ const src = new EventSource('/api/sniper/radar-stream?network=mainnet');
+ _sse = src;
+ src.addEventListener('open', () => { _sseRetry = 0; setConn('live', 'Live'); });
+ src.addEventListener('precursor', (e) => {
+ try { ingest(JSON.parse(e.data)); } catch {}
+ });
+ src.addEventListener('close', () => { try { src.close(); } catch {} scheduleReconnect(); });
+ src.onerror = () => { try { src.close(); } catch {} if (_sse === src) _sse = null; scheduleReconnect(); };
+}
+
+function ingest(ev) {
+ const list = document.getElementById('rd-events');
+ if (!list || !ev.id) return;
+ if (_seen.has(ev.id)) return;
+ _seen.add(ev.id);
+ if (_seen.size > 3000) _seen = new Set([...(_seen)].slice(-1500));
+ // Drop the empty-state if present.
+ const empty = list.querySelector('.rd-empty');
+ if (empty) list.innerHTML = '';
+ list.insertAdjacentHTML('afterbegin', eventRow(ev, true));
+ // Trim to a sane cap.
+ const rows = list.querySelectorAll('.rd-ev');
+ for (let i = rows.length - 1; i >= 80; i--) rows[i].remove();
+}
+
+function scheduleReconnect() {
+ if (_sseTimer) return;
+ if (!document.getElementById('rd-events')) return;
+ _sseRetry = Math.min(_sseRetry + 1, 6);
+ const delay = Math.min(1000 * 2 ** (_sseRetry - 1), 30000);
+ setConn('paused', `Reconnecting in ${Math.round(delay / 1000)}s…`);
+ _sseTimer = setTimeout(() => { _sseTimer = null; if (document.getElementById('rd-events')) startSse(); }, delay);
+}
+
+window.addEventListener('beforeunload', () => {
+ if (_sse) try { _sse.close(); } catch {}
+ if (_refreshTimer) clearInterval(_refreshTimer);
+});
diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.js
index 8961bc48e..70195217e 100644
--- a/src/dashboard-next/pages/sniper.js
+++ b/src/dashboard-next/pages/sniper.js
@@ -303,7 +303,7 @@ function stratCard(s) {
const wins = s.summary?.wins || 0;
const wr = closed > 0 ? Math.round((wins / closed) * 100) : null;
const img = s.image || '/favicon.ico';
- const triggerLabel = s.trigger === 'first_claim' ? 'First-claim trigger' : s.trigger === 'intel_confirmed' ? 'Intel-confirmed trigger' : 'New mint trigger';
+ const triggerLabel = s.trigger === 'first_claim' ? 'First-claim trigger' : s.trigger === 'intel_confirmed' ? 'Intel-confirmed trigger' : s.trigger === 'prelaunch_radar' ? 'Pre-launch radar trigger' : 'New mint trigger';
const walletBal = s.wallet_sol != null ? s.wallet_sol : null;
const walletWarn = walletBal != null && walletBal < lamportsToSol(s.per_trade_lamports || '0') + 0.003;
@@ -376,7 +376,9 @@ function stratForm(s) {
<option value="new_mint" ${s.trigger === 'new_mint' || (!s.trigger || (s.trigger !== 'first_claim' && s.trigger !== 'intel_confirmed')) ? 'selected' : ''}>New mint — snipe every launch</option>
<option value="first_claim" ${s.trigger === 'first_claim' ? 'selected' : ''}>First claim — creator claims for first time</option>
<option value="intel_confirmed" ${s.trigger === 'intel_confirmed' ? 'selected' : ''}>Intel confirmed — buy after Coin Intelligence verdict</option>
+ <option value="prelaunch_radar" ${s.trigger === 'prelaunch_radar' ? 'selected' : ''}>Pre-launch radar — pre-arm on a proven creator's launch precursor</option>
</select>
+ <span class="sn-hint">Pre-launch radar watches proven creator + smart-money wallets on-chain and pre-arms the snipe the instant one funds a fresh deploy wallet or submits a pump.fun create — at block-0, on signal not luck.</span>
<span class="sn-hint">Intel confirmed waits for the observation window (~60s) and only buys if the coin passes bundle detection and quality analysis.</span>
<span class="sn-hint">When the agent enters a position.</span>
</div>
@@ -487,6 +489,7 @@ function stratForm(s) {
${s.trigger === 'first_claim' ? firstClaimFields(s) : ''}
${s.trigger === 'intel_confirmed' ? intelFields(s) : ''}
+ ${s.trigger === 'prelaunch_radar' ? radarFields(s) : ''}
<div class="sn-section-head">Notifications</div>
<div class="sn-field sn-field-full">
@@ -502,6 +505,29 @@ function stratForm(s) {
</form>`;
}
+function radarFields(s) {
+ return `
+ <div class="sn-section-head">Pre-Launch Radar Gates</div>
+ <div class="sn-field">
+ <label>Min creator graduated</label>
+ <input name="min_creator_graduated_radar" type="number" min="0" max="100000" value="${s.min_creator_graduated_radar != null ? s.min_creator_graduated_radar : ''}" placeholder="worker default (2)" aria-label="Min creator graduated coins for the radar" />
+ <span class="sn-hint">Only pre-arm when the triggering creator has graduated at least this many coins. Blank uses the worker default.</span>
+ </div>
+ <div class="sn-field">
+ <label>Max precursor age (ms)</label>
+ <input name="radar_max_age_ms" type="number" min="1000" max="3600000" value="${s.radar_max_age_ms != null ? s.radar_max_age_ms : ''}" placeholder="120000" aria-label="Max precursor age in milliseconds" />
+ <span class="sn-hint">Skip a precursor first seen older than this — never chase a launch the floor already moved past.</span>
+ </div>
+ <div class="sn-field">
+ <label>Require smart-money funder</label>
+ <select name="require_smart_money_funder" aria-label="Require a proven smart-money funder">
+ <option value="false" ${!s.require_smart_money_funder ? 'selected' : ''}>No — any proven creator</option>
+ <option value="true" ${s.require_smart_money_funder ? 'selected' : ''}>Yes — funder must be proven smart money</option>
+ </select>
+ <span class="sn-hint">Demand the triggering wallet (or the funder of the fresh deploy wallet) be a proven smart-money address before pre-arming.</span>
+ </div>`;
+}
+
function firstClaimFields(s) {
const toLamSolOptional = (l) => (l != null ? lamportsToSol(l).toFixed(4) : '');
return `
@@ -1016,6 +1042,11 @@ async function saveForm(form, root) {
body.avoid_dev_dump = fd.avoid_dev_dump !== 'false';
body.allowed_categories = fd.allowed_categories ? fd.allowed_categories.split(',').map((c) => c.trim()).filter(Boolean) : null;
}
+ if (fd.trigger === 'prelaunch_radar') {
+ body.min_creator_graduated_radar = fd.min_creator_graduated_radar !== '' ? Number(fd.min_creator_graduated_radar) : null;
+ body.radar_max_age_ms = fd.radar_max_age_ms !== '' ? Number(fd.radar_max_age_ms) : null;
+ body.require_smart_money_funder = fd.require_smart_money_funder === 'true';
+ }
await post('/api/sniper/strategy', body);
if (msg) { msg.textContent = 'Saved!'; setTimeout(() => { if (msg) msg.textContent = ''; }, 2000); }
diff --git a/src/mission-control/enrich.js b/src/mission-control/enrich.js
new file mode 100644
index 000000000..c3a6a2ca3
--- /dev/null
+++ b/src/mission-control/enrich.js
@@ -0,0 +1,143 @@
+/**
+ * Mission Control — per-mint enrichment.
+ *
+ * The launch stream gives us thin rows (mint, name, symbol, market cap). The
+ * intel score, firewall verdict, and smart-money flow come from three real,
+ * public, rate-limited endpoints. Fetching them for every row on a fast stream
+ * would hammer those services, so this layer:
+ *
+ * • caches each result with a short TTL (the endpoints themselves cache too),
+ * • dedupes in-flight requests so N panes asking for the same mint share one,
+ * • bounds concurrency so a burst of newly-visible rows can't open 50 sockets,
+ * • patches results onto the store row so every pane sees the same data.
+ *
+ * Only rows the user can actually see (virtualized feed → ~20 at a time, plus
+ * the selected coin) get enriched — never the whole 300-row buffer.
+ */
+
+const TTL = { intel: 30_000, safety: 25_000, smart: 20_000 };
+const MAX_CONCURRENT = 4;
+
+export function createEnricher({ store }) {
+ const cache = new Map(); // key -> { at, value }
+ const inflight = new Map(); // key -> Promise
+ const queue = [];
+ let running = 0;
+
+ function net() {
+ return store.getNetwork();
+ }
+ function key(kind, mint) {
+ return `${net()}:${kind}:${mint}`;
+ }
+ function cached(kind, mint) {
+ const hit = cache.get(key(kind, mint));
+ if (hit && Date.now() - hit.at < TTL[kind]) return hit.value;
+ return undefined;
+ }
+
+ function pump() {
+ while (running < MAX_CONCURRENT && queue.length) {
+ const job = queue.shift();
+ running += 1;
+ job().finally(() => {
+ running -= 1;
+ pump();
+ });
+ }
+ }
+
+ function schedule(fn) {
+ return new Promise((resolve) => {
+ queue.push(() => fn().then(resolve, () => resolve(null)));
+ pump();
+ });
+ }
+
+ async function fetchJson(url) {
+ const r = await fetch(url, { headers: { accept: 'application/json' } });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.json();
+ }
+
+ function run(kind, mint, urlFor, shape, patchFor) {
+ const k = key(kind, mint);
+ const hit = cached(kind, mint);
+ if (hit !== undefined) {
+ if (patchFor) store.enrichRow(mint, patchFor(hit));
+ return Promise.resolve(hit);
+ }
+ if (inflight.has(k)) return inflight.get(k);
+ const p = schedule(async () => {
+ try {
+ const raw = await fetchJson(urlFor(mint));
+ const value = shape ? shape(raw) : raw;
+ cache.set(k, { at: Date.now(), value });
+ if (patchFor) store.enrichRow(mint, patchFor(value));
+ return value;
+ } catch {
+ // Honest failure: cache a null briefly so we don't retry-storm, and
+ // mark the row's field as unavailable rather than faking a value.
+ cache.set(k, { at: Date.now(), value: null });
+ if (patchFor) store.enrichRow(mint, patchFor(null));
+ return null;
+ } finally {
+ inflight.delete(k);
+ }
+ });
+ inflight.set(k, p);
+ return p;
+ }
+
+ const ensureIntel = (mint) =>
+ run(
+ 'intel',
+ mint,
+ (m) => `/api/pump/intel?mint=${encodeURIComponent(m)}&network=${net()}`,
+ (raw) => raw?.coin || (raw?.found === false ? { _none: true } : null),
+ (coin) => ({ intel: coin }),
+ );
+
+ const ensureSafety = (mint, amountSol) =>
+ run(
+ 'safety',
+ mint,
+ (m) => {
+ const u = new URLSearchParams({ mint: m, network: net() });
+ if (amountSol > 0) u.set('amount', String(amountSol));
+ return `/api/pump/safety?${u.toString()}`;
+ },
+ (raw) => raw, // { verdict, score, simulated, reasons, checks }
+ (v) => ({ safety: v }),
+ );
+
+ const ensureSmart = (mint) =>
+ run(
+ 'smart',
+ mint,
+ (m) => `/api/intel/smart-money?mint=${encodeURIComponent(m)}&network=${net()}`,
+ (raw) => raw, // { smart_money_score, count, wallets, clusters, computed, ... }
+ (v) => ({ smart: v }),
+ );
+
+ return {
+ ensureIntel,
+ ensureSafety,
+ ensureSmart,
+ /** Light enrichment for a visible feed row: intel score + smart-money + firewall verdict. */
+ ensureRow(mint, amountSol) {
+ ensureIntel(mint);
+ ensureSmart(mint);
+ ensureSafety(mint, amountSol);
+ },
+ /** Drop everything for a mint so the focus pane refetches fresh. */
+ invalidate(mint) {
+ for (const kind of Object.keys(TTL)) cache.delete(key(kind, mint));
+ },
+ clear() {
+ cache.clear();
+ inflight.clear();
+ queue.length = 0;
+ },
+ };
+}
diff --git a/src/mission-control/feed.js b/src/mission-control/feed.js
new file mode 100644
index 000000000..6fde2e293
--- /dev/null
+++ b/src/mission-control/feed.js
@@ -0,0 +1,468 @@
+/**
+ * Mission Control — live launch feed pane.
+ *
+ * The left rail. Three real sources, switchable:
+ * • Live — SSE /api/pump/trades-stream (global new-mint firehose). Brand-new
+ * pump.fun launches stream in; each row is enriched on demand with
+ * its intel score, firewall verdict, and smart-money count.
+ * • Signals — GET /api/pump/intel?view=feed: the intel engine's scored launches
+ * (already carrying quality_score + verdict), refreshed live.
+ * • Radar — GET /api/sniper/radar (pre-launch precursors, epic task 04). When
+ * that source isn't live yet the pane shows an honest degraded
+ * state — never fabricated rows.
+ *
+ * The list is virtualized (fixed row height, windowed render) so a fast feed
+ * never janks, and only rows actually on screen get enriched.
+ */
+
+import { createSseClient } from './realtime.js';
+import {
+ escapeHtml,
+ formatCompactUsd,
+ ageFrom,
+ verdictChip,
+ formatCompact,
+} from './format.js';
+
+const ROW_H = 50;
+const OVERSCAN = 6;
+const SIGNALS_REFRESH_MS = 12_000;
+
+export function createFeedPane({ store, bus, enrich, mount }) {
+ mount.classList.add('mc-pane', 'mc-pane--feed');
+ mount.setAttribute('role', 'region');
+ mount.setAttribute('aria-label', 'Live launch feed');
+ mount.innerHTML = `
+ <div class="mc-pane-head">
+ <span class="mc-pane-title">Feed</span>
+ <div class="mc-tabs" role="tablist" aria-label="Feed source">
+ <button class="mc-tab" role="tab" data-src="live" aria-selected="true">Live</button>
+ <button class="mc-tab" role="tab" data-src="signals" aria-selected="false">Signals</button>
+ <button class="mc-tab" role="tab" data-src="radar" aria-selected="false">Radar</button>
+ </div>
+ <span class="mc-pane-head-spacer"></span>
+ <span class="mc-pane-count" data-host="count"></span>
+ </div>
+ <div class="mc-filterbar" data-host="filterbar"></div>
+ <div class="mc-pane-body" data-host="body" tabindex="-1">
+ <div class="mc-vlist" data-host="vlist"><div class="mc-vlist-spacer" data-host="spacer"></div></div>
+ </div>
+ `;
+
+ const body = mount.querySelector('[data-host="body"]');
+ const vlist = mount.querySelector('[data-host="vlist"]');
+ const spacer = mount.querySelector('[data-host="spacer"]');
+ const countEl = mount.querySelector('[data-host="count"]');
+ const filterbar = mount.querySelector('[data-host="filterbar"]');
+ const tabs = [...mount.querySelectorAll('.mc-tab')];
+
+ let source = store.getFilters().source || 'live';
+ let sse = null;
+ let signalsTimer = null;
+ let radarState = null; // null | 'loading' | 'degraded' | 'ok'
+ let connState = 'reconnecting'; // mirror of conn:feed so the body can show an honest down-state
+ let rafToken = 0;
+ const rowEls = new Map(); // mint -> element (in current window)
+
+ // Single place that publishes feed connection health — drives both the topbar
+ // pill and the in-pane state panel so a dead source never shows a forever-skeleton.
+ function setConn(state) {
+ connState = state;
+ bus.emit('conn:feed', state);
+ scheduleRender();
+ }
+
+ // ── filter bar ────────────────────────────────────────────────────────────
+ renderFilterBar();
+ function renderFilterBar() {
+ const f = store.getFilters();
+ filterbar.innerHTML = `
+ <input class="mc-search" data-host="search" type="search" placeholder="Filter name / symbol / mint ( / )" aria-label="Filter feed" value="${escapeHtml(f.query)}" />
+ <button class="mc-chipbtn" data-f="smartOnly" aria-pressed="${f.smartOnly}">◎ Smart</button>
+ <button class="mc-chipbtn" data-f="socialsOnly" aria-pressed="${f.socialsOnly}">Socials</button>
+ <button class="mc-chipbtn" data-f="verdict" aria-pressed="${f.verdict !== 'any'}" title="Hide blocked / show only cleared">Safe</button>
+ <button class="mc-chipbtn" data-cycle="minIntel" aria-pressed="${f.minIntel > 0}">Intel ${f.minIntel > 0 ? '≥' + f.minIntel : 'any'}</button>
+ <button class="mc-chipbtn" data-cycle="mcBand" aria-pressed="${f.mcBand !== 'any'}">${mcBandLabel(f.mcBand)}</button>
+ <span class="mc-views" data-host="views"></span>
+ `;
+ const search = filterbar.querySelector('[data-host="search"]');
+ search.addEventListener('input', () => store.setFilters({ query: search.value.trim() }));
+ filterbar.querySelector('[data-f="smartOnly"]').addEventListener('click', () =>
+ store.setFilters({ smartOnly: !store.getFilters().smartOnly }));
+ filterbar.querySelector('[data-f="socialsOnly"]').addEventListener('click', () =>
+ store.setFilters({ socialsOnly: !store.getFilters().socialsOnly }));
+ filterbar.querySelector('[data-f="verdict"]').addEventListener('click', () =>
+ store.setFilters({ verdict: store.getFilters().verdict === 'any' ? 'warn' : 'any' }));
+ filterbar.querySelector('[data-cycle="minIntel"]').addEventListener('click', () => {
+ const steps = [0, 40, 60, 80];
+ const cur = store.getFilters().minIntel;
+ store.setFilters({ minIntel: steps[(steps.indexOf(cur) + 1) % steps.length] || 0 });
+ });
+ filterbar.querySelector('[data-cycle="mcBand"]').addEventListener('click', () => {
+ const steps = ['any', 'nano', 'micro', 'small', 'mid'];
+ const cur = store.getFilters().mcBand;
+ store.setFilters({ mcBand: steps[(steps.indexOf(cur) + 1) % steps.length] });
+ });
+ renderViews();
+ }
+ function mcBandLabel(b) {
+ return { any: 'Mcap any', nano: '<$10K', micro: '$10–50K', small: '$50–250K', mid: '>$250K' }[b] || 'Mcap';
+ }
+ function renderViews() {
+ const host = filterbar.querySelector('[data-host="views"]');
+ if (!host) return;
+ const views = store.listViews();
+ host.innerHTML = `
+ ${views.map((v) => `<button class="mc-chipbtn" data-view="${escapeHtml(v.name)}" title="Apply saved view">${escapeHtml(v.name)}</button>`).join('')}
+ <button class="mc-chipbtn" data-host="saveview" title="Save current filters as a view">+ Save view</button>
+ `;
+ host.querySelectorAll('[data-view]').forEach((b) =>
+ b.addEventListener('click', () => { store.applyView(b.dataset.view); }));
+ host.querySelector('[data-host="saveview"]').addEventListener('click', () => {
+ const name = prompt('Name this view (filters will be saved):');
+ if (name && name.trim()) store.saveView(name.trim().slice(0, 24));
+ });
+ }
+
+ // ── source tabs ─────────────────────────────────────────────────────────
+ for (const t of tabs) {
+ t.addEventListener('click', () => switchSource(t.dataset.src));
+ t.setAttribute('aria-selected', String(t.dataset.src === source));
+ }
+
+ function switchSource(next) {
+ if (next === source) return;
+ source = next;
+ store.setFilters({ source: next });
+ for (const t of tabs) t.setAttribute('aria-selected', String(t.dataset.src === next));
+ stopStreams();
+ store.resetFeed();
+ startSource();
+ }
+
+ function stopStreams() {
+ if (sse) { sse.stop(); sse = null; }
+ if (signalsTimer) { clearInterval(signalsTimer); signalsTimer = null; }
+ radarState = null;
+ setConn('reconnecting');
+ }
+
+ function startSource() {
+ if (source === 'live') startLive();
+ else if (source === 'signals') startSignals();
+ else startRadar();
+ scheduleRender();
+ }
+
+ // Live — global pump.fun new-mint firehose.
+ function startLive() {
+ sse = createSseClient({
+ url: '/api/pump/trades-stream',
+ onState: (s) => setConn(s),
+ events: {
+ open: () => {},
+ mint: (d) => {
+ if (!d?.mint) return;
+ store.upsertRow({
+ mint: d.mint,
+ name: d.name,
+ symbol: d.symbol,
+ creator: d.creator,
+ market_cap_usd: d.market_cap_usd ?? null,
+ market_cap_sol: d.market_cap_sol ?? null,
+ image_uri: d.image_uri || null,
+ twitter: d.twitter || null,
+ telegram: d.telegram || null,
+ website: d.website || null,
+ created_at: d.created_at || Math.floor(Date.now() / 1000),
+ creator_launches: d.creator_coins_count ?? null,
+ creator_graduated: d.creator_graduated ?? null,
+ source: 'live',
+ });
+ scheduleRender();
+ },
+ graduation: () => {},
+ ping: () => {},
+ close: () => {},
+ error: () => {},
+ },
+ });
+ sse.start();
+ }
+
+ // Signals — intel engine's scored feed (already carries quality_score + verdict).
+ function startSignals() {
+ setConn('reconnecting');
+ const tick = async () => {
+ try {
+ const r = await fetch(`/api/pump/intel?view=feed&network=${store.getNetwork()}&limit=120`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const data = await r.json();
+ setConn('live');
+ const coins = Array.isArray(data?.coins) ? data.coins : [];
+ // Newest first — the intel feed returns recent-first already.
+ for (let i = coins.length - 1; i >= 0; i--) {
+ const c = coins[i];
+ if (!c?.mint) continue;
+ store.upsertRow({
+ mint: c.mint,
+ name: c.name,
+ symbol: c.symbol,
+ creator: c.creator,
+ market_cap_usd: c.market_cap_usd ?? null,
+ image_uri: c.image_uri || null,
+ twitter: c.twitter || null,
+ telegram: c.telegram || null,
+ website: c.website || null,
+ created_at: c.first_seen_at_ms ? Math.floor(c.first_seen_at_ms / 1000) : null,
+ intel: c, // full intel row → quality_score, verdict, risk_flags…
+ source: 'signals',
+ });
+ }
+ scheduleRender();
+ } catch {
+ setConn('down');
+ }
+ };
+ tick();
+ signalsTimer = setInterval(tick, SIGNALS_REFRESH_MS);
+ }
+
+ // Radar — pre-launch precursors (epic task 04). Honest degraded state when absent.
+ async function startRadar() {
+ radarState = 'loading';
+ setConn('reconnecting');
+ scheduleRender();
+ try {
+ const r = await fetch(`/api/sniper/radar?network=${store.getNetwork()}`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const data = await r.json();
+ const items = data?.precursors || data?.radar || data?.items || [];
+ if (!Array.isArray(items) || !items.length) {
+ radarState = 'degraded';
+ setConn('down');
+ scheduleRender();
+ return;
+ }
+ radarState = 'ok';
+ setConn('live');
+ for (const it of items) {
+ if (!it?.mint) continue;
+ store.upsertRow({ ...it, source: 'radar' });
+ }
+ scheduleRender();
+ } catch {
+ // Source not live (404 / network) — degrade honestly, no fabricated rows.
+ radarState = 'degraded';
+ setConn('down');
+ scheduleRender();
+ }
+ }
+
+ // ── virtualized render ─────────────────────────────────────────────────────
+ function scheduleRender() {
+ if (rafToken) return;
+ rafToken = requestAnimationFrame(() => {
+ rafToken = 0;
+ render();
+ });
+ }
+
+ function render() {
+ const rows = store.visibleRows();
+ countEl.textContent = `${rows.length}${store.allRowsCount() > rows.length ? ` / ${store.allRowsCount()}` : ''}`;
+
+ // Non-list states own the whole body.
+ const statePanel = pickStatePanel(rows);
+ if (statePanel) {
+ vlist.style.display = 'none';
+ ensureStateHost().innerHTML = statePanel.html;
+ statePanel.wire?.(ensureStateHost());
+ return;
+ }
+ removeStateHost();
+ vlist.style.display = '';
+
+ // The list owns the scroll height; absolutely-positioned rows are windowed
+ // into it. (The spacer is just a sizing sentinel kept for clarity.)
+ const totalH = `${rows.length * ROW_H}px`;
+ vlist.style.height = totalH;
+ spacer.style.height = totalH;
+ const scrollTop = body.scrollTop;
+ const viewport = body.clientHeight || 600;
+ const start = Math.max(0, Math.floor(scrollTop / ROW_H) - OVERSCAN);
+ const end = Math.min(rows.length, Math.ceil((scrollTop + viewport) / ROW_H) + OVERSCAN);
+
+ // Reconcile the window — keep elements for mints still in range, drop others.
+ const wantMints = new Set();
+ const selected = store.getSelected();
+ const enrichSize = store.getActiveSize();
+ for (let i = start; i < end; i++) {
+ const row = rows[i];
+ if (!row) continue;
+ wantMints.add(row.mint);
+ let el = rowEls.get(row.mint);
+ if (!el) {
+ el = document.createElement('button');
+ el.className = 'mc-row';
+ el.type = 'button';
+ el.setAttribute('role', 'option');
+ el.dataset.mint = row.mint;
+ el.addEventListener('click', () => store.select(row.mint));
+ vlist.appendChild(el);
+ rowEls.set(row.mint, el);
+ if (Date.now() - (row.firstSeen || 0) < 1200) el.classList.add('mc-enter');
+ }
+ el.style.transform = `translateY(${i * ROW_H}px)`;
+ el.setAttribute('aria-selected', String(row.mint === selected));
+ el.innerHTML = rowInnerHtml(row);
+ // Enrich only what's on screen.
+ if (needsEnrich(row)) enrich.ensureRow(row.mint, enrichSize);
+ }
+ for (const [mint, el] of rowEls) {
+ if (!wantMints.has(mint)) { el.remove(); rowEls.delete(mint); }
+ }
+ }
+
+ function needsEnrich(row) {
+ // Signals rows arrive with intel; everything still wants safety + smart.
+ return row.safety === undefined || row.smart === undefined || row.intel === undefined;
+ }
+
+ function rowInnerHtml(row) {
+ const sym = escapeHtml(row.symbol || row.mint.slice(0, 4));
+ const name = escapeHtml(row.name || '');
+ const age = row.created_at ? ageFrom(row.created_at) : '';
+ const mc = formatCompactUsd(row.market_cap_usd);
+ return `
+ <span class="mc-row-top">
+ <span class="mc-row-sym">${sym}</span>
+ <span class="mc-row-name">${name}</span>
+ </span>
+ <span class="mc-row-age mc-num">${age}</span>
+ <span class="mc-row-meta">
+ <span class="mc-row-mc mc-num">MC <b>${mc}</b></span>
+ ${intelChip(row)}
+ ${safetyChip(row)}
+ ${smartChip(row)}
+ </span>`;
+ }
+
+ function intelChip(row) {
+ if (row.intel === undefined) return `<span class="mc-chip-skel"></span>`;
+ const q = row.intel?.quality_score;
+ if (q == null) return '';
+ const v = row.intel?.verdict;
+ return `<span class="mc-chip mc-chip--intel" title="Intel quality score">${Math.round(q)}${v?.label ? ` · ${escapeHtml(v.label)}` : ''}</span>`;
+ }
+ function safetyChip(row) {
+ if (row.safety === undefined) return `<span class="mc-chip-skel"></span>`;
+ if (row.safety === null) return '';
+ const c = verdictChip(row.safety.verdict);
+ return `<span class="mc-chip mc-chip--${c.tone}" title="Firewall verdict">${c.label}</span>`;
+ }
+ function smartChip(row) {
+ if (row.smart === undefined) return '';
+ if (!row.smart || !(row.smart.count > 0)) return '';
+ return `<span class="mc-chip mc-chip--smart" title="Smart-money buyers">◎ ${formatCompact(row.smart.count)}</span>`;
+ }
+
+ // ── state panels (loading / empty / degraded) ──────────────────────────────
+ function pickStatePanel(rows) {
+ if (source === 'radar' && radarState === 'degraded') {
+ return {
+ html: stateHtml('◎', 'Pre-launch radar is offline', 'The radar precursor stream isn’t live in this environment yet. Switch to <b>Live</b> for the new-launch firehose or <b>Signals</b> for scored launches.', 'Switch to Live'),
+ wire: (host) => host.querySelector('button')?.addEventListener('click', () => switchSource('live')),
+ };
+ }
+ if (source === 'radar' && radarState === 'loading') return { html: skeletonHtml() };
+ if (!rows.length) {
+ if (store.allRowsCount() === 0) {
+ // Source unreachable with nothing received yet — show an honest,
+ // actionable down-state instead of a skeleton that never resolves.
+ if (connState === 'down') {
+ const label = source === 'signals' ? 'Signals' : 'Live';
+ return {
+ html: stateHtml('⚠', `${label} feed is unreachable`, 'We can’t reach this source right now and we’re retrying automatically. No stale or placeholder rows are shown.', 'Retry now'),
+ wire: (host) => host.querySelector('button')?.addEventListener('click', () => { stopStreams(); store.resetFeed(); startSource(); }),
+ };
+ }
+ // Connecting / waiting for the first launch to stream in.
+ return { html: skeletonHtml() };
+ }
+ // Rows exist but all filtered out.
+ return {
+ html: stateHtml('⛶', 'No launches match your filters', 'Loosen the filters above to see the live feed.', 'Clear filters'),
+ wire: (host) => host.querySelector('button')?.addEventListener('click', () => { store.resetFilters(); }),
+ };
+ }
+ return null;
+ }
+ function skeletonHtml() {
+ return `<div>${Array.from({ length: 9 }, () => `<div class="mc-skelrow"><i></i><i></i></div>`).join('')}</div>`;
+ }
+ function stateHtml(ico, title, body, btn) {
+ return `<div class="mc-empty"><div class="mc-empty-ico" aria-hidden="true">${ico}</div><h3>${title}</h3><p>${body}</p>${btn ? `<button class="mc-chipbtn">${btn}</button>` : ''}</div>`;
+ }
+ let stateHost = null;
+ function ensureStateHost() {
+ if (!stateHost) {
+ stateHost = document.createElement('div');
+ stateHost.style.height = '100%';
+ body.appendChild(stateHost);
+ }
+ return stateHost;
+ }
+ function removeStateHost() {
+ if (stateHost) { stateHost.remove(); stateHost = null; }
+ }
+
+ // ── events ─────────────────────────────────────────────────────────────────
+ const onScroll = () => scheduleRender();
+ body.addEventListener('scroll', onScroll, { passive: true });
+
+ const unsubs = [
+ bus.on('feed:add', scheduleRender),
+ bus.on('feed:update', () => {
+ // Re-render only the touched row's chips if it's in the window; cheap full render otherwise.
+ scheduleRender();
+ }),
+ bus.on('feed:reset', () => { rowEls.forEach((el) => el.remove()); rowEls.clear(); scheduleRender(); }),
+ bus.on('filters', scheduleRender),
+ bus.on('views', renderViews),
+ bus.on('select', (mint) => {
+ for (const [m, el] of rowEls) el.setAttribute('aria-selected', String(m === mint));
+ scrollToMint(mint);
+ }),
+ bus.on('network', () => { stopStreams(); store.resetFeed(); startSource(); }),
+ ];
+
+ function scrollToMint(mint) {
+ const rows = store.visibleRows();
+ const idx = rows.findIndex((r) => r.mint === mint);
+ if (idx < 0) return;
+ const top = idx * ROW_H;
+ const viewTop = body.scrollTop;
+ const viewBot = viewTop + body.clientHeight;
+ if (top < viewTop) body.scrollTop = top;
+ else if (top + ROW_H > viewBot) body.scrollTop = top + ROW_H - body.clientHeight;
+ }
+
+ startSource();
+
+ return {
+ focusSearch() { filterbar.querySelector('[data-host="search"]')?.focus(); },
+ scrollTop() { body.scrollTop = 0; scheduleRender(); },
+ destroy() {
+ stopStreams();
+ body.removeEventListener('scroll', onScroll);
+ unsubs.forEach((u) => u());
+ if (rafToken) cancelAnimationFrame(rafToken);
+ rowEls.clear();
+ },
+ };
+}
diff --git a/src/mission-control/focus.js b/src/mission-control/focus.js
new file mode 100644
index 000000000..df423d431
--- /dev/null
+++ b/src/mission-control/focus.js
@@ -0,0 +1,348 @@
+/**
+ * Mission Control — focus / detail pane.
+ *
+ * The center cockpit. When a coin is selected anywhere (feed row, position, or
+ * keyboard), this pane fuses everything three.ws knows about it:
+ * • identity + market stats (GET /api/pump/coin)
+ * • a real price sparkline (GET /api/pump/price-history — never fabricated)
+ * • the intel breakdown (organic vs bundle, risk flags, verdict)
+ * • the firewall safety verdict (reused createSafetyPanel → /api/pump/safety)
+ * • smart-money flow (GET /api/intel/smart-money)
+ * • a buy/sell desk with size presets, a live quote, and real guarded execution
+ *
+ * The shell mounts ONCE per selection; enrichment patches update individual
+ * sections in place so the safety panel and live quote never thrash. Buy is
+ * disabled on a firewall `block`; the server enforces it regardless.
+ */
+
+import { createSafetyPanel } from '../shared/safety-panel.js';
+import { buy, sell, quote } from './trade.js';
+import {
+ escapeHtml,
+ shortAddress,
+ copyToClipboard,
+ formatCompactUsd,
+ formatCompact,
+ ageFrom,
+ formatPct,
+ explorerAddressUrl,
+ formatSol,
+} from './format.js';
+
+export function createFocusPane({ store, bus, enrich, mount }) {
+ mount.classList.add('mc-pane', 'mc-pane--focus');
+ mount.setAttribute('role', 'region');
+ mount.setAttribute('aria-label', 'Coin detail');
+ mount.innerHTML = `
+ <div class="mc-pane-head">
+ <span class="mc-pane-title">Focus</span>
+ <span class="mc-pane-head-spacer"></span>
+ <span class="mc-pane-count" data-host="net"></span>
+ </div>
+ <div class="mc-pane-body" data-host="body"></div>
+ `;
+ const body = mount.querySelector('[data-host="body"]');
+ const netEl = mount.querySelector('[data-host="net"]');
+ netEl.textContent = store.getNetwork();
+
+ let currentMint = null;
+ let seq = 0;
+ let safety = null;
+ let buyDisabled = false;
+ let coinDetail = null;
+ let quoteTimer = null;
+
+ const $ = (sel) => body.querySelector(sel);
+
+ function showIdle() {
+ currentMint = null;
+ teardownSafety();
+ body.innerHTML = `
+ <div class="mc-empty">
+ <div class="mc-empty-ico" aria-hidden="true">⌖</div>
+ <h3>Select a coin</h3>
+ <p>Click a launch in the feed, or use <kbd style="font-family:var(--font-mono)">j</kbd> / <kbd style="font-family:var(--font-mono)">k</kbd> to move and watch it light up here — intel, safety, smart-money, and one-keystroke trading.</p>
+ </div>`;
+ }
+
+ function teardownSafety() {
+ if (safety) { safety.destroy(); safety = null; }
+ }
+
+ function load(mint) {
+ if (!mint) { showIdle(); return; }
+ const fresh = mint !== currentMint;
+ currentMint = mint;
+ const mySeq = ++seq;
+ const row = store.getRow(mint) || { mint };
+ coinDetail = null;
+ if (fresh) renderShell(row);
+ else { updateHead(row); updateIntel(row); updateSmart(row); }
+
+ enrich.ensureIntel(mint);
+ enrich.ensureSmart(mint);
+
+ fetchCoin(mint).then((coin) => {
+ if (mySeq !== seq) return;
+ coinDetail = coin;
+ updateHead(store.getRow(mint) || row);
+ });
+ fetchSpark(mint).then((pts) => {
+ if (mySeq !== seq) return;
+ renderSpark(pts);
+ });
+ }
+
+ async function fetchCoin(mint) {
+ try {
+ const r = await fetch(`/api/pump/coin?mint=${encodeURIComponent(mint)}`, { headers: { accept: 'application/json' } });
+ if (!r.ok) return null;
+ return await r.json();
+ } catch { return null; }
+ }
+
+ async function fetchSpark(mint) {
+ try {
+ const to = Math.floor(Date.now() / 1000);
+ const from = to - 6 * 3600;
+ const r = await fetch(`/api/pump/price-history?mint=${encodeURIComponent(mint)}&interval=5m&from=${from}&to=${to}`, { headers: { accept: 'application/json' } });
+ if (!r.ok) return null;
+ const j = await r.json();
+ const arr = Array.isArray(j?.data) ? j.data : [];
+ return arr.map((d) => Number(d.c)).filter((n) => Number.isFinite(n));
+ } catch { return null; }
+ }
+
+ // ── shell (built once per selection) ────────────────────────────────────────
+ function renderShell(row) {
+ const mint = row.mint;
+ body.innerHTML = `
+ <div class="mc-focus">
+ <div class="mc-focus-head" data-host="head"></div>
+ <div class="mc-stats" data-host="stats"></div>
+ <div class="mc-spark-wrap"><div class="mc-section-h">Price · 6h</div><div data-host="sparkbody" style="color:var(--ink-faint,#666);font-size:.72rem">Loading chart…</div></div>
+ <div data-host="intel"></div>
+ <div data-host="safety"></div>
+ <div data-host="smart"></div>
+ <div class="mc-trade" data-host="trade"></div>
+ </div>`;
+ updateHead(row);
+ updateIntel(row);
+ updateSmart(row);
+ mountSafety(mint);
+ mountTrade();
+ }
+
+ function updateHead(row) {
+ const head = $('[data-host="head"]');
+ const stats = $('[data-host="stats"]');
+ if (!head || !stats) return;
+ const coin = coinDetail || {};
+ const mint = row.mint;
+ const sym = escapeHtml(row.symbol || coin.symbol || mint.slice(0, 4));
+ const name = escapeHtml(row.name || coin.name || '');
+ const img = row.image_uri || coin.image_uri || coin.image || '';
+ const mcUsd = coin.usd_market_cap ?? coin.market_cap ?? row.market_cap_usd ?? null;
+ const created = coin.created_timestamp ? Math.floor(coin.created_timestamp / 1000) : row.created_at;
+ const intel = row.intel && !row.intel._none ? row.intel : null;
+ const smart = row.smart;
+ const socials = [
+ (row.twitter || coin.twitter) && { href: row.twitter || coin.twitter, label: 'X' },
+ (row.telegram || coin.telegram) && { href: row.telegram || coin.telegram, label: 'TG' },
+ (row.website || coin.website) && { href: row.website || coin.website, label: 'Web' },
+ ].filter(Boolean);
+
+ head.innerHTML = `
+ ${img ? `<img class="mc-focus-img" src="${escapeHtml(img)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'" />` : '<div class="mc-focus-img" aria-hidden="true"></div>'}
+ <div class="mc-focus-id">
+ <h2>${sym} <span class="mc-focus-name">${name}</span></h2>
+ <div class="mc-focus-addr">
+ <span class="mc-mono" title="${escapeHtml(mint)}">${escapeHtml(shortAddress(mint, 6, 6))}</span>
+ <button class="mc-iconbtn" data-act="copy" title="Copy mint" style="min-width:24px;height:22px;padding:0 6px;font-size:.7rem">⧉</button>
+ <a href="${escapeHtml(explorerAddressUrl(mint, store.getNetwork()))}" target="_blank" rel="noopener">Explorer ↗</a>
+ </div>
+ ${socials.length ? `<div class="mc-focus-socials">${socials.map((s) => `<a href="${escapeHtml(s.href)}" target="_blank" rel="noopener">${escapeHtml(s.label)}</a>`).join('')}</div>` : ''}
+ </div>`;
+ head.querySelector('[data-act="copy"]')?.addEventListener('click', async () => {
+ const ok = await copyToClipboard(mint);
+ const b = head.querySelector('[data-act="copy"]');
+ if (b) { b.textContent = ok ? '✓' : '⧉'; setTimeout(() => { if (b) b.textContent = '⧉'; }, 1100); }
+ });
+
+ stats.innerHTML = `
+ <div class="mc-stat"><span>Market cap</span><b>${formatCompactUsd(mcUsd)}</b></div>
+ <div class="mc-stat"><span>Age</span><b>${created ? ageFrom(created) : '—'}</b></div>
+ <div class="mc-stat"><span>Intel</span><b>${intel?.quality_score != null ? Math.round(intel.quality_score) : '—'}</b></div>
+ <div class="mc-stat"><span>Smart $</span><b>${smart?.computed ? Math.round(smart.smart_money_score || 0) : '—'}</b></div>
+ <div class="mc-stat"><span>Buyers</span><b>${intel?.unique_buyers != null ? formatCompact(intel.unique_buyers) : '—'}</b></div>
+ <div class="mc-stat"><span>B/S ratio</span><b>${intel?.buy_sell_ratio != null ? Number(intel.buy_sell_ratio).toFixed(2) : '—'}</b></div>`;
+ }
+
+ function updateIntel(row) {
+ const host = $('[data-host="intel"]');
+ if (!host) return;
+ const intel = row.intel && !row.intel._none ? row.intel : (row.intel === undefined ? undefined : null);
+ if (intel === undefined) { host.innerHTML = `<div class="mc-section-h">Intel</div><div class="mc-chip-skel" style="width:100%"></div>`; return; }
+ if (!intel) {
+ host.innerHTML = `<div class="mc-section-h">Intel</div><p style="color:var(--ink-faint,#666);font-size:.75rem;margin:0">Structural intel is still being gathered for this launch.</p>`;
+ return;
+ }
+ const flags = Array.isArray(intel.risk_flags) ? intel.risk_flags : [];
+ const v = intel.verdict;
+ const tone = v?.tone === 'success' ? 'allow' : v?.tone === 'danger' ? 'block' : v?.tone === 'warn' ? 'warn' : 'unknown';
+ const bars = [
+ ['Organic', intel.organic_score],
+ ['Bundle', intel.bundle_score],
+ ['Snipe', intel.snipe_ratio != null ? intel.snipe_ratio * 100 : null],
+ ['Top-10', intel.concentration_top10 != null ? intel.concentration_top10 * 100 : null],
+ ].filter(([, val]) => val != null);
+ host.innerHTML = `
+ <div class="mc-section-h">Intel breakdown ${v?.label ? `<span class="mc-chip mc-chip--${tone}" style="margin-left:6px">${escapeHtml(v.label)}</span>` : ''}</div>
+ <div class="mc-stats" style="grid-template-columns:repeat(auto-fit,minmax(76px,1fr))">
+ ${bars.map(([label, val]) => `<div class="mc-stat"><span>${escapeHtml(label)}</span><b>${Math.round(Number(val))}${label === 'Organic' || label === 'Bundle' ? '' : '%'}</b></div>`).join('')}
+ </div>
+ ${flags.length ? `<ul class="mc-smart-wallets" style="margin-top:8px">${flags.slice(0, 5).map((f) => `<li style="color:var(--warn,#fbbf24)">⚠ ${escapeHtml(String(f).replace(/_/g, ' '))}</li>`).join('')}</ul>` : ''}`;
+ }
+
+ function updateSmart(row) {
+ const host = $('[data-host="smart"]');
+ if (!host) return;
+ const smart = row.smart;
+ if (smart === undefined) { host.innerHTML = `<div class="mc-section-h">Smart money</div><div class="mc-chip-skel" style="width:100%"></div>`; return; }
+ if (!smart || smart.computed === false) {
+ host.innerHTML = `<div class="mc-section-h">Smart money</div><p style="color:var(--ink-faint,#666);font-size:.75rem;margin:0">Not enough on-chain history yet to score who's buying this coin.</p>`;
+ return;
+ }
+ const score = Math.round(smart.smart_money_score || 0);
+ const wallets = Array.isArray(smart.wallets) ? smart.wallets.slice(0, 4) : [];
+ host.innerHTML = `
+ <div class="mc-section-h">Smart money <span class="mc-num" style="margin-left:auto;color:var(--accent,#7dd3fc)">${score}/100${smart.count ? ` · ${smart.count} wallets` : ''}</span></div>
+ <div class="mc-smart-bar"><i style="width:${Math.max(2, score)}%"></i></div>
+ ${smart.sybil_flag ? `<p style="color:var(--warn,#fbbf24);font-size:.72rem;margin:8px 0 0">⚠ One funder cluster dominates the buyers (${Math.round((smart.sybil_share || 0) * 100)}%) — possible sybil.</p>` : ''}
+ ${wallets.length ? `<ul class="mc-smart-wallets">${wallets.map((w) => `<li><span class="mc-mono">${escapeHtml(shortAddress(w.address))}</span> <b>${Math.round(w.realized_score || 0)}</b> score${w.win_rate != null ? ` · ${Math.round(w.win_rate * 100)}% win` : ''}${w.buy_sol ? ` · ${formatSol(w.buy_sol)}◎` : ''}</li>`).join('')}</ul>` : ''}`;
+ }
+
+ function mountSafety(mint) {
+ teardownSafety();
+ const host = $('[data-host="safety"]');
+ if (!host) return;
+ safety = createSafetyPanel({
+ onVerdict: (v) => { buyDisabled = v?.verdict === 'block'; updateTradeButtons(); },
+ });
+ host.innerHTML = `<div class="mc-section-h">Safety firewall</div>`;
+ host.appendChild(safety.el);
+ safety.loadForMint({ mint, network: store.getNetwork(), amountSol: store.getActiveSize() });
+ }
+
+ function mountTrade() {
+ const host = $('[data-host="trade"]');
+ if (!host) return;
+ const presets = store.getPresets();
+ const active = store.getActiveSize();
+ host.innerHTML = `
+ <div class="mc-section-h">Trade · from ${escapeHtml(store.getAgent()?.name || 'agent')}</div>
+ <div class="mc-sizes" role="group" aria-label="Buy size (SOL)">
+ ${presets.map((p, i) => `<button class="mc-size" data-size="${p}" aria-pressed="${p === active}">${p}<span class="mc-size-kbd">${i + 1}</span></button>`).join('')}
+ <span style="color:var(--ink-faint,#666);font-size:.72rem">SOL</span>
+ </div>
+ <div class="mc-trade-actions">
+ <button class="mc-btn mc-btn--buy" data-act="buy"><kbd>b</kbd> Buy</button>
+ <button class="mc-btn mc-btn--sell" data-act="sell"><kbd>s</kbd> Sell all</button>
+ </div>
+ <div class="mc-trade-note is-dim" data-host="note" role="status" aria-live="polite">Pick a size — a live quote appears here.</div>`;
+ host.querySelectorAll('[data-size]').forEach((b) => {
+ b.addEventListener('click', () => store.setActiveSize(Number(b.dataset.size)));
+ });
+ host.querySelector('[data-act="buy"]').addEventListener('click', () => doBuy());
+ host.querySelector('[data-act="sell"]').addEventListener('click', () => doSell());
+ updateTradeButtons();
+ refreshQuote();
+ }
+
+ function updateTradeButtons() {
+ const buyBtn = $('[data-act="buy"]');
+ if (!buyBtn) return;
+ const noAgent = !store.getAgent();
+ buyBtn.disabled = buyDisabled || noAgent;
+ buyBtn.title = buyDisabled ? 'Firewall blocked — buying disabled' : noAgent ? 'Select an agent first' : '';
+ body.querySelectorAll('[data-size]').forEach((b) => b.setAttribute('aria-pressed', String(Number(b.dataset.size) === store.getActiveSize())));
+ }
+
+ function refreshQuote() {
+ const note = $('[data-host="note"]');
+ if (!note || !currentMint) return;
+ clearTimeout(quoteTimer);
+ const size = store.getActiveSize();
+ note.className = 'mc-trade-note is-dim';
+ note.textContent = 'Pricing…';
+ const mySeq = seq;
+ const mint = currentMint;
+ quoteTimer = setTimeout(async () => {
+ try {
+ const q = await quote({ store, side: 'buy', mint, solAmount: size });
+ if (mySeq !== seq || !$('[data-host="note"]')) return;
+ const n = $('[data-host="note"]');
+ const out = q?.out;
+ const impact = q?.price_impact_pct;
+ const guard = q?.guard;
+ if (guard) { n.className = 'mc-trade-note is-err'; n.textContent = `⚠ ${guard.message}`; return; }
+ n.className = impact >= 8 ? 'mc-trade-note is-warn' : 'mc-trade-note is-dim';
+ n.innerHTML = `${size} SOL → <b style="color:var(--ink-bright,#fff)">${formatCompact(out?.amount)}</b> tokens · impact ${impact != null ? Number(impact).toFixed(1) + '%' : '—'}${impact >= 8 ? ' ⚠' : ''}`;
+ } catch (e) {
+ if (mySeq !== seq || !$('[data-host="note"]')) return;
+ const n = $('[data-host="note"]');
+ n.className = 'mc-trade-note is-dim';
+ n.textContent = e?.code === 'no_agent' ? 'Select a trading agent to quote.' : 'Quote unavailable right now.';
+ }
+ }, 350);
+ }
+
+ function renderSpark(pts) {
+ const host = $('[data-host="sparkbody"]');
+ if (!host) return;
+ if (!pts || pts.length < 2) { host.textContent = 'No price history yet for this coin.'; return; }
+ const w = 100, h = 36;
+ const min = Math.min(...pts), max = Math.max(...pts);
+ const span = max - min || 1;
+ const step = w / (pts.length - 1);
+ const d = pts.map((p, i) => `${(i * step).toFixed(2)},${(h - ((p - min) / span) * h).toFixed(2)}`).join(' ');
+ const up = pts[pts.length - 1] >= pts[0];
+ const col = up ? 'var(--success,#4ade80)' : 'var(--danger,#f87171)';
+ const change = pts[0] ? ((pts[pts.length - 1] - pts[0]) / pts[0]) * 100 : 0;
+ host.innerHTML = `
+ <svg class="mc-spark" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none" role="img" aria-label="Price chart, ${formatPct(change)} over 6 hours">
+ <polyline points="${d}" fill="none" stroke="${col}" stroke-width="1.4" vector-effect="non-scaling-stroke" stroke-linejoin="round" stroke-linecap="round" />
+ </svg>
+ <div class="mc-num" style="margin-top:4px;color:${col};font-size:.74rem">${formatPct(change)} · 6h</div>`;
+ }
+
+ async function doBuy() {
+ if (!currentMint) { return; }
+ await buy({ store, bus, mint: currentMint, solAmount: store.getActiveSize() });
+ }
+ async function doSell() {
+ if (!currentMint) { return; }
+ await sell({ store, bus, mint: currentMint });
+ }
+
+ const unsubs = [
+ bus.on('select', (mint) => load(mint)),
+ bus.on('size', () => { updateTradeButtons(); refreshQuote(); if (safety && currentMint) safety.loadForMint({ mint: currentMint, network: store.getNetwork(), amountSol: store.getActiveSize() }); }),
+ bus.on('presets', () => { if (currentMint) mountTrade(); }),
+ bus.on('agent', () => { if (currentMint) mountTrade(); }),
+ bus.on('network', () => { netEl.textContent = store.getNetwork(); if (currentMint) load(currentMint); }),
+ bus.on('feed:update', (row) => { if (row.mint === currentMint) { updateHead(row); updateIntel(row); updateSmart(row); } }),
+ bus.on('action:buy', () => doBuy()),
+ bus.on('action:sell', () => doSell()),
+ ];
+
+ showIdle();
+
+ return {
+ destroy() {
+ teardownSafety();
+ clearTimeout(quoteTimer);
+ unsubs.forEach((u) => u());
+ },
+ };
+}
diff --git a/src/mission-control/index.js b/src/mission-control/index.js
new file mode 100644
index 000000000..bc9593aa1
--- /dev/null
+++ b/src/mission-control/index.js
@@ -0,0 +1,252 @@
+/**
+ * Mission Control — the real-time trading terminal.
+ *
+ * A keyboard-driven cockpit that fuses every live signal three.ws computes —
+ * the launch firehose, intel scores, firewall verdicts, smart-money flow, and
+ * the agent's own streaming positions — into one screen, and executes real
+ * firewall + MEV-gated trades from the agent wallet.
+ *
+ * mountMissionControl(root) resolves the signed-in user and their trading
+ * agents, builds the shell + three live panes, and owns the full lifecycle
+ * (every SSE stream, timer, and listener is torn down on unmount / route change).
+ *
+ * $THREE is the only coin three.ws promotes. Every other mint shown here is live
+ * market data the cockpit assesses — it names and recommends no other token.
+ */
+
+import { getMe } from '../account.js';
+import { loadUserAgents } from '../memory-seed.js';
+import { fetchAgentSolanaWallet } from '../agent-solana-wallet.js';
+
+import { injectMissionControlStyles } from './styles.js';
+import { createBus } from './realtime.js';
+import { createStore } from './store.js';
+import { createEnricher } from './enrich.js';
+import { createFeedPane } from './feed.js';
+import { createPositionsPane } from './positions.js';
+import { createFocusPane } from './focus.js';
+import { createKeyboard } from './keyboard.js';
+import { escapeHtml, formatSol, shortAddress } from './format.js';
+
+export function mountMissionControl(root, opts = {}) {
+ if (!root) throw new Error('mountMissionControl requires a root element');
+ injectMissionControlStyles();
+
+ const bus = createBus();
+ let store = null;
+ let enricher = null;
+ const panes = [];
+ let keyboard = null;
+ let balanceTimer = null;
+ const cleanups = [];
+ let destroyed = false;
+
+ root.innerHTML = `<div class="mc-root" data-host="mc"><div class="mc-empty" style="height:100%"><div class="mc-empty-ico">◎</div><h3>Booting Mission Control…</h3><p>Connecting to the live launch firehose.</p></div></div>`;
+ const rootEl = root.querySelector('[data-host="mc"]');
+
+ (async () => {
+ // Resolve session + agents in parallel; either failing degrades gracefully
+ // to a read-only cockpit rather than a dead page.
+ const [user, agents] = await Promise.all([
+ getMe().catch(() => null),
+ loadUserAgents().catch(() => []),
+ ]);
+ if (destroyed) return;
+
+ const tradable = (agents || []).filter((a) => a && (a.solana_address || a.meta?.solana_address || a.wallet_ready || a.walletReady));
+
+ store = createStore({ bus, userId: user?.id || 'anon' });
+ enricher = createEnricher({ store });
+ if (opts.network === 'devnet') store.setNetwork('devnet');
+ if (tradable[0]) store.setAgent(normalizeAgent(tradable[0]));
+
+ buildShell({ user, agents: tradable });
+ })();
+
+ function normalizeAgent(a) {
+ return {
+ id: a.id,
+ name: a.name || 'Agent',
+ solana_address: a.solana_address || a.meta?.solana_address || null,
+ };
+ }
+
+ function buildShell({ user, agents }) {
+ rootEl.innerHTML = `
+ ${topbarHtml({ user, agents })}
+ <div class="mc-main" data-host="main">
+ <div class="mc-pane" data-host="feed"></div>
+ <div class="mc-pane" data-host="focus"></div>
+ <div class="mc-pane" data-host="positions"></div>
+ </div>
+ <div class="mc-mobilebar" role="tablist" aria-label="Panels">
+ <button role="tab" data-mpane="feed" aria-selected="true">Feed</button>
+ <button role="tab" data-mpane="focus" aria-selected="false">Focus</button>
+ <button role="tab" data-mpane="positions" aria-selected="false">Positions</button>
+ </div>
+ `;
+
+ // panes
+ const feed = createFeedPane({ store, bus, enrich: enricher, mount: rootEl.querySelector('[data-host="feed"]') });
+ const focus = createFocusPane({ store, bus, enrich: enricher, mount: rootEl.querySelector('[data-host="focus"]') });
+ const positions = createPositionsPane({ store, bus, mount: rootEl.querySelector('[data-host="positions"]') });
+ panes.push(feed, focus, positions);
+ keyboard = createKeyboard({ store, bus, feed });
+
+ wireTopbar({ agents });
+ wireMobileBar();
+ wireConnPills();
+ wireExpressBadge();
+
+ // Auto-select the first launch that streams in (one-shot) for instant signal.
+ const offFirst = bus.on('feed:add', (row) => {
+ if (!store.getSelected()) { store.select(row.mint); }
+ offFirst();
+ });
+ cleanups.push(offFirst);
+
+ startBalance();
+ }
+
+ // ── topbar ────────────────────────────────────────────────────────────────
+ function topbarHtml({ user, agents }) {
+ let agentControl;
+ if (agents.length) {
+ agentControl = `
+ <label class="mc-ctrl"><span class="mc-sr">Trading agent</span>
+ <select class="mc-select" data-host="agentsel" aria-label="Trading agent">
+ ${agents.map((a) => `<option value="${escapeHtml(a.id)}">${escapeHtml(a.name || 'Agent')}</option>`).join('')}
+ </select>
+ </label>`;
+ } else if (user) {
+ agentControl = `<a class="mc-select" href="/create-agent" title="Create an agent wallet to trade">+ Create a wallet</a>`;
+ } else {
+ agentControl = `<a class="mc-select" href="/login?next=%2Fterminal" title="Sign in to trade from your agent wallet">Sign in to trade</a>`;
+ }
+ return `
+ <div class="mc-topbar">
+ <a class="mc-brand" href="/" title="three.ws home">
+ <img class="mc-brand-logo" src="/three.svg" alt="" width="22" height="22" />
+ <b>Mission Control</b><span>Terminal</span>
+ </a>
+ <span class="mc-topbar-spacer"></span>
+ <span class="mc-balance" data-host="balance" hidden>◎ <b data-host="balsol">—</b></span>
+ ${agentControl}
+ <label class="mc-ctrl"><span class="mc-sr">Network</span>
+ <select class="mc-select" data-host="netsel" aria-label="Network">
+ <option value="mainnet">Mainnet</option>
+ <option value="devnet">Devnet</option>
+ </select>
+ </label>
+ <div class="mc-conn-group">
+ <span class="mc-conn" data-host="conn-feed" data-state="reconnecting"><span class="mc-conn-dot"></span>Feed</span>
+ <span class="mc-conn" data-host="conn-pos" data-state="reconnecting"><span class="mc-conn-dot"></span>Positions</span>
+ </div>
+ <button class="mc-iconbtn" data-host="help" aria-label="Keyboard shortcuts" title="Keyboard shortcuts (?)">?</button>
+ </div>`;
+ }
+
+ function wireTopbar({ agents }) {
+ const agentSel = rootEl.querySelector('[data-host="agentsel"]');
+ if (agentSel) {
+ agentSel.value = store.getAgent()?.id || '';
+ agentSel.addEventListener('change', () => {
+ const a = agents.find((x) => x.id === agentSel.value);
+ if (a) store.setAgent(normalizeAgent(a));
+ });
+ }
+ const netSel = rootEl.querySelector('[data-host="netsel"]');
+ netSel.value = store.getNetwork();
+ netSel.addEventListener('change', () => store.setNetwork(netSel.value));
+
+ rootEl.querySelector('[data-host="help"]').addEventListener('click', () => keyboard?.openHelp());
+ }
+
+ function wireMobileBar() {
+ const buttons = [...rootEl.querySelectorAll('[data-mpane]')];
+ const main = rootEl.querySelector('[data-host="main"]');
+ const setActive = (name) => {
+ for (const b of buttons) b.setAttribute('aria-selected', String(b.dataset.mpane === name));
+ for (const key of ['feed', 'focus', 'positions']) {
+ rootEl.querySelector(`[data-host="${key}"]`)?.classList.toggle('is-active', key === name);
+ }
+ main.classList.toggle('show-positions', name === 'positions');
+ };
+ for (const b of buttons) b.addEventListener('click', () => setActive(b.dataset.mpane));
+ setActive('feed');
+ // jump to Focus on the phone when a coin is picked
+ cleanups.push(bus.on('select', () => {
+ if (window.matchMedia('(max-width: 760px)').matches) setActive('focus');
+ }));
+ }
+
+ function wireConnPills() {
+ const feedPill = rootEl.querySelector('[data-host="conn-feed"]');
+ const posPill = rootEl.querySelector('[data-host="conn-pos"]');
+ cleanups.push(bus.on('conn:feed', (s) => feedPill?.setAttribute('data-state', s)));
+ cleanups.push(bus.on('conn:positions', (s) => posPill?.setAttribute('data-state', s)));
+ }
+
+ function wireExpressBadge() {
+ // Reflect express mode in the brand chip so the user always knows the trade
+ // confirmation state at a glance.
+ const chip = rootEl.querySelector('.mc-brand span');
+ const refresh = () => {
+ const a = store.getAgent();
+ const express = a && store.isExpress(a.id);
+ if (chip) {
+ chip.textContent = express ? 'Express' : 'Terminal';
+ chip.style.color = express ? 'var(--warn,#fbbf24)' : '';
+ chip.style.borderColor = express ? 'color-mix(in srgb, var(--warn,#fbbf24) 40%, transparent)' : '';
+ }
+ };
+ cleanups.push(bus.on('express', refresh));
+ cleanups.push(bus.on('agent', refresh));
+ refresh();
+ }
+
+ // ── balance ───────────────────────────────────────────────────────────────
+ function startBalance() {
+ const refresh = async () => {
+ const agent = store.getAgent();
+ const wrap = rootEl.querySelector('[data-host="balance"]');
+ const sol = rootEl.querySelector('[data-host="balsol"]');
+ if (!agent?.id || !wrap || !sol) { if (wrap) wrap.hidden = true; return; }
+ try {
+ const r = await fetchAgentSolanaWallet(agent.id, store.getNetwork());
+ if (r.status === 'ok' && r.data) {
+ wrap.hidden = false;
+ sol.textContent = r.data.sol != null ? formatSol(r.data.sol) : '—';
+ wrap.title = r.data.address ? shortAddress(r.data.address, 6, 6) : '';
+ } else {
+ wrap.hidden = true;
+ }
+ } catch { /* transient — keep last */ }
+ };
+ refresh();
+ cleanups.push(bus.on('agent', refresh));
+ cleanups.push(bus.on('network', refresh));
+ cleanups.push(bus.on('trade:done', refresh));
+ balanceTimer = setInterval(refresh, 30_000);
+ }
+
+ // ── teardown ────────────────────────────────────────────────────────────────
+ function destroy() {
+ if (destroyed) return;
+ destroyed = true;
+ if (balanceTimer) clearInterval(balanceTimer);
+ for (const c of cleanups) { try { c(); } catch { /* ignore */ } }
+ for (const p of panes) { try { p.destroy?.(); } catch { /* ignore */ } }
+ try { keyboard?.destroy?.(); } catch { /* ignore */ }
+ try { enricher?.clear?.(); } catch { /* ignore */ }
+ try { bus.clear?.(); } catch { /* ignore */ }
+ root.innerHTML = '';
+ }
+
+ // Clean up on SPA-style navigation away or full unload.
+ const onPageHide = () => destroy();
+ window.addEventListener('pagehide', onPageHide, { once: true });
+ cleanups.push(() => window.removeEventListener('pagehide', onPageHide));
+
+ return { destroy };
+}
diff --git a/src/mission-control/keyboard.js b/src/mission-control/keyboard.js
new file mode 100644
index 000000000..a64cb5a15
--- /dev/null
+++ b/src/mission-control/keyboard.js
@@ -0,0 +1,128 @@
+/**
+ * Mission Control — keyboard controller + shortcut overlay.
+ *
+ * Keyboard-first cockpit. Movement and trading never require the mouse:
+ * j / ↓ · k / ↑ move the selection through the visible feed
+ * b · s buy the preset size · sell the whole position
+ * 1…6 pick a buy-size preset
+ * / focus the feed filter
+ * x toggle express mode (confirm-on-first-use ↔ instant)
+ * ? this overlay · Esc closes it / clears selection
+ *
+ * Shortcuts are suppressed while typing in an input so the filter box behaves.
+ */
+
+import { toast } from './ui.js';
+import { escapeHtml } from './format.js';
+
+const SHORTCUTS = [
+ ['j / ↓', 'Next launch'],
+ ['k / ↑', 'Previous launch'],
+ ['b', 'Buy preset size'],
+ ['s', 'Sell entire position'],
+ ['1 – 6', 'Choose buy size'],
+ ['/', 'Filter the feed'],
+ ['x', 'Toggle express trading'],
+ ['g', 'Jump to top of feed'],
+ ['?', 'Show / hide this help'],
+ ['Esc', 'Close help · clear selection'],
+];
+
+export function createKeyboard({ store, bus, feed }) {
+ let overlay = null;
+
+ function isEditable(el) {
+ if (!el) return false;
+ const tag = el.tagName;
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable;
+ }
+
+ function move(delta) {
+ const rows = store.visibleRows();
+ if (!rows.length) return;
+ const cur = store.getSelected();
+ let idx = rows.findIndex((r) => r.mint === cur);
+ if (idx < 0) idx = delta > 0 ? -1 : 0;
+ const next = Math.max(0, Math.min(rows.length - 1, idx + delta));
+ store.select(rows[next].mint);
+ }
+
+ function chooseSize(n) {
+ const presets = store.getPresets();
+ if (presets[n - 1] != null) store.setActiveSize(presets[n - 1]);
+ }
+
+ function toggleOverlay(force) {
+ const show = force != null ? force : !overlay;
+ if (show && !overlay) {
+ overlay = document.createElement('div');
+ overlay.className = 'mc-overlay';
+ overlay.setAttribute('role', 'dialog');
+ overlay.setAttribute('aria-modal', 'true');
+ overlay.setAttribute('aria-label', 'Keyboard shortcuts');
+ overlay.innerHTML = `
+ <div class="mc-overlay-card">
+ <h2>Keyboard shortcuts</h2>
+ <div class="mc-keys">
+ ${SHORTCUTS.map(([k, d]) => `<div class="mc-keyrow"><span>${escapeHtml(d)}</span><kbd>${escapeHtml(k)}</kbd></div>`).join('')}
+ </div>
+ <p style="margin:16px 0 0;color:var(--ink-faint,#666);font-size:.72rem">Every trade runs through the firewall + MEV engine and is signed by your agent wallet, spend-guarded and audited. $THREE is the only coin three.ws promotes — every other mint here is live market data.</p>
+ </div>`;
+ overlay.addEventListener('mousedown', (e) => { if (e.target === overlay) toggleOverlay(false); });
+ document.body.appendChild(overlay);
+ } else if (!show && overlay) {
+ overlay.remove();
+ overlay = null;
+ }
+ }
+
+ function onKey(e) {
+ // Always allow Escape to close the overlay, even from an input.
+ if (e.key === 'Escape') {
+ if (overlay) { toggleOverlay(false); e.preventDefault(); return; }
+ if (isEditable(e.target)) { e.target.blur(); return; }
+ return;
+ }
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ if (isEditable(e.target)) return;
+ if (overlay && e.key !== '?') { /* let ? toggle; other keys close */ if (e.key !== 'Escape') { toggleOverlay(false); } }
+
+ switch (e.key) {
+ case 'j': case 'ArrowDown': e.preventDefault(); move(1); break;
+ case 'k': case 'ArrowUp': e.preventDefault(); move(-1); break;
+ case 'b': e.preventDefault(); requireSelection() && bus.emit('action:buy'); break;
+ case 's': e.preventDefault(); requireSelection() && bus.emit('action:sell'); break;
+ case '/': e.preventDefault(); feed?.focusSearch?.(); break;
+ case 'g': e.preventDefault(); feed?.scrollTop?.(); break;
+ case '?': e.preventDefault(); toggleOverlay(); break;
+ case 'x': {
+ e.preventDefault();
+ const agent = store.getAgent();
+ if (!agent) { toast('Select an agent first.', { tone: 'warn' }); break; }
+ const on = store.toggleExpress(agent.id);
+ toast(on ? 'Express trading on — buys & sells execute instantly.' : 'Express off — each trade asks once more.', { tone: on ? 'warn' : 'info' });
+ break;
+ }
+ default:
+ if (/^[1-6]$/.test(e.key)) { e.preventDefault(); chooseSize(Number(e.key)); }
+ }
+ }
+
+ function requireSelection() {
+ if (store.getSelected()) return true;
+ const rows = store.visibleRows();
+ if (rows.length) { store.select(rows[0].mint); }
+ toast('Pick a coin first (j / k to move).', { tone: 'info', ms: 1800 });
+ return false;
+ }
+
+ document.addEventListener('keydown', onKey);
+
+ return {
+ openHelp: () => toggleOverlay(true),
+ destroy() {
+ document.removeEventListener('keydown', onKey);
+ if (overlay) { overlay.remove(); overlay = null; }
+ },
+ };
+}
diff --git a/src/mission-control/positions.js b/src/mission-control/positions.js
new file mode 100644
index 000000000..a112e8bf9
--- /dev/null
+++ b/src/mission-control/positions.js
@@ -0,0 +1,335 @@
+/**
+ * Mission Control — positions pane.
+ *
+ * The active agent's live book. Two real, fused sources:
+ * • SSE /api/sniper/stream — streaming unrealized PnL on the agent's sniper
+ * positions (open → live %, close → realized), filtered to this agent.
+ * • GET /api/agents/:id/solana/holdings — the wallet's real on-chain token
+ * balances, so discretionary buys made right here in the terminal show up as
+ * spot positions you can one-tap exit.
+ * Backlog comes from /api/sniper/leaderboard (open) + /api/sniper/history (closed).
+ *
+ * Quick-exit sells the full balance through the same guarded trade path.
+ */
+
+import { createSseClient } from './realtime.js';
+import { sell } from './trade.js';
+import {
+ escapeHtml,
+ formatSol,
+ formatSolDelta,
+ formatPct,
+ formatCompact,
+ signClass,
+ timeAgo,
+} from './format.js';
+
+const CLOSED_CAP = 12;
+const HOLDINGS_REFRESH_MS = 30_000;
+
+export function createPositionsPane({ store, bus, mount }) {
+ mount.classList.add('mc-pane', 'mc-pane--positions');
+ mount.setAttribute('role', 'region');
+ mount.setAttribute('aria-label', 'Your positions');
+ mount.innerHTML = `
+ <div class="mc-pane-head">
+ <span class="mc-pane-title">Positions</span>
+ <span class="mc-pane-head-spacer"></span>
+ <span class="mc-pane-count" data-host="count"></span>
+ </div>
+ <div class="mc-pos-summary" data-host="summary"></div>
+ <div class="mc-pane-body" data-host="body" aria-live="polite"></div>
+ `;
+ const body = mount.querySelector('[data-host="body"]');
+ const summary = mount.querySelector('[data-host="summary"]');
+ const countEl = mount.querySelector('[data-host="count"]');
+
+ const positions = new Map(); // key -> position
+ const closed = []; // recently closed, newest first
+ let sse = null;
+ let holdingsTimer = null;
+ let rafToken = 0;
+ let agentId = store.getAgent()?.id || null;
+ let summaryTween = { from: 0, to: 0, t0: 0, raf: 0 };
+
+ const keyOf = (p) => (p.source === 'spot' ? `spot:${p.mint}` : `snipe:${p.id}`);
+
+ function normSniper(d, status) {
+ return {
+ id: d.id,
+ mint: d.mint,
+ symbol: d.symbol || (d.mint ? d.mint.slice(0, 4) : '—'),
+ name: d.name || '',
+ source: 'sniper',
+ status: status || (d.status === 'closed' ? 'closed' : 'open'),
+ entry_sol: d.entry_sol ?? null,
+ current_sol: d.current_sol ?? null,
+ pnl_pct: d.pnl_pct ?? d.unrealized_pct ?? null,
+ pnl_sol: d.pnl_sol ?? null,
+ exit_reason: d.exit_reason || null,
+ at: d.at || d.closed_at || d.opened_at || null,
+ };
+ }
+
+ function upsert(p) {
+ positions.set(keyOf(p), p);
+ }
+
+ function ingestSniper(d, status) {
+ if (!d?.mint) return;
+ const p = normSniper(d, status);
+ if (p.status === 'closed') {
+ positions.delete(keyOf({ source: 'sniper', id: p.id }));
+ closed.unshift(p);
+ closed.splice(CLOSED_CAP);
+ } else {
+ upsert(p);
+ }
+ }
+
+ // ── backlog ────────────────────────────────────────────────────────────────
+ async function loadBacklog() {
+ if (!agentId) return;
+ const net = store.getNetwork();
+ try {
+ const r = await fetch(`/api/sniper/leaderboard?network=${net}`, { headers: { accept: 'application/json' } });
+ if (r.ok) {
+ const data = await r.json();
+ for (const p of data?.positions || []) {
+ if (p.agent_id === agentId) ingestSniper(p, 'open');
+ }
+ }
+ } catch { /* degrade — holdings + stream still populate the pane */ }
+ try {
+ const r = await fetch(`/api/sniper/history?network=${net}&agent_id=${encodeURIComponent(agentId)}&limit=${CLOSED_CAP}`, { headers: { accept: 'application/json' } });
+ if (r.ok) {
+ const data = await r.json();
+ for (const t of data?.trades || []) {
+ closed.push(normSniper({ ...t, current_sol: t.exit_sol }, 'closed'));
+ }
+ closed.sort((a, b) => new Date(b.at || 0) - new Date(a.at || 0));
+ closed.splice(CLOSED_CAP);
+ }
+ } catch { /* closed history is best-effort */ }
+ scheduleRender();
+ }
+
+ // ── holdings (spot) ──────────────────────────────────────────────────────────
+ async function refreshHoldings() {
+ const agent = store.getAgent();
+ if (!agent?.id) return;
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(agent.id)}/solana/holdings?network=${store.getNetwork()}`, { credentials: 'include' });
+ if (!r.ok) return;
+ const data = await r.json();
+ const tokens = (data?.data?.tokens || []).filter((t) => !t.is_usdc);
+ const seen = new Set();
+ for (const t of tokens) {
+ seen.add(`spot:${t.mint}`);
+ // Skip if an open sniper position already represents this mint (the
+ // sniper row carries live PnL the bare holding can't).
+ const hasSniper = [...positions.values()].some((p) => p.source === 'sniper' && p.mint === t.mint && p.status === 'open');
+ if (hasSniper) { positions.delete(`spot:${t.mint}`); continue; }
+ const row = store.getRow(t.mint);
+ upsert({
+ mint: t.mint,
+ symbol: row?.symbol || t.mint.slice(0, 4),
+ name: row?.name || '',
+ source: 'spot',
+ status: 'open',
+ ui_amount: t.ui_amount,
+ amount_raw: t.amount_raw,
+ decimals: t.decimals,
+ market_cap_usd: row?.market_cap_usd ?? null,
+ });
+ }
+ // Drop spot rows the wallet no longer holds.
+ for (const k of [...positions.keys()]) {
+ if (k.startsWith('spot:') && !seen.has(k)) positions.delete(k);
+ }
+ scheduleRender();
+ } catch { /* transient RPC — keep last good book */ }
+ }
+
+ // ── stream ───────────────────────────────────────────────────────────────────
+ function startStream() {
+ sse = createSseClient({
+ url: `/api/sniper/stream?network=${store.getNetwork()}`,
+ onState: (s) => bus.emit('conn:positions', s),
+ events: {
+ open: () => {},
+ buy: (d) => { if (d?.agent_id === agentId) { ingestSniper(d, 'open'); flash(d.mint, d.pnl_pct); scheduleRender(); } },
+ sell: (d) => { if (d?.agent_id === agentId) { ingestSniper(d, 'closed'); scheduleRender(); refreshHoldings(); } },
+ update: (d) => { if (d?.agent_id === agentId) { ingestSniper(d, 'open'); flash(d.mint, d.pnl_pct); scheduleRender(); } },
+ ping: () => {},
+ close: () => {},
+ error: () => {},
+ },
+ });
+ sse.start();
+ }
+
+ let flashMint = null, flashDir = null;
+ function flash(mint, pct) {
+ flashMint = mint;
+ flashDir = (pct ?? 0) >= 0 ? 'pos' : 'neg';
+ }
+
+ // ── render ─────────────────────────────────────────────────────────────────
+ function scheduleRender() {
+ if (rafToken) return;
+ rafToken = requestAnimationFrame(() => { rafToken = 0; render(); });
+ }
+
+ function openList() {
+ return [...positions.values()].filter((p) => p.status === 'open')
+ .sort((a, b) => (b.current_sol ?? 0) - (a.current_sol ?? 0));
+ }
+
+ function tweenSummaryTo(value) {
+ const el = summary.querySelector('[data-host="unreal"]');
+ if (!el) return;
+ summaryTween.from = summaryTween.to;
+ summaryTween.to = value;
+ summaryTween.t0 = performance.now();
+ if (summaryTween.raf) cancelAnimationFrame(summaryTween.raf);
+ const step = (now) => {
+ const k = Math.min(1, (now - summaryTween.t0) / 300);
+ const v = summaryTween.from + (summaryTween.to - summaryTween.from) * (k * (2 - k));
+ el.textContent = formatSolDelta(v);
+ el.className = `mc-num`;
+ el.style.color = v > 0 ? 'var(--success,#4ade80)' : v < 0 ? 'var(--danger,#f87171)' : 'var(--ink-bright,#fff)';
+ if (k < 1) summaryTween.raf = requestAnimationFrame(step);
+ };
+ summaryTween.raf = requestAnimationFrame(step);
+ }
+
+ function render() {
+ const open = openList();
+ const selected = store.getSelected();
+ countEl.textContent = open.length ? `${open.length} open` : '';
+
+ // summary
+ const unreal = open.reduce((s, p) => s + (p.pnl_sol ?? 0), 0);
+ const exposure = open.reduce((s, p) => s + (p.current_sol ?? 0), 0);
+ const realized = closed.reduce((s, p) => s + (p.pnl_sol ?? 0), 0);
+ summary.innerHTML = `
+ <div><span>Open</span><b class="mc-num">${open.length}</b></div>
+ <div><span>Exposure</span><b class="mc-num">${formatSol(exposure)} ◎</b></div>
+ <div><span>Unrealized</span><b class="mc-num" data-host="unreal">${formatSolDelta(unreal)}</b></div>
+ <div><span>Realized</span><b class="mc-num" style="color:${realized > 0 ? 'var(--success,#4ade80)' : realized < 0 ? 'var(--danger,#f87171)' : 'inherit'}">${formatSolDelta(realized)}</b></div>
+ `;
+ tweenSummaryTo(unreal);
+
+ if (!store.getAgent()) {
+ body.innerHTML = stateHtml('◎', 'No agent selected', 'Pick a trading agent in the top bar to see its live positions.');
+ return;
+ }
+ if (!open.length && !closed.length) {
+ body.innerHTML = stateHtml('▦', 'No open positions', 'Buy a coin from the feed to open your first position — its live PnL streams here.');
+ return;
+ }
+
+ const openHtml = open.map((p) => positionRow(p, selected)).join('');
+ const closedHtml = closed.length
+ ? `<div class="mc-section-h" style="padding:10px 12px 4px">Recently closed</div>${closed.map((p) => closedRow(p)).join('')}`
+ : '';
+ body.innerHTML = `<div class="mc-poss">${openHtml}${closedHtml}</div>`;
+
+ // wire row interactions
+ body.querySelectorAll('[data-pos-mint]').forEach((el) => {
+ el.addEventListener('click', (e) => {
+ if (e.target.closest('[data-exit]')) return;
+ store.select(el.dataset.posMint);
+ });
+ });
+ body.querySelectorAll('[data-exit]').forEach((btn) => {
+ btn.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ const mint = btn.dataset.exit;
+ const raw = btn.dataset.raw || null;
+ btn.disabled = true;
+ btn.textContent = 'Selling…';
+ await sell({ store, bus, mint, tokenAmountRaw: raw });
+ // success/failure handled by toast + trade:done → holdings refresh
+ });
+ });
+
+ // apply a one-shot flash to the just-updated row
+ if (flashMint) {
+ const el = body.querySelector(`[data-pos-mint="${cssEscape(flashMint)}"]`);
+ if (el) { el.classList.remove('mc-flash-pos', 'mc-flash-neg'); void el.offsetWidth; el.classList.add(flashDir === 'pos' ? 'mc-flash-pos' : 'mc-flash-neg'); }
+ flashMint = null;
+ }
+ }
+
+ function positionRow(p, selected) {
+ const cls = signClass(p.pnl_pct ?? 0);
+ const isSel = p.mint === selected ? ' style="box-shadow:inset 2px 0 0 var(--accent,#7dd3fc)"' : '';
+ const pnl = p.source === 'spot'
+ ? `<span class="mc-pos-pnl" style="color:var(--ink-dim,#888)">${formatCompact(p.ui_amount)}</span>`
+ : `<span class="mc-pos-pnl mc-num">${formatPct(p.pnl_pct)}<br><small style="font-weight:400;opacity:.8">${formatSolDelta(p.pnl_sol)} ◎</small></span>`;
+ const sub = p.source === 'spot'
+ ? `<span class="mc-pos-sub">Spot · ${formatCompact(p.ui_amount)} tokens</span>`
+ : `<span class="mc-pos-sub">Entry ${formatSol(p.entry_sol)} → ${formatSol(p.current_sol)} ◎</span>`;
+ return `
+ <div class="mc-pos ${cls}" data-pos-mint="${escapeHtml(p.mint)}"${isSel} tabindex="0" role="button" aria-label="${escapeHtml(p.symbol)} position">
+ <span class="mc-pos-sym">${escapeHtml(p.symbol)}<span class="mc-pos-name">${escapeHtml(p.name)}</span></span>
+ ${pnl}
+ ${sub}
+ <span class="mc-pos-actions">
+ <button class="mc-chipbtn" data-exit="${escapeHtml(p.mint)}"${p.amount_raw ? ` data-raw="${escapeHtml(p.amount_raw)}"` : ''} title="Sell full balance">Exit</button>
+ </span>
+ </div>`;
+ }
+
+ function closedRow(p) {
+ const cls = signClass(p.pnl_pct ?? 0);
+ return `
+ <div class="mc-pos mc-pos--closed ${cls}" data-pos-mint="${escapeHtml(p.mint)}" tabindex="0" role="button" aria-label="${escapeHtml(p.symbol)} closed">
+ <span class="mc-pos-sym">${escapeHtml(p.symbol)}<span class="mc-pos-name">${escapeHtml(p.exit_reason || 'closed')}</span></span>
+ <span class="mc-pos-pnl mc-num">${formatPct(p.pnl_pct)}<br><small style="font-weight:400;opacity:.8">${formatSolDelta(p.pnl_sol)} ◎</small></span>
+ <span class="mc-pos-sub">${p.at ? timeAgo(Math.floor(new Date(p.at).getTime() / 1000)) : ''}</span>
+ </div>`;
+ }
+
+ function stateHtml(ico, title, msg) {
+ return `<div class="mc-empty"><div class="mc-empty-ico" aria-hidden="true">${ico}</div><h3>${title}</h3><p>${msg}</p></div>`;
+ }
+ function cssEscape(s) { return (window.CSS && CSS.escape) ? CSS.escape(s) : String(s).replace(/"/g, '\\"'); }
+
+ // ── lifecycle ────────────────────────────────────────────────────────────────
+ function reset() {
+ positions.clear();
+ closed.length = 0;
+ agentId = store.getAgent()?.id || null;
+ if (sse) { sse.stop(); sse = null; }
+ startStream();
+ loadBacklog();
+ refreshHoldings();
+ scheduleRender();
+ }
+
+ const unsubs = [
+ bus.on('agent', () => reset()),
+ bus.on('network', () => reset()),
+ bus.on('select', () => scheduleRender()),
+ bus.on('trade:done', () => { refreshHoldings(); }),
+ ];
+
+ startStream();
+ loadBacklog();
+ refreshHoldings();
+ holdingsTimer = setInterval(refreshHoldings, HOLDINGS_REFRESH_MS);
+ render();
+
+ return {
+ destroy() {
+ if (sse) sse.stop();
+ if (holdingsTimer) clearInterval(holdingsTimer);
+ if (rafToken) cancelAnimationFrame(rafToken);
+ if (summaryTween.raf) cancelAnimationFrame(summaryTween.raf);
+ unsubs.forEach((u) => u());
+ },
+ };
+}
diff --git a/src/mission-control/store.js b/src/mission-control/store.js
new file mode 100644
index 000000000..cfd75f2ce
--- /dev/null
+++ b/src/mission-control/store.js
@@ -0,0 +1,247 @@
+/**
+ * Mission Control — central store.
+ *
+ * Owns the cockpit's shared, cross-pane state: the live feed ring buffer, the
+ * active filter set, the current selection, buy-size presets, the trading agent
+ * + network, and named saved views (persisted per signed-in user). Panes read
+ * from here and mutate through the typed mutators, which emit on the shared bus
+ * so every pane stays in sync without reaching into one another.
+ */
+
+const FEED_CAP = 300; // hard cap on retained feed rows — bounds memory on a fast stream
+const VIEWS_KEY = 'mc:views:v1';
+const PRESETS_KEY = 'mc:presets:v1';
+const EXPRESS_KEY = 'mc:express:v1';
+
+export const DEFAULT_FILTERS = Object.freeze({
+ source: 'live', // 'live' | 'signals' | 'radar'
+ query: '', // free-text on name/symbol/mint
+ minIntel: 0, // 0..100 quality/intel score floor
+ verdict: 'any', // 'any' | 'allow' | 'warn' — firewall verdict floor (block always hidden when set)
+ smartOnly: false, // only rows with ≥1 smart-money buyer
+ socialsOnly: false, // only rows with at least one social link
+ mcBand: 'any', // 'any' | 'nano' | 'micro' | 'small' | 'mid' — market-cap band
+});
+
+export const SIZE_PRESETS_DEFAULT = [0.1, 0.25, 0.5, 1];
+
+const MC_BANDS = {
+ nano: [0, 10_000],
+ micro: [10_000, 50_000],
+ small: [50_000, 250_000],
+ mid: [250_000, Infinity],
+};
+
+function readLocal(key, fallback) {
+ try {
+ const raw = localStorage.getItem(key);
+ return raw ? JSON.parse(raw) : fallback;
+ } catch {
+ return fallback;
+ }
+}
+function writeLocal(key, value) {
+ try {
+ localStorage.setItem(key, JSON.stringify(value));
+ } catch {
+ /* storage unavailable (private mode / quota) — non-fatal */
+ }
+}
+
+export function createStore({ bus, userId = 'anon' }) {
+ const order = []; // mints, newest first
+ const rows = new Map(); // mint -> row
+ let filters = { ...DEFAULT_FILTERS };
+ let selectedMint = null;
+ let agent = null; // active trading agent record
+ let network = 'mainnet';
+ let sizePresets = sanitizePresets(readLocal(PRESETS_KEY, SIZE_PRESETS_DEFAULT));
+ let activeSize = sizePresets[1] ?? sizePresets[0] ?? 0.1;
+ let expressMint = readLocal(EXPRESS_KEY, {}); // { [agentId]: true } — confirm-on-first-use satisfied
+
+ const viewsNs = `${VIEWS_KEY}:${userId}`;
+
+ function sanitizePresets(arr) {
+ const nums = (Array.isArray(arr) ? arr : SIZE_PRESETS_DEFAULT)
+ .map(Number)
+ .filter((n) => Number.isFinite(n) && n > 0)
+ .slice(0, 6);
+ return nums.length ? nums : [...SIZE_PRESETS_DEFAULT];
+ }
+
+ function bandOf(mcUsd) {
+ if (mcUsd == null) return null;
+ for (const [name, [lo, hi]] of Object.entries(MC_BANDS)) {
+ if (mcUsd >= lo && mcUsd < hi) return name;
+ }
+ return null;
+ }
+
+ function matchesFilters(row) {
+ const f = filters;
+ if (f.query) {
+ const q = f.query.toLowerCase();
+ const hay = `${row.name || ''} ${row.symbol || ''} ${row.mint || ''}`.toLowerCase();
+ if (!hay.includes(q)) return false;
+ }
+ if (f.minIntel > 0) {
+ const score = row.intel?.quality_score;
+ if (score == null || score < f.minIntel) return false;
+ }
+ if (f.verdict !== 'any') {
+ const v = row.safety?.verdict;
+ if (!v) return false;
+ if (v === 'block') return false;
+ if (f.verdict === 'allow' && v !== 'allow') return false;
+ // 'warn' admits allow + warn (block already excluded)
+ }
+ if (f.smartOnly && !(row.smart?.count > 0)) return false;
+ if (f.socialsOnly && !(row.twitter || row.telegram || row.website)) return false;
+ if (f.mcBand !== 'any' && bandOf(row.market_cap_usd) !== f.mcBand) return false;
+ return true;
+ }
+
+ return {
+ // ── feed ──────────────────────────────────────────────────────────────
+ /** Insert or merge a feed row (keyed by mint). Returns the stored row. */
+ upsertRow(partial) {
+ const mint = partial.mint;
+ if (!mint) return null;
+ const existing = rows.get(mint);
+ if (existing) {
+ Object.assign(existing, partial);
+ bus.emit('feed:update', existing);
+ return existing;
+ }
+ const row = { firstSeen: Date.now(), ...partial };
+ rows.set(mint, row);
+ order.unshift(mint);
+ // Evict the oldest beyond the cap (but never the selected row).
+ while (order.length > FEED_CAP) {
+ const drop = order[order.length - 1];
+ if (drop === selectedMint) {
+ // move selection-protected row up one and drop the next-oldest
+ order.splice(order.length - 1, 1);
+ order.splice(order.length - 1, 0, drop);
+ break;
+ }
+ order.pop();
+ rows.delete(drop);
+ }
+ bus.emit('feed:add', row);
+ return row;
+ },
+ /** Patch enrichment onto a row without reordering. */
+ enrichRow(mint, patch) {
+ const row = rows.get(mint);
+ if (!row) return null;
+ Object.assign(row, patch);
+ bus.emit('feed:update', row);
+ return row;
+ },
+ getRow: (mint) => rows.get(mint) || null,
+ /** All rows passing the active filters, newest first. */
+ visibleRows() {
+ const out = [];
+ for (const mint of order) {
+ const row = rows.get(mint);
+ if (row && matchesFilters(row)) out.push(row);
+ }
+ return out;
+ },
+ allRowsCount: () => order.length,
+ resetFeed() {
+ order.length = 0;
+ rows.clear();
+ bus.emit('feed:reset');
+ },
+ matchesFilters,
+ bandOf,
+
+ // ── filters ───────────────────────────────────────────────────────────
+ getFilters: () => ({ ...filters }),
+ setFilters(patch) {
+ filters = { ...filters, ...patch };
+ bus.emit('filters', { ...filters });
+ },
+ resetFilters() {
+ filters = { ...DEFAULT_FILTERS };
+ bus.emit('filters', { ...filters });
+ },
+
+ // ── selection ─────────────────────────────────────────────────────────
+ getSelected: () => selectedMint,
+ select(mint) {
+ if (mint === selectedMint) return;
+ selectedMint = mint;
+ bus.emit('select', mint);
+ },
+
+ // ── agent / network ───────────────────────────────────────────────────
+ getAgent: () => agent,
+ setAgent(next) {
+ agent = next;
+ bus.emit('agent', agent);
+ },
+ getNetwork: () => network,
+ setNetwork(net) {
+ network = net === 'devnet' ? 'devnet' : 'mainnet';
+ bus.emit('network', network);
+ },
+
+ // ── size presets ──────────────────────────────────────────────────────
+ getPresets: () => [...sizePresets],
+ getActiveSize: () => activeSize,
+ setActiveSize(sol) {
+ const n = Number(sol);
+ if (Number.isFinite(n) && n > 0) {
+ activeSize = n;
+ bus.emit('size', activeSize);
+ }
+ },
+ setPresets(arr) {
+ sizePresets = sanitizePresets(arr);
+ writeLocal(PRESETS_KEY, sizePresets);
+ if (!sizePresets.includes(activeSize)) activeSize = sizePresets[0];
+ bus.emit('presets', [...sizePresets]);
+ },
+
+ // ── express (confirm-on-first-use) ──────────────────────────────────────
+ isExpress: (agentId) => !!expressMint[agentId],
+ setExpress(agentId) {
+ expressMint = { ...expressMint, [agentId]: true };
+ writeLocal(EXPRESS_KEY, expressMint);
+ bus.emit('express', { agentId, on: true });
+ },
+ toggleExpress(agentId) {
+ const on = !expressMint[agentId];
+ expressMint = { ...expressMint, [agentId]: on };
+ writeLocal(EXPRESS_KEY, expressMint);
+ bus.emit('express', { agentId, on });
+ return on;
+ },
+
+ // ── saved views (named filter sets, per user) ───────────────────────────
+ listViews: () => readLocal(viewsNs, []),
+ saveView(name) {
+ const views = readLocal(viewsNs, []).filter((v) => v.name !== name);
+ views.unshift({ name, filters: { ...filters }, savedAt: Date.now() });
+ writeLocal(viewsNs, views.slice(0, 24));
+ bus.emit('views', views);
+ return views;
+ },
+ applyView(name) {
+ const view = readLocal(viewsNs, []).find((v) => v.name === name);
+ if (!view) return false;
+ filters = { ...DEFAULT_FILTERS, ...view.filters };
+ bus.emit('filters', { ...filters });
+ return true;
+ },
+ deleteView(name) {
+ const views = readLocal(viewsNs, []).filter((v) => v.name !== name);
+ writeLocal(viewsNs, views);
+ bus.emit('views', views);
+ return views;
+ },
+ };
+}
diff --git a/src/mission-control/styles.js b/src/mission-control/styles.js
new file mode 100644
index 000000000..c26ac47a2
--- /dev/null
+++ b/src/mission-control/styles.js
@@ -0,0 +1,222 @@
+/**
+ * Mission Control — styles. One injected stylesheet, built entirely on the
+ * platform design tokens (public/tokens.css) with safe fallbacks so the cockpit
+ * themes correctly in dark and light. Bloomberg-grade density, Linear-grade
+ * polish: tabular numerics, hairline strokes, intentional motion, full
+ * reduced-motion + focus-ring support.
+ */
+
+const STYLE_ID = 'mission-control-style';
+
+const CSS = `
+.mc-root {
+ --mc-gap: var(--space-3, 12px);
+ --mc-pos: var(--success, #4ade80);
+ --mc-neg: var(--danger, #f87171);
+ --mc-radius: var(--radius-md, 10px);
+ position: fixed; inset: 0; display: flex; flex-direction: column;
+ background: var(--bg-0, #0a0a0b); color: var(--ink, #e8e8e8);
+ font-family: var(--font-sans, system-ui, sans-serif);
+ font-size: var(--text-md, .8125rem);
+ -webkit-font-smoothing: antialiased; overflow: hidden;
+}
+.mc-root *, .mc-root *::before, .mc-root *::after { box-sizing: border-box; }
+.mc-num { font-variant-numeric: tabular-nums; font-feature-settings: 'tnum' 1; }
+.mc-mono { font-family: var(--font-mono, ui-monospace, monospace); }
+
+/* ── top bar ─────────────────────────────────────────────────────────────── */
+.mc-topbar { display: flex; align-items: center; gap: var(--space-3,12px); padding: 8px 14px; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.08)); background: var(--surface-1, rgba(255,255,255,.02)); flex: none; min-height: 50px; }
+.mc-brand { display: flex; align-items: center; gap: 9px; font-weight: 700; color: var(--ink-bright, #fff); letter-spacing: .02em; text-decoration: none; white-space: nowrap; }
+.mc-brand-logo { width: 22px; height: 22px; border-radius: 6px; }
+.mc-brand b { font-family: var(--font-display, system-ui); font-size: var(--text-md,.8125rem); }
+.mc-brand span { color: var(--ink-dim,#888); font-weight: 600; font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .08em; padding: 2px 6px; border: 1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-pill,999px); }
+.mc-topbar-spacer { flex: 1 1 auto; }
+.mc-conn-group { display: flex; align-items: center; gap: 10px; }
+.mc-conn { display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); white-space: nowrap; }
+.mc-conn-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ink-faint,#555); flex: none; transition: background var(--duration-fast,140ms); }
+.mc-conn[data-state="live"] .mc-conn-dot { background: var(--success,#4ade80); box-shadow: 0 0 6px color-mix(in srgb, var(--success,#4ade80) 70%, transparent); animation: mc-breathe 2.4s ease-in-out infinite; }
+.mc-conn[data-state="reconnecting"] .mc-conn-dot { background: var(--warn,#fbbf24); animation: mc-pulse 1s ease-in-out infinite; }
+.mc-conn[data-state="down"] .mc-conn-dot { background: var(--danger,#f87171); }
+.mc-ctrl { display: inline-flex; align-items: center; gap: 6px; }
+.mc-select, .mc-iconbtn { font: inherit; font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-sm,6px); padding: 5px 9px; cursor: pointer; }
+.mc-select:hover, .mc-iconbtn:hover { border-color: var(--stroke-strong, rgba(255,255,255,.18)); }
+.mc-select:focus-visible, .mc-iconbtn:focus-visible, .mc-row:focus-visible, .mc-tab:focus-visible, .mc-chipbtn:focus-visible, .mc-size:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#7dd3fc); outline-offset: 2px; }
+.mc-iconbtn { display: inline-grid; place-items: center; min-width: 30px; height: 30px; padding: 0 8px; }
+.mc-balance { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); white-space: nowrap; }
+.mc-balance b { color: var(--ink-bright,#fff); font-variant-numeric: tabular-nums; }
+
+/* ── grid ────────────────────────────────────────────────────────────────── */
+.mc-main { flex: 1 1 auto; min-height: 0; display: grid; grid-template-columns: minmax(300px, 1.05fr) minmax(360px, 1.5fr) minmax(280px, 1fr); gap: 1px; background: var(--stroke, rgba(255,255,255,.07)); }
+.mc-pane { background: var(--bg-0, #0a0a0b); min-height: 0; min-width: 0; display: flex; flex-direction: column; overflow: hidden; }
+.mc-pane-head { display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-bottom: 1px solid var(--stroke,rgba(255,255,255,.07)); flex: none; }
+.mc-pane-title { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .07em; color: var(--ink-dim,#888); font-weight: 700; }
+.mc-pane-count { font-size: var(--text-2xs,.6875rem); color: var(--ink-faint,#666); font-variant-numeric: tabular-nums; }
+.mc-pane-head-spacer { flex: 1 1 auto; }
+.mc-pane-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; overflow-x: hidden; scrollbar-width: thin; scrollbar-color: var(--stroke-strong,rgba(255,255,255,.18)) transparent; position: relative; }
+
+/* ── source / filter strip ───────────────────────────────────────────────── */
+.mc-tabs { display: flex; gap: 2px; }
+.mc-tab { appearance: none; font: inherit; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); background: transparent; border: 1px solid transparent; border-radius: var(--radius-sm,6px); padding: 3px 9px; cursor: pointer; transition: color var(--duration-fast,140ms), background var(--duration-fast,140ms); }
+.mc-tab:hover { color: var(--ink,#e8e8e8); background: var(--surface-1,rgba(255,255,255,.04)); }
+.mc-tab[aria-selected="true"] { color: var(--ink-bright,#fff); background: var(--surface-2,rgba(255,255,255,.06)); border-color: var(--stroke,rgba(255,255,255,.1)); }
+.mc-filterbar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 7px 12px; border-bottom: 1px solid var(--stroke,rgba(255,255,255,.07)); flex: none; }
+.mc-search { flex: 1 1 120px; min-width: 90px; font: inherit; font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); background: var(--surface-1,rgba(255,255,255,.04)); border: 1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-sm,6px); padding: 5px 8px; }
+.mc-search:focus-visible { outline: none; border-color: var(--accent,#7dd3fc); }
+.mc-chipbtn { appearance: none; font: inherit; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); background: var(--surface-1,rgba(255,255,255,.04)); border: 1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-pill,999px); padding: 3px 9px; cursor: pointer; white-space: nowrap; display: inline-flex; align-items: center; gap: 5px; transition: all var(--duration-fast,140ms); }
+.mc-chipbtn:hover { color: var(--ink,#e8e8e8); border-color: var(--stroke-strong,rgba(255,255,255,.18)); }
+.mc-chipbtn[aria-pressed="true"], .mc-chipbtn.is-active { color: var(--ink-bright,#fff); background: color-mix(in srgb, var(--accent,#7dd3fc) 18%, transparent); border-color: color-mix(in srgb, var(--accent,#7dd3fc) 50%, transparent); }
+.mc-views { margin-left: auto; display: inline-flex; gap: 6px; align-items: center; }
+
+/* ── feed rows (virtualized) ─────────────────────────────────────────────── */
+.mc-vlist { position: relative; width: 100%; }
+.mc-vlist-spacer { position: absolute; inset: 0; pointer-events: none; }
+.mc-row { position: absolute; left: 0; right: 0; display: grid; grid-template-columns: 1fr auto; gap: 2px 10px; align-items: center; padding: 7px 12px; border-bottom: 1px solid var(--stroke,rgba(255,255,255,.05)); cursor: pointer; text-align: left; appearance: none; background: transparent; font: inherit; color: inherit; width: 100%; transition: background var(--duration-fast,140ms); content-visibility: auto; }
+.mc-row:hover { background: var(--surface-1,rgba(255,255,255,.035)); }
+.mc-row[aria-selected="true"] { background: color-mix(in srgb, var(--accent,#7dd3fc) 12%, transparent); box-shadow: inset 2px 0 0 var(--accent,#7dd3fc); }
+.mc-row-top { display: flex; align-items: center; gap: 7px; min-width: 0; grid-column: 1; }
+.mc-row-sym { font-weight: 700; color: var(--ink-bright,#fff); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 9ch; }
+.mc-row-name { color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
+.mc-row-age { grid-column: 2; grid-row: 1; color: var(--ink-faint,#666); font-size: var(--text-2xs,.6875rem); font-variant-numeric: tabular-nums; white-space: nowrap; justify-self: end; }
+.mc-row-meta { grid-column: 1 / -1; grid-row: 2; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.mc-row-mc { color: var(--ink,#cfcfcf); font-size: var(--text-2xs,.6875rem); font-variant-numeric: tabular-nums; }
+.mc-row-mc b { color: var(--ink-bright,#fff); }
+.mc-enter { animation: mc-rowin var(--duration-base,260ms) var(--ease-out, cubic-bezier(.22,1,.36,1)); }
+
+/* chips */
+.mc-chip { display: inline-flex; align-items: center; gap: 4px; font-size: var(--text-2xs,.6875rem); font-weight: 700; padding: 1px 6px; border-radius: var(--radius-sm,5px); line-height: 1.5; white-space: nowrap; border: 1px solid transparent; font-variant-numeric: tabular-nums; }
+.mc-chip--allow { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 13%, transparent); border-color: color-mix(in srgb, var(--success,#4ade80) 32%, transparent); }
+.mc-chip--warn { color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 13%, transparent); border-color: color-mix(in srgb, var(--warn,#fbbf24) 32%, transparent); }
+.mc-chip--block { color: var(--danger,#f87171); background: color-mix(in srgb, var(--danger,#f87171) 13%, transparent); border-color: color-mix(in srgb, var(--danger,#f87171) 36%, transparent); }
+.mc-chip--unknown { color: var(--ink-faint,#666); background: var(--surface-1,rgba(255,255,255,.04)); border-color: var(--stroke,rgba(255,255,255,.08)); }
+.mc-chip--intel { color: var(--ink,#e8e8e8); background: var(--surface-2,rgba(255,255,255,.06)); border-color: var(--stroke,rgba(255,255,255,.1)); }
+.mc-chip--smart { color: var(--accent,#7dd3fc); background: color-mix(in srgb, var(--accent,#7dd3fc) 12%, transparent); border-color: color-mix(in srgb, var(--accent,#7dd3fc) 30%, transparent); }
+.mc-chip-skel { width: 38px; height: 15px; border-radius: 5px; background: var(--surface-2,rgba(255,255,255,.05)); animation: mc-skel 1.3s ease-in-out infinite; }
+
+/* ── positions ───────────────────────────────────────────────────────────── */
+.mc-poss { display: flex; flex-direction: column; }
+.mc-pos { display: grid; grid-template-columns: 1fr auto; gap: 2px 10px; padding: 8px 12px; border-bottom: 1px solid var(--stroke,rgba(255,255,255,.05)); align-items: center; }
+.mc-pos-sym { font-weight: 700; color: var(--ink-bright,#fff); display: flex; align-items: center; gap: 6px; min-width: 0; }
+.mc-pos-sym .mc-pos-name { color: var(--ink-dim,#888); font-weight: 400; font-size: var(--text-sm,.764rem); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.mc-pos-pnl { justify-self: end; text-align: right; font-variant-numeric: tabular-nums; font-weight: 700; }
+.mc-pos-sub { grid-column: 1; color: var(--ink-faint,#666); font-size: var(--text-2xs,.6875rem); font-variant-numeric: tabular-nums; }
+.mc-pos-actions { grid-column: 2; justify-self: end; display: flex; gap: 6px; }
+.mc-pos.pos .mc-pos-pnl { color: var(--mc-pos); } .mc-pos.neg .mc-pos-pnl { color: var(--mc-neg); } .mc-pos.flat .mc-pos-pnl { color: var(--ink-dim,#888); }
+.mc-pos--closed { opacity: .62; }
+.mc-flash-pos { animation: mc-flashpos .8s ease-out; } .mc-flash-neg { animation: mc-flashneg .8s ease-out; }
+.mc-pos-summary { display: flex; gap: 14px; padding: 9px 12px; border-bottom: 1px solid var(--stroke,rgba(255,255,255,.07)); flex: none; flex-wrap: wrap; }
+.mc-pos-summary div { display: flex; flex-direction: column; gap: 1px; }
+.mc-pos-summary span { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); text-transform: uppercase; letter-spacing: .05em; }
+.mc-pos-summary b { font-size: var(--text-md,.8125rem); font-variant-numeric: tabular-nums; color: var(--ink-bright,#fff); }
+
+/* ── focus / detail ──────────────────────────────────────────────────────── */
+.mc-focus { padding: 14px; display: flex; flex-direction: column; gap: 14px; }
+.mc-focus-head { display: flex; align-items: flex-start; gap: 12px; }
+.mc-focus-img { width: 48px; height: 48px; border-radius: var(--radius-md,10px); object-fit: cover; background: var(--surface-2,rgba(255,255,255,.05)); border: 1px solid var(--stroke,rgba(255,255,255,.08)); flex: none; }
+.mc-focus-id { min-width: 0; flex: 1 1 auto; }
+.mc-focus-id h2 { margin: 0; font-size: var(--text-lg,1.236rem); color: var(--ink-bright,#fff); font-family: var(--font-display,system-ui); display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.mc-focus-id .mc-focus-name { color: var(--ink-dim,#888); font-size: var(--text-md,.8125rem); }
+.mc-focus-addr { display: inline-flex; align-items: center; gap: 6px; margin-top: 5px; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }
+.mc-focus-addr a { color: inherit; text-decoration: none; border-bottom: 1px dotted currentColor; }
+.mc-focus-socials { display: inline-flex; gap: 8px; margin-top: 6px; }
+.mc-focus-socials a { color: var(--ink-dim,#888); text-decoration: none; font-size: var(--text-sm,.764rem); border: 1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-sm,6px); padding: 2px 8px; }
+.mc-focus-socials a:hover { color: var(--ink-bright,#fff); border-color: var(--stroke-strong,rgba(255,255,255,.2)); }
+.mc-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(92px, 1fr)); gap: 1px; background: var(--stroke,rgba(255,255,255,.07)); border: 1px solid var(--stroke,rgba(255,255,255,.07)); border-radius: var(--mc-radius); overflow: hidden; }
+.mc-stat { background: var(--surface-1,rgba(255,255,255,.02)); padding: 9px 11px; display: flex; flex-direction: column; gap: 2px; }
+.mc-stat span { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); text-transform: uppercase; letter-spacing: .05em; }
+.mc-stat b { font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); font-variant-numeric: tabular-nums; }
+.mc-section-h { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .07em; color: var(--ink-dim,#888); font-weight: 700; margin: 0 0 8px; }
+.mc-spark { width: 100%; height: 64px; display: block; }
+.mc-spark-wrap { border: 1px solid var(--stroke,rgba(255,255,255,.07)); border-radius: var(--mc-radius); padding: 10px 12px; background: var(--surface-1,rgba(255,255,255,.02)); }
+.mc-smart-bar { height: 8px; border-radius: 999px; background: var(--surface-2,rgba(255,255,255,.06)); overflow: hidden; }
+.mc-smart-bar > i { display: block; height: 100%; background: linear-gradient(90deg, var(--accent,#7dd3fc), var(--success,#4ade80)); border-radius: 999px; transition: width var(--duration-base,260ms) var(--ease-out,ease); }
+.mc-smart-wallets { list-style: none; margin: 8px 0 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
+.mc-smart-wallets li { display: flex; align-items: center; gap: 8px; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }
+.mc-smart-wallets b { color: var(--ink,#e8e8e8); font-variant-numeric: tabular-nums; }
+
+/* ── trade panel ─────────────────────────────────────────────────────────── */
+.mc-trade { border: 1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-lg,14px); background: var(--surface-1,rgba(255,255,255,.025)); padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
+.mc-sizes { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
+.mc-size { appearance: none; font: inherit; font-size: var(--text-sm,.764rem); font-variant-numeric: tabular-nums; color: var(--ink,#e8e8e8); background: var(--surface-2,rgba(255,255,255,.05)); border: 1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-sm,6px); padding: 5px 11px; cursor: pointer; min-width: 30px; }
+.mc-size[aria-pressed="true"] { color: #08121b; background: var(--accent,#7dd3fc); border-color: var(--accent,#7dd3fc); font-weight: 700; }
+.mc-size-kbd { color: var(--ink-faint,#666); font-size: .85em; margin-left: 3px; }
+.mc-trade-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
+.mc-btn { appearance: none; font: inherit; font-size: var(--text-md,.8125rem); font-weight: 700; border-radius: var(--radius-md,10px); padding: 10px 14px; cursor: pointer; border: 1px solid transparent; transition: transform var(--duration-instant,80ms), background var(--duration-fast,140ms), opacity var(--duration-fast,140ms); display: inline-flex; align-items: center; justify-content: center; gap: 7px; }
+.mc-btn:active:not(:disabled) { transform: translateY(1px); }
+.mc-btn:disabled { opacity: .4; cursor: not-allowed; }
+.mc-btn--buy { background: var(--success,#4ade80); color: #04140a; }
+.mc-btn--buy:hover:not(:disabled) { background: color-mix(in srgb, var(--success,#4ade80) 88%, #fff); }
+.mc-btn--sell { background: color-mix(in srgb, var(--danger,#f87171) 18%, transparent); color: var(--danger,#f87171); border-color: color-mix(in srgb, var(--danger,#f87171) 45%, transparent); }
+.mc-btn--sell:hover:not(:disabled) { background: color-mix(in srgb, var(--danger,#f87171) 28%, transparent); }
+.mc-btn kbd { font-family: var(--font-mono,ui-monospace,monospace); font-size: .8em; opacity: .7; border: 1px solid currentColor; border-radius: 4px; padding: 0 4px; }
+.mc-trade-note { font-size: var(--text-sm,.764rem); line-height: 1.45; min-height: 1.2em; }
+.mc-trade-note.is-err { color: var(--danger,#f87171); } .mc-trade-note.is-warn { color: var(--warn,#fbbf24); } .mc-trade-note.is-ok { color: var(--success,#4ade80); } .mc-trade-note.is-dim { color: var(--ink-dim,#888); }
+
+/* ── empty / loading / error states ──────────────────────────────────────── */
+.mc-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; padding: 40px 20px; text-align: center; color: var(--ink-dim,#888); height: 100%; }
+.mc-empty-ico { font-size: 26px; opacity: .5; }
+.mc-empty h3 { margin: 0; font-size: var(--text-md,.8125rem); color: var(--ink,#e8e8e8); font-weight: 600; }
+.mc-empty p { margin: 0; font-size: var(--text-sm,.764rem); max-width: 34ch; line-height: 1.5; }
+.mc-empty button { margin-top: 4px; }
+.mc-skelrow { height: 46px; border-bottom: 1px solid var(--stroke,rgba(255,255,255,.05)); padding: 8px 12px; display: flex; flex-direction: column; gap: 7px; }
+.mc-skelrow i { display: block; height: 11px; border-radius: 5px; background: var(--surface-2,rgba(255,255,255,.05)); animation: mc-skel 1.3s ease-in-out infinite; }
+.mc-skelrow i:first-child { width: 45%; } .mc-skelrow i:last-child { width: 70%; }
+
+/* ── shortcut overlay ────────────────────────────────────────────────────── */
+.mc-overlay { position: fixed; inset: 0; background: color-mix(in srgb, var(--bg-0,#0a0a0b) 78%, transparent); backdrop-filter: blur(4px); display: grid; place-items: center; z-index: 1000; animation: mc-fade var(--duration-base,220ms) ease; padding: 20px; }
+.mc-overlay[hidden] { display: none; }
+.mc-overlay-card { background: var(--surface-1,#16161a); border: 1px solid var(--stroke-strong,rgba(255,255,255,.16)); border-radius: var(--radius-lg,14px); box-shadow: var(--shadow-3, 0 20px 60px rgba(0,0,0,.6)); padding: 22px 26px; max-width: 540px; width: 100%; max-height: 86vh; overflow-y: auto; }
+.mc-overlay-card h2 { margin: 0 0 14px; font-size: var(--text-lg,1.236rem); color: var(--ink-bright,#fff); font-family: var(--font-display,system-ui); }
+.mc-keys { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 22px; }
+.mc-keys dl { margin: 0; display: contents; }
+.mc-keyrow { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 4px 0; border-bottom: 1px solid var(--stroke,rgba(255,255,255,.05)); }
+.mc-keyrow span { color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); }
+.mc-keyrow kbd { font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-2xs,.6875rem); background: var(--surface-2,rgba(255,255,255,.07)); border: 1px solid var(--stroke,rgba(255,255,255,.12)); border-bottom-width: 2px; border-radius: 5px; padding: 2px 7px; color: var(--ink-bright,#fff); }
+
+/* ── toast ───────────────────────────────────────────────────────────────── */
+.mc-toast { position: fixed; left: 50%; bottom: 28px; transform: translateX(-50%) translateY(10px); background: var(--surface-1,#16161a); color: var(--ink-bright,#fff); border: 1px solid var(--stroke-strong,rgba(255,255,255,.16)); border-left-width: 3px; border-radius: var(--radius-md,10px); padding: 11px 16px; font-size: var(--text-md,.8125rem); box-shadow: var(--shadow-3,0 12px 40px rgba(0,0,0,.5)); opacity: 0; pointer-events: none; transition: opacity var(--duration-base,220ms), transform var(--duration-base,220ms); z-index: 1100; max-width: min(440px, 90vw); }
+.mc-toast[data-show="true"] { opacity: 1; transform: translateX(-50%) translateY(0); }
+.mc-toast.ok { border-left-color: var(--success,#4ade80); } .mc-toast.err { border-left-color: var(--danger,#f87171); } .mc-toast.warn { border-left-color: var(--warn,#fbbf24); } .mc-toast.info { border-left-color: var(--accent,#7dd3fc); }
+.mc-toast a { color: var(--accent,#7dd3fc); }
+
+/* ── mobile pane switch ──────────────────────────────────────────────────── */
+.mc-mobilebar { display: none; }
+.mc-sr { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
+
+/* ── responsive ──────────────────────────────────────────────────────────── */
+@media (max-width: 1100px) {
+ .mc-main { grid-template-columns: minmax(280px, 1fr) minmax(320px, 1.4fr); grid-template-rows: 1fr; }
+ .mc-pane--positions { grid-column: 1 / -1; display: none; } /* folded into focus column tab on tablet */
+ .mc-main.show-positions .mc-pane--focus { display: none; }
+ .mc-main.show-positions .mc-pane--positions { display: flex; grid-column: 2; }
+}
+@media (max-width: 760px) {
+ .mc-main { grid-template-columns: 1fr; }
+ .mc-pane { display: none; }
+ .mc-pane.is-active { display: flex; }
+ .mc-mobilebar { display: grid; grid-template-columns: repeat(3, 1fr); gap: 2px; flex: none; border-top: 1px solid var(--stroke,rgba(255,255,255,.08)); background: var(--surface-1,rgba(255,255,255,.02)); }
+ .mc-mobilebar button { appearance: none; font: inherit; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); background: transparent; border: none; padding: 11px 6px; cursor: pointer; }
+ .mc-mobilebar button[aria-selected="true"] { color: var(--ink-bright,#fff); box-shadow: inset 0 2px 0 var(--accent,#7dd3fc); }
+ .mc-topbar { flex-wrap: wrap; min-height: auto; padding: 8px 10px; }
+ .mc-conn-group { order: 3; flex-basis: 100%; }
+}
+
+/* ── motion ──────────────────────────────────────────────────────────────── */
+@keyframes mc-rowin { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: none; } }
+@keyframes mc-skel { 0%,100% { opacity: .45; } 50% { opacity: .9; } }
+@keyframes mc-pulse { 0%,100% { opacity: 1; } 50% { opacity: .3; } }
+@keyframes mc-breathe { 0%,100% { opacity: 1; } 50% { opacity: .55; } }
+@keyframes mc-fade { from { opacity: 0; } to { opacity: 1; } }
+@keyframes mc-flashpos { 0% { background: color-mix(in srgb, var(--success,#4ade80) 24%, transparent); } 100% { background: transparent; } }
+@keyframes mc-flashneg { 0% { background: color-mix(in srgb, var(--danger,#f87171) 24%, transparent); } 100% { background: transparent; } }
+@media (prefers-reduced-motion: reduce) {
+ .mc-root *, .mc-enter, .mc-flash-pos, .mc-flash-neg, .mc-conn-dot, .mc-chip-skel, .mc-skelrow i { animation: none !important; transition: none !important; }
+}
+`;
+
+export function injectMissionControlStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = STYLE_ID;
+ tag.textContent = CSS;
+ document.head.appendChild(tag);
+}
diff --git a/src/mission-control/trade.js b/src/mission-control/trade.js
new file mode 100644
index 000000000..ca54b9592
--- /dev/null
+++ b/src/mission-control/trade.js
@@ -0,0 +1,167 @@
+/**
+ * Mission Control — execution. A thin, fast layer over the REAL guarded trade
+ * path: POST /api/agents/:id/solana/trade (server-signed, firewall + MEV + spend
+ * guard + custody audit enforced server-side). This module NEVER bypasses any of
+ * that — it only sequences the same calls the wallet hub's Trade tab makes, with
+ * confirm-on-first-use then express mode for keyboard-speed trading.
+ */
+
+import {
+ previewAgentTrade,
+ executeAgentTrade,
+ fetchAgentHoldings,
+ TradeError,
+} from '../agent-solana-wallet.js';
+import { confirmModal, toast } from './ui.js';
+import { explorerTxUrl, formatSol, formatCompact } from './format.js';
+
+const DEFAULT_SLIPPAGE_BPS = 300; // 3% — matches the server default
+
+function uuid() {
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
+ return `mc-${Date.now()}-${Math.floor(Math.random() * 1e9)}`;
+}
+
+function friendlyError(e) {
+ if (e instanceof TradeError) {
+ switch (e.code) {
+ case 'firewall_blocked':
+ return 'Firewall blocked this trade — the coin failed a safety check.';
+ case 'insufficient_funds':
+ return 'Not enough SOL in the agent wallet for this trade.';
+ case 'spend_limit_exceeded':
+ case 'daily_budget_exceeded':
+ return 'This trade would exceed the wallet’s spend guard.';
+ case 'slippage_exceeded':
+ return 'Price moved past your slippage — trade not sent.';
+ case 'network_error':
+ return 'Network unreachable — check your connection and retry.';
+ default:
+ return e.message || 'Trade failed.';
+ }
+ }
+ return e?.message || 'Trade failed.';
+}
+
+async function ensureConfirmed(store, { side, mint, sizeDesc }) {
+ const agent = store.getAgent();
+ if (store.isExpress(agent.id)) return true;
+ const ok = await confirmModal({
+ title: side === 'buy' ? 'Confirm buy' : 'Confirm sell',
+ body:
+ `You're about to <b>${side}</b> <b class="mc-mono">${mint.slice(0, 4)}…${mint.slice(-4)}</b>` +
+ ` ${sizeDesc} from <b>${escapeName(agent.name)}</b>'s wallet on <b>${store.getNetwork()}</b>.` +
+ ` Every trade runs through the firewall + MEV engine.<br><br>` +
+ `<span style="color:var(--ink-faint,#666)">After this, trades execute instantly (express mode). Toggle it off anytime with <kbd>x</kbd>.</span>`,
+ confirmLabel: side === 'buy' ? 'Buy' : 'Sell',
+ tone: side,
+ });
+ if (ok) store.setExpress(agent.id);
+ return ok;
+}
+
+function escapeName(s) {
+ return String(s ?? 'agent').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+/** Execute a buy of `solAmount` SOL into `mint`. Returns the result or null. */
+export async function buy({ store, bus, mint, solAmount }) {
+ const agent = store.getAgent();
+ if (!agent?.id) { toast('Select a trading agent first.', { tone: 'err' }); return null; }
+ if (!(solAmount > 0)) { toast('Pick a buy size first.', { tone: 'warn' }); return null; }
+
+ // Fast client-side gate on the cached firewall verdict — the server is the real
+ // gate, this just spares an obviously-blocked round trip and explains why.
+ const row = store.getRow(mint);
+ if (row?.safety?.verdict === 'block') {
+ toast('Firewall has this coin blocked — it likely can’t be sold.', { tone: 'err' });
+ return null;
+ }
+
+ if (!(await ensureConfirmed(store, { side: 'buy', mint, sizeDesc: `for ${formatSol(solAmount)} SOL` }))) return null;
+
+ bus.emit('trade:pending', { mint, side: 'buy' });
+ try {
+ const res = await executeAgentTrade({
+ agentId: agent.id, side: 'buy', mint, solAmount,
+ slippageBps: DEFAULT_SLIPPAGE_BPS, network: store.getNetwork(), idempotencyKey: uuid(),
+ });
+ const out = res?.out;
+ toast(
+ `Bought ${formatCompact(out?.amount)} ${out?.asset === 'TOKEN' ? (row?.symbol || 'tokens') : out?.asset || 'tokens'}`,
+ { tone: 'ok', link: res?.signature ? { href: explorerTxUrl(res.signature, store.getNetwork()), label: 'View ↗' } : null },
+ );
+ bus.emit('trade:done', { mint, side: 'buy', result: res });
+ return res;
+ } catch (e) {
+ toast(friendlyError(e), { tone: 'err' });
+ bus.emit('trade:error', { mint, side: 'buy', error: e });
+ return null;
+ }
+}
+
+/** Resolve the full raw token balance the agent holds for `mint` (for a 100% exit). */
+export async function holdingRawFor(store, mint) {
+ const agent = store.getAgent();
+ if (!agent?.id) return null;
+ try {
+ const data = await fetchAgentHoldings(agent.id, store.getNetwork());
+ const t = (data?.tokens || []).find((x) => x.mint === mint);
+ return t ? { amount_raw: t.amount_raw, ui_amount: t.ui_amount, decimals: t.decimals } : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Sell tokens of `mint`. Pass an explicit `tokenAmountRaw`, or omit it to sell
+ * the full on-chain balance (quick exit). Returns the result or null.
+ */
+export async function sell({ store, bus, mint, tokenAmountRaw, label }) {
+ const agent = store.getAgent();
+ if (!agent?.id) { toast('Select a trading agent first.', { tone: 'err' }); return null; }
+
+ let raw = tokenAmountRaw;
+ let uiHint = label;
+ if (raw == null) {
+ const h = await holdingRawFor(store, mint);
+ if (!h || !(Number(h.amount_raw) > 0)) {
+ toast('No balance to sell for this coin.', { tone: 'warn' });
+ return null;
+ }
+ raw = h.amount_raw;
+ uiHint = uiHint || `${formatCompact(h.ui_amount)} tokens`;
+ }
+
+ if (!(await ensureConfirmed(store, { side: 'sell', mint, sizeDesc: uiHint ? `(${uiHint})` : '' }))) return null;
+
+ bus.emit('trade:pending', { mint, side: 'sell' });
+ try {
+ const res = await executeAgentTrade({
+ agentId: agent.id, side: 'sell', mint, tokenAmountRaw: String(raw),
+ slippageBps: DEFAULT_SLIPPAGE_BPS, network: store.getNetwork(), idempotencyKey: uuid(),
+ });
+ toast(
+ `Sold for ${formatSol(res?.out?.amount)} SOL`,
+ { tone: 'ok', link: res?.signature ? { href: explorerTxUrl(res.signature, store.getNetwork()), label: 'View ↗' } : null },
+ );
+ bus.emit('trade:done', { mint, side: 'sell', result: res });
+ return res;
+ } catch (e) {
+ toast(friendlyError(e), { tone: 'err' });
+ bus.emit('trade:error', { mint, side: 'sell', error: e });
+ return null;
+ }
+}
+
+/** Live, non-binding quote (used by the focus pane to preview before execution). */
+export async function quote({ store, side, mint, solAmount, tokenAmountRaw }) {
+ const agent = store.getAgent();
+ if (!agent?.id) throw new TradeError('No trading agent selected.', { code: 'no_agent' });
+ return previewAgentTrade({
+ agentId: agent.id, side, mint, solAmount, tokenAmountRaw,
+ slippageBps: DEFAULT_SLIPPAGE_BPS, network: store.getNetwork(),
+ });
+}
diff --git a/src/mission-control/ui.js b/src/mission-control/ui.js
new file mode 100644
index 000000000..1572622dc
--- /dev/null
+++ b/src/mission-control/ui.js
@@ -0,0 +1,86 @@
+/**
+ * Mission Control — shared UI primitives: a single styled toast and a focus-
+ * trapped confirm dialog. Both are dependency-free and respect reduced motion
+ * (the stylesheet gates the transitions).
+ */
+
+import { escapeHtml } from './format.js';
+
+let toastEl = null;
+let toastTimer = null;
+
+/**
+ * Transient toast. `tone` drives the left-border colour.
+ * @param {string} message — may contain a single trailing link via `link`.
+ * @param {{ tone?: 'ok'|'err'|'warn'|'info', ms?: number, link?: {href:string,label:string} }} [opts]
+ */
+export function toast(message, { tone = 'info', ms = 3200, link = null } = {}) {
+ if (typeof document === 'undefined') return;
+ if (!toastEl) {
+ toastEl = document.createElement('div');
+ toastEl.className = 'mc-toast';
+ toastEl.setAttribute('role', 'status');
+ toastEl.setAttribute('aria-live', 'polite');
+ document.body.appendChild(toastEl);
+ }
+ toastEl.className = `mc-toast ${tone}`;
+ toastEl.innerHTML = `${escapeHtml(message)}${
+ link ? ` <a href="${escapeHtml(link.href)}" target="_blank" rel="noopener">${escapeHtml(link.label)}</a>` : ''
+ }`;
+ // reflow so re-fired toasts re-animate
+ void toastEl.offsetWidth;
+ toastEl.dataset.show = 'true';
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => {
+ if (toastEl) toastEl.dataset.show = 'false';
+ }, ms);
+}
+
+/**
+ * Modal confirm. Resolves true on confirm, false on cancel/escape/backdrop.
+ * @param {{ title:string, body:string, confirmLabel?:string, tone?:'buy'|'sell'|'default' }} opts
+ */
+export function confirmModal({ title, body, confirmLabel = 'Confirm', tone = 'default' }) {
+ return new Promise((resolve) => {
+ const overlay = document.createElement('div');
+ overlay.className = 'mc-overlay';
+ overlay.setAttribute('role', 'dialog');
+ overlay.setAttribute('aria-modal', 'true');
+ overlay.setAttribute('aria-label', title);
+ const btnClass = tone === 'buy' ? 'mc-btn mc-btn--buy' : tone === 'sell' ? 'mc-btn mc-btn--sell' : 'mc-btn mc-btn--buy';
+ overlay.innerHTML = `
+ <div class="mc-overlay-card" style="max-width:420px">
+ <h2>${escapeHtml(title)}</h2>
+ <p style="color:var(--ink-dim,#888);line-height:1.55;margin:0 0 18px">${body}</p>
+ <div class="mc-trade-actions">
+ <button class="mc-btn" data-act="cancel" style="background:var(--surface-2,rgba(255,255,255,.06));color:var(--ink,#e8e8e8)">Cancel</button>
+ <button class="${btnClass}" data-act="ok">${escapeHtml(confirmLabel)}</button>
+ </div>
+ </div>`;
+ document.body.appendChild(overlay);
+ const okBtn = overlay.querySelector('[data-act="ok"]');
+ const cancelBtn = overlay.querySelector('[data-act="cancel"]');
+ let done = false;
+ const close = (val) => {
+ if (done) return;
+ done = true;
+ overlay.remove();
+ document.removeEventListener('keydown', onKey, true);
+ resolve(val);
+ };
+ const onKey = (e) => {
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(false); }
+ else if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); close(true); }
+ else if (e.key === 'Tab') {
+ // trap focus between the two buttons
+ e.preventDefault();
+ (document.activeElement === okBtn ? cancelBtn : okBtn).focus();
+ }
+ };
+ document.addEventListener('keydown', onKey, true);
+ okBtn.addEventListener('click', () => close(true));
+ cancelBtn.addEventListener('click', () => close(false));
+ overlay.addEventListener('mousedown', (e) => { if (e.target === overlay) close(false); });
+ okBtn.focus();
+ });
+}
diff --git a/src/signal-detail.js b/src/signal-detail.js
new file mode 100644
index 000000000..0c5c4fa2b
--- /dev/null
+++ b/src/signal-detail.js
@@ -0,0 +1,270 @@
+/**
+ * Signal feed detail controller.
+ *
+ * Renders /api/signals/feed?slug= : the publisher's verified track record, the
+ * feed's proven accuracy (hit-rate, avg realized ROI, follower ROI, emit→fill
+ * latency), and the emission log — every signal with its realized outcome and a
+ * link to the on-chain tx that proves it. A signed-in viewer can subscribe one of
+ * their agents inline (simulate or live), which auto-mirrors paid emissions.
+ */
+
+import { apiFetch } from './api.js';
+import { escapeHtml, fmtPct, compact, identicon } from './trader-format.js';
+
+const $ = (s, r = document) => r.querySelector(s);
+
+function slugFromUrl() {
+ const m = location.pathname.match(/\/signals\/([^/]+)/);
+ if (m) return decodeURIComponent(m[1]);
+ return new URLSearchParams(location.search).get('slug') || '';
+}
+function networkFromUrl() {
+ const n = new URLSearchParams(location.search).get('network');
+ return n === 'devnet' ? 'devnet' : 'mainnet';
+}
+
+const slug = slugFromUrl();
+const network = networkFromUrl();
+let feed = null;
+let myAgents = [];
+
+function epochLabel(sec) {
+ if (sec % 86400 === 0) { const d = sec / 86400; return d === 1 ? 'day' : `${d}d`; }
+ if (sec % 3600 === 0) { const h = sec / 3600; return h === 1 ? 'hour' : `${h}h`; }
+ return `${Math.round(sec / 60)}m`;
+}
+function latency(ms) {
+ if (ms == null) return '—';
+ if (ms < 1000) return `${ms}ms`;
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
+ return `${Math.round(ms / 60000)}m`;
+}
+
+function statBlock(label, value, { cls = '', sub = '' } = {}) {
+ return `<div class="sd-stat"><div class="l">${label}</div><div class="v ${cls}">${value}</div>${sub ? `<div class="s">${sub}</div>` : ''}</div>`;
+}
+
+function heroHtml(f) {
+ const p = f.publisher;
+ const avatar = p.image
+ ? `<img class="sm-avatar" src="${escapeHtml(p.image)}" alt="" />`
+ : `<span class="sm-avatar" aria-hidden="true" style="background:${identicon(p.agent_id)}"></span>`;
+ const verified = p.verified ? `<span class="sm-verified">✓ Verified track record</span>` : `<span class="sm-thin">Unverified</span>`;
+ return `
+ <div class="sd-hero">
+ <div class="sd-hero-id">
+ ${avatar}
+ <div>
+ <h1 id="sd-title">${escapeHtml(f.title)}</h1>
+ <div class="sd-hero-pub">
+ by <a href="/trader/${encodeURIComponent(p.agent_id)}">${escapeHtml(p.name)}</a>
+ ${verified}
+ </div>
+ </div>
+ </div>
+ <div class="sd-edge-big"><div class="n">${f.edge_score}</div><div class="l">Proven edge</div></div>
+ </div>`;
+}
+
+function statsHtml(f) {
+ const s = f.stats;
+ const hit = s.hit_rate != null ? `${Math.round(s.hit_rate * 100)}%` : '—';
+ const roi = s.avg_realized_pct != null ? fmtPct(s.avg_realized_pct, { sign: true }) : '—';
+ const roiCls = s.avg_realized_pct == null ? 'muted' : s.avg_realized_pct > 0 ? 'win' : s.avg_realized_pct < 0 ? 'loss' : 'muted';
+ const froi = s.avg_follower_roi_pct != null ? fmtPct(s.avg_follower_roi_pct, { sign: true }) : '—';
+ const froiCls = s.avg_follower_roi_pct == null ? 'muted' : s.avg_follower_roi_pct > 0 ? 'win' : 'loss';
+ return `
+ <div class="sd-stats">
+ ${statBlock('Hit rate', hit, { cls: s.hit_rate != null && s.hit_rate >= 0.5 ? 'win' : '', sub: `${s.winning_signals}/${s.closed_signals} won` })}
+ ${statBlock('Avg realized', roi, { cls: roiCls, sub: 'per closed signal' })}
+ ${statBlock('Follower ROI', froi, { cls: froiCls, sub: `${s.executed_fills} fills` })}
+ ${statBlock('Signals', compact(s.total_entries), { sub: `${s.closed_signals} closed` })}
+ ${statBlock('Avg latency', latency(s.avg_latency_ms), { sub: 'emit → fill' })}
+ ${statBlock('Subscribers', compact(s.subscribers), { sub: f.publisher.closed_trades != null ? `${f.publisher.closed_trades} trades` : '' })}
+ </div>`;
+}
+
+function outcomeCell(e) {
+ if (e.status !== 'closed') return `<div class="pct flat">live</div><div class="badge open">open</div>`;
+ const cls = e.outcome === 'win' ? 'win' : e.outcome === 'loss' ? 'loss' : 'flat';
+ const pct = e.realized_pnl_pct != null ? fmtPct(e.realized_pnl_pct, { sign: true }) : '—';
+ return `<div class="pct ${cls}">${pct}</div><div class="badge">${escapeHtml(e.outcome || 'flat')}</div>`;
+}
+
+function emitRow(e) {
+ const sym = e.symbol ? `$${escapeHtml(e.symbol)}` : `${escapeHtml((e.mint || '').slice(0, 6))}…`;
+ const conv = e.conviction != null ? `conv ${Math.round(e.conviction * 100)}%` : '';
+ const size = e.size_multiple != null ? `${e.size_multiple.toFixed(2)}× size` : '';
+ const proof = e.buy_url ? `<a href="${escapeHtml(e.buy_url)}" target="_blank" rel="noopener">buy ↗</a>` : '';
+ const proofS = e.sell_url ? `<a href="${escapeHtml(e.sell_url)}" target="_blank" rel="noopener">sell ↗</a>` : '';
+ const meta = [conv, size, proof, proofS].filter(Boolean).join('<span aria-hidden="true">·</span>');
+ return `
+ <div class="sd-emit">
+ <span class="sd-emit-side ${e.side}">${e.side}</span>
+ <div class="sd-emit-coin"><div class="sym">${sym}</div><div class="meta">${meta || '<span style="opacity:.6">no on-chain proof yet</span>'}</div></div>
+ <div class="sd-emit-out">${outcomeCell(e)}</div>
+ </div>`;
+}
+
+function logHtml(f) {
+ const rows = (f.emissions || []).map(emitRow).join('');
+ return `
+ <div class="sd-panel">
+ <h2>Signal log <span class="sd-count">${f.emissions?.length || 0} recent · realized outcomes</span></h2>
+ <div class="sd-log">${rows || '<p class="sd-note">No signals emitted yet. The moment this trader opens or closes a real position, it appears here.</p>'}</div>
+ </div>`;
+}
+
+function subscribeHtml(f) {
+ const p = f.pricing;
+ let price;
+ if (p.per_signal_usdc > 0 && p.per_epoch_usdc > 0) price = `<span class="amt">$${p.per_signal_usdc}</span><span class="per">/ signal · $${p.per_epoch_usdc}/${epochLabel(p.epoch_seconds)} option</span>`;
+ else if (p.per_signal_usdc > 0) price = `<span class="amt">$${p.per_signal_usdc}</span><span class="per">USDC / signal</span>`;
+ else if (p.per_epoch_usdc > 0) price = `<span class="amt">$${p.per_epoch_usdc}</span><span class="per">USDC / ${epochLabel(p.epoch_seconds)}</span>`;
+ else price = `<span class="amt">Free</span><span class="per">no charge</span>`;
+
+ const agentOpts = myAgents.length
+ ? myAgents.map((a) => `<option value="${escapeHtml(a.id)}">${escapeHtml(a.name || a.id)}</option>`).join('')
+ : '';
+ const billingOpts = [
+ p.per_signal_usdc > 0 ? `<option value="per_signal">Per signal ($${p.per_signal_usdc})</option>` : '',
+ p.per_epoch_usdc > 0 ? `<option value="per_epoch">Per ${epochLabel(p.epoch_seconds)} ($${p.per_epoch_usdc})</option>` : '',
+ ].filter(Boolean).join('');
+
+ const form = `
+ <div class="sd-modes" role="radiogroup" aria-label="Mode">
+ <div class="sd-mode is-active" data-mode="simulate" role="radio" aria-checked="true" tabindex="0">Simulate<small>track, no spend</small></div>
+ <div class="sd-mode" data-mode="live" role="radio" aria-checked="false" tabindex="0">Live<small>pay + auto-mirror</small></div>
+ </div>
+ <div class="sd-field"><label for="sd-agent">Subscriber agent</label>
+ <select id="sd-agent">${agentOpts}</select></div>
+ <div class="sd-field"><label for="sd-billing">Billing</label>
+ <select id="sd-billing">${billingOpts}</select></div>
+ <div class="sd-row2">
+ <div class="sd-field"><label for="sd-base">Base order (SOL)</label><input id="sd-base" type="number" min="0.001" step="0.01" value="0.05" /></div>
+ <div class="sd-field"><label for="sd-scale">Size scaling</label><input id="sd-scale" type="number" min="0.05" step="0.25" value="1" /></div>
+ </div>
+ <div class="sd-row2">
+ <div class="sd-field"><label for="sd-max">Max / trade (SOL)</label><input id="sd-max" type="number" min="0.001" step="0.05" value="0.25" /></div>
+ <div class="sd-field"><label for="sd-slip">Slippage (bps)</label><input id="sd-slip" type="number" min="0" max="5000" step="50" value="300" /></div>
+ </div>
+ <div class="sd-field"><label for="sd-fw">Firewall</label>
+ <select id="sd-fw"><option value="block">Block unsafe trades (recommended)</option><option value="warn">Warn only</option></select></div>
+ <button class="sd-btn" id="sd-subscribe" type="button">Subscribe &amp; auto-mirror</button>
+ <p class="sd-note" id="sd-note">Simulate mode mirrors every signal without paying or trading — proof before you commit real funds. Switch to Live to pay USDC from your agent's wallet and mirror real trades, fully spend-guarded. Halt instantly anytime from your wallet hub.</p>`;
+
+ const gate = `<div class="sd-gate"><p style="margin:0 0 8px;color:var(--ink-dim,#9aa)">Sign in and pick one of your agents to subscribe — its wallet pays the USDC and signs the mirror.</p><a href="/login?next=${encodeURIComponent(location.pathname)}">Sign in →</a></div>`;
+ const noAgents = `<div class="sd-gate"><p style="margin:0 0 8px;color:var(--ink-dim,#9aa)">You don't have an agent with a wallet yet.</p><a href="/create-agent">Create your first agent →</a></div>`;
+
+ const body = myAgents === null ? gate : (myAgents.length ? form : noAgents);
+ return `
+ <div class="sd-panel">
+ <h2>Subscribe</h2>
+ <div class="sd-price-row">${price}</div>
+ ${body}
+ </div>`;
+}
+
+function render() {
+ const root = $('#sd-root');
+ root.setAttribute('aria-busy', 'false');
+ root.innerHTML = `
+ ${heroHtml(feed)}
+ ${statsHtml(feed)}
+ <div class="sd-cols">
+ ${logHtml(feed)}
+ ${subscribeHtml(feed)}
+ </div>`;
+ document.title = `${feed.title} · Signals · three.ws`;
+ wireSubscribe();
+}
+
+function wireSubscribe() {
+ let mode = 'simulate';
+ for (const m of document.querySelectorAll('.sd-mode')) {
+ const pick = () => {
+ mode = m.dataset.mode;
+ for (const el of document.querySelectorAll('.sd-mode')) {
+ const on = el === m;
+ el.classList.toggle('is-active', on);
+ el.setAttribute('aria-checked', on ? 'true' : 'false');
+ }
+ };
+ m.addEventListener('click', pick);
+ m.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); pick(); } });
+ }
+
+ const btn = $('#sd-subscribe');
+ if (!btn) return;
+ btn.addEventListener('click', async () => {
+ const note = $('#sd-note');
+ note.className = 'sd-note';
+ const agentId = $('#sd-agent')?.value;
+ if (!agentId) { note.textContent = 'Pick a subscriber agent first.'; note.classList.add('is-error'); return; }
+ btn.disabled = true;
+ const prev = btn.textContent;
+ btn.textContent = 'Subscribing…';
+ try {
+ const res = await apiFetch('/api/signals/subscribe', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ agent_id: agentId,
+ feed_id: feed.id,
+ mode,
+ billing: $('#sd-billing')?.value || 'per_signal',
+ base_sol: Number($('#sd-base')?.value) || 0.05,
+ size_scaling: Number($('#sd-scale')?.value) || 1,
+ max_per_trade_sol: Number($('#sd-max')?.value) || 0.25,
+ slippage_bps: Number($('#sd-slip')?.value) || 300,
+ firewall_level: $('#sd-fw')?.value || 'block',
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(data.message || data.error || `HTTP ${res.status}`);
+ note.textContent = mode === 'live'
+ ? '✓ Subscribed. Your agent will pay per signal and auto-mirror new trades. Manage or kill it anytime from your wallet hub → Signals.'
+ : '✓ Subscribed in simulate mode. New signals will be tracked without spending. Switch to Live from your wallet hub when ready.';
+ note.classList.add('is-ok');
+ btn.textContent = 'Subscribed ✓';
+ setTimeout(() => { btn.disabled = false; btn.textContent = prev; }, 2500);
+ } catch (err) {
+ note.textContent = `Could not subscribe: ${err.message}`;
+ note.classList.add('is-error');
+ btn.disabled = false;
+ btn.textContent = prev;
+ }
+ });
+}
+
+function errorState(msg) {
+ const root = $('#sd-root');
+ root.setAttribute('aria-busy', 'false');
+ root.innerHTML = `<div class="sm-empty"><h2>${escapeHtml(msg)}</h2><p>This feed may have been paused or never existed.</p><a class="sm-cta" href="/signals">Browse all feeds →</a></div>`;
+}
+
+async function loadAgents() {
+ try {
+ const res = await apiFetch('/api/agents', { allowAnonymous: true });
+ if (res.status === 401) { myAgents = null; return; }
+ const j = await res.json().catch(() => ({}));
+ const list = j.agents || j.data?.agents || j.data || [];
+ myAgents = list.filter((a) => a && a.id);
+ } catch { myAgents = []; }
+}
+
+async function init() {
+ if (!slug) { errorState('No feed specified'); return; }
+ const [detailRes] = await Promise.all([
+ apiFetch(`/api/signals/feed?slug=${encodeURIComponent(slug)}&network=${network}`, { allowAnonymous: true }).catch(() => null),
+ loadAgents(),
+ ]);
+ if (!detailRes || !detailRes.ok) { errorState('Feed not found'); return; }
+ const data = await detailRes.json().catch(() => null);
+ if (!data?.feed) { errorState('Feed not found'); return; }
+ feed = data.feed;
+ render();
+}
+
+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
+else init();
diff --git a/src/signals.css b/src/signals.css
new file mode 100644
index 000000000..a40fd1e2f
--- /dev/null
+++ b/src/signals.css
@@ -0,0 +1,203 @@
+/* Signal Marketplace — directory + shared signal tokens.
+ Reuses the platform's dark/light theme tokens (var fallbacks keep it robust if
+ a token is missing). Mobile-first; grid collapses to one column at 640px. */
+
+:root {
+ --sm-accent: #8b5cf6;
+ --sm-accent-soft: rgba(139, 92, 246, 0.12);
+ --sm-stroke: rgba(139, 92, 246, 0.32);
+ --sm-win: #34d399;
+ --sm-loss: #f87171;
+ --sm-flat: #94a3b8;
+}
+
+.sm-shell {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: clamp(16px, 3vw, 40px) clamp(14px, 3vw, 28px) 80px;
+}
+
+/* ── Hero ─────────────────────────────────────────────────────────────────── */
+.sm-hero { margin: 8px 0 26px; }
+.sm-kicker {
+ display: inline-flex; align-items: center; gap: 8px;
+ font: 600 12px/1.2 var(--mono, ui-monospace, monospace);
+ letter-spacing: 0.04em; text-transform: uppercase;
+ color: var(--ink-dim, #9aa); margin: 0 0 14px;
+}
+.sm-live-dot {
+ width: 8px; height: 8px; border-radius: 50%; background: var(--sm-win);
+ box-shadow: 0 0 0 0 rgba(52, 211, 153, 0.55); animation: sm-pulse 2s ease infinite;
+}
+@keyframes sm-pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(52,211,153,0.5); } 70% { box-shadow: 0 0 0 7px rgba(52,211,153,0); } }
+.sm-title {
+ margin: 0 0 12px; font: 700 clamp(28px, 5vw, 46px)/1.05 var(--display, 'Space Grotesk', sans-serif);
+ color: var(--ink-bright, #fff); letter-spacing: -0.02em;
+}
+.sm-sub {
+ margin: 0; max-width: 760px; font-size: clamp(14px, 1.6vw, 16px); line-height: 1.62;
+ color: var(--ink-dim, #aab);
+}
+.sm-sub strong { color: var(--ink, #e8e8ee); font-weight: 600; }
+
+.sm-summary {
+ display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px;
+ margin: 22px 0 0; padding: 0;
+}
+.sm-summary-cell {
+ background: var(--surface-1, rgba(255,255,255,0.03)); border: 1px solid var(--line, rgba(255,255,255,0.08));
+ border-radius: 12px; padding: 12px 14px;
+}
+.sm-summary-cell dt { font: 600 11px/1 var(--mono, monospace); text-transform: uppercase; letter-spacing: 0.05em; color: var(--ink-dim, #889); }
+.sm-summary-cell dd { margin: 8px 0 0; font: 600 19px/1 var(--display, sans-serif); color: var(--ink-bright, #fff); }
+@media (max-width: 640px) { .sm-summary { grid-template-columns: repeat(2, 1fr); } }
+
+/* ── Controls ─────────────────────────────────────────────────────────────── */
+.sm-controls { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; justify-content: space-between; margin: 0 0 18px; }
+.sm-seg { display: inline-flex; gap: 4px; padding: 4px; border: 1px solid var(--line, rgba(255,255,255,0.08)); border-radius: 12px; background: var(--surface-1, rgba(255,255,255,0.03)); flex-wrap: wrap; }
+.sm-seg-btn {
+ appearance: none; border: 0; cursor: pointer; font: 600 12.5px/1 var(--body, Inter, sans-serif);
+ color: var(--ink-dim, #9aa); background: transparent; padding: 8px 13px; border-radius: 9px;
+ transition: color 0.14s, background 0.14s;
+}
+.sm-seg-btn:hover { color: var(--ink-bright, #fff); }
+.sm-seg-btn.is-active { color: #160d28; background: var(--sm-accent); }
+.sm-seg-btn:focus-visible { outline: 2px solid var(--sm-accent); outline-offset: 2px; }
+[data-theme='dark'] .sm-seg-btn.is-active { color: #fff; background: color-mix(in srgb, var(--sm-accent) 70%, #000); }
+
+/* ── Status (loading / empty / error) ─────────────────────────────────────── */
+.sm-status { margin: 0 0 16px; padding: 14px 16px; border-radius: 12px; font-size: 13.5px; line-height: 1.5; border: 1px solid var(--line, rgba(255,255,255,0.1)); background: var(--surface-1, rgba(255,255,255,0.03)); color: var(--ink-dim, #aab); }
+.sm-status.is-error { border-color: color-mix(in srgb, var(--sm-loss) 40%, transparent); background: color-mix(in srgb, var(--sm-loss) 8%, transparent); color: var(--sm-loss); }
+.sm-status .sm-retry { margin-left: 10px; appearance: none; cursor: pointer; border: 1px solid currentColor; background: transparent; color: inherit; border-radius: 8px; padding: 5px 11px; font: 600 12px/1 var(--body, sans-serif); }
+.sm-empty { text-align: center; padding: 60px 20px; }
+.sm-empty h2 { margin: 0 0 8px; font: 600 20px/1.2 var(--display, sans-serif); color: var(--ink-bright, #fff); }
+.sm-empty p { margin: 0 auto 18px; max-width: 460px; color: var(--ink-dim, #9aa); line-height: 1.6; font-size: 14px; }
+.sm-empty .sm-cta { display: inline-block; text-decoration: none; font: 600 13px/1 var(--body, sans-serif); color: #160d28; background: var(--sm-accent); padding: 11px 18px; border-radius: 10px; }
+[data-theme='dark'] .sm-empty .sm-cta { color: #fff; background: color-mix(in srgb, var(--sm-accent) 72%, #000); }
+
+/* ── Grid + cards ─────────────────────────────────────────────────────────── */
+.sm-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(330px, 1fr)); gap: 16px; }
+@media (max-width: 480px) { .sm-grid { grid-template-columns: 1fr; } }
+
+.sm-card {
+ position: relative; display: flex; flex-direction: column; gap: 14px;
+ background: var(--surface-1, rgba(255,255,255,0.03)); border: 1px solid var(--line, rgba(255,255,255,0.08));
+ border-radius: 16px; padding: 18px; text-decoration: none; color: inherit;
+ transition: border-color 0.16s, transform 0.16s, box-shadow 0.16s;
+ animation: sm-card-in 0.32s ease both;
+}
+.sm-card:hover { border-color: var(--sm-stroke); transform: translateY(-2px); box-shadow: 0 12px 32px -16px rgba(139, 92, 246, 0.45); }
+.sm-card:focus-visible { outline: 2px solid var(--sm-accent); outline-offset: 2px; }
+@keyframes sm-card-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
+
+.sm-rank { position: absolute; top: 14px; right: 16px; font: 700 12px/1 var(--mono, monospace); color: var(--ink-dim, #778); }
+
+.sm-card-head { display: flex; align-items: center; gap: 12px; }
+.sm-avatar { width: 44px; height: 44px; border-radius: 11px; flex: none; object-fit: cover; background: var(--surface-2, rgba(255,255,255,0.06)); border: 1px solid var(--line, rgba(255,255,255,0.1)); }
+.sm-card-head .sm-id { min-width: 0; }
+.sm-feed-title { margin: 0; font: 600 15px/1.25 var(--display, sans-serif); color: var(--ink-bright, #fff); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.sm-pub { display: flex; align-items: center; gap: 6px; margin-top: 3px; font-size: 12px; color: var(--ink-dim, #9aa); }
+.sm-verified { display: inline-flex; align-items: center; gap: 3px; font: 600 10.5px/1 var(--mono, monospace); color: var(--sm-win); background: color-mix(in srgb, var(--sm-win) 12%, transparent); border: 1px solid color-mix(in srgb, var(--sm-win) 30%, transparent); border-radius: 6px; padding: 3px 6px; }
+
+.sm-edge { display: flex; align-items: baseline; gap: 8px; }
+.sm-edge-score { font: 700 30px/1 var(--display, sans-serif); color: var(--ink-bright, #fff); }
+.sm-edge-label { font: 600 11px/1.3 var(--mono, monospace); text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-dim, #889); }
+.sm-edge-bar { height: 6px; border-radius: 999px; background: var(--surface-2, rgba(255,255,255,0.07)); overflow: hidden; }
+.sm-edge-fill { height: 100%; border-radius: 999px; background: linear-gradient(90deg, var(--sm-accent), var(--sm-win)); transition: width 0.5s ease; }
+
+.sm-metrics { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
+.sm-metric { background: var(--surface-2, rgba(255,255,255,0.04)); border-radius: 10px; padding: 9px 10px; }
+.sm-metric .l { font: 600 10px/1 var(--mono, monospace); text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-dim, #889); }
+.sm-metric .v { margin-top: 5px; font: 600 14px/1 var(--display, sans-serif); color: var(--ink-bright, #fff); }
+.sm-metric .v.win { color: var(--sm-win); }
+.sm-metric .v.loss { color: var(--sm-loss); }
+.sm-metric .v.muted { color: var(--ink-dim, #9aa); }
+
+.sm-card-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding-top: 4px; border-top: 1px solid var(--line, rgba(255,255,255,0.06)); }
+.sm-price { display: flex; flex-direction: column; gap: 2px; }
+.sm-price .amt { font: 600 15px/1 var(--display, sans-serif); color: var(--ink-bright, #fff); }
+.sm-price .per { font: 500 11px/1 var(--mono, monospace); color: var(--ink-dim, #889); }
+.sm-thin { font: 600 10.5px/1 var(--mono, monospace); color: var(--sm-flat); background: var(--surface-2, rgba(255,255,255,0.05)); border-radius: 6px; padding: 4px 7px; }
+.sm-view { font: 600 12.5px/1 var(--body, sans-serif); color: var(--sm-accent); white-space: nowrap; }
+.sm-card:hover .sm-view { text-decoration: underline; }
+
+/* Skeleton loaders. */
+.sm-skel { position: relative; overflow: hidden; }
+.sm-skel::after { content: ''; position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.06), transparent); animation: sm-shimmer 1.2s infinite; }
+@keyframes sm-shimmer { 100% { transform: translateX(100%); } }
+.sm-skel-line { height: 12px; border-radius: 6px; background: var(--surface-2, rgba(255,255,255,0.06)); }
+
+/* ── Feed detail ──────────────────────────────────────────────────────────── */
+.sd-back { display: inline-block; margin: 0 0 16px; font: 600 13px/1 var(--body, sans-serif); color: var(--ink-dim, #9aa); text-decoration: none; }
+.sd-back:hover { color: var(--ink-bright, #fff); }
+
+.sd-hero { display: flex; flex-wrap: wrap; gap: 18px; align-items: flex-start; justify-content: space-between; background: linear-gradient(160deg, var(--sm-accent-soft), var(--surface-1, rgba(255,255,255,0.03))); border: 1px solid var(--sm-stroke); border-radius: 18px; padding: 22px; }
+.sd-hero-id { display: flex; gap: 14px; align-items: center; min-width: 0; }
+.sd-hero .sm-avatar { width: 56px; height: 56px; border-radius: 14px; }
+.sd-hero h1 { margin: 0; font: 700 clamp(20px, 3vw, 28px)/1.1 var(--display, sans-serif); color: var(--ink-bright, #fff); letter-spacing: -0.01em; }
+.sd-hero-pub { margin-top: 6px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 13px; color: var(--ink-dim, #9aa); }
+.sd-hero-pub a { color: var(--sm-accent); text-decoration: none; }
+.sd-hero-pub a:hover { text-decoration: underline; }
+.sd-edge-big { text-align: right; }
+.sd-edge-big .n { font: 700 44px/1 var(--display, sans-serif); color: var(--ink-bright, #fff); }
+.sd-edge-big .l { font: 600 11px/1.3 var(--mono, monospace); text-transform: uppercase; letter-spacing: 0.05em; color: var(--ink-dim, #889); }
+
+.sd-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; margin: 18px 0; }
+.sd-stat { background: var(--surface-1, rgba(255,255,255,0.03)); border: 1px solid var(--line, rgba(255,255,255,0.08)); border-radius: 12px; padding: 13px 14px; }
+.sd-stat .l { font: 600 10.5px/1 var(--mono, monospace); text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-dim, #889); }
+.sd-stat .v { margin-top: 7px; font: 600 18px/1 var(--display, sans-serif); color: var(--ink-bright, #fff); }
+.sd-stat .v.win { color: var(--sm-win); } .sd-stat .v.loss { color: var(--sm-loss); } .sd-stat .v.muted { color: var(--ink-dim, #9aa); }
+.sd-stat .s { margin-top: 3px; font: 500 11px/1.2 var(--mono, monospace); color: var(--ink-dim, #778); }
+
+.sd-cols { display: grid; grid-template-columns: 1.5fr 1fr; gap: 18px; align-items: start; }
+@media (max-width: 820px) { .sd-cols { grid-template-columns: 1fr; } }
+
+.sd-panel { background: var(--surface-1, rgba(255,255,255,0.03)); border: 1px solid var(--line, rgba(255,255,255,0.08)); border-radius: 16px; padding: 18px; }
+.sd-panel h2 { margin: 0 0 14px; font: 600 15px/1.2 var(--display, sans-serif); color: var(--ink-bright, #fff); display: flex; align-items: center; gap: 8px; }
+.sd-panel h2 .sd-count { font: 600 11px/1 var(--mono, monospace); color: var(--ink-dim, #889); }
+
+/* Emission log */
+.sd-log { display: flex; flex-direction: column; gap: 8px; max-height: 560px; overflow-y: auto; }
+.sd-emit { display: grid; grid-template-columns: auto 1fr auto; gap: 10px; align-items: center; padding: 10px 12px; border-radius: 11px; background: var(--surface-2, rgba(255,255,255,0.04)); }
+.sd-emit-side { font: 700 10px/1 var(--mono, monospace); text-transform: uppercase; padding: 4px 7px; border-radius: 6px; }
+.sd-emit-side.entry { color: #160d28; background: var(--sm-accent); }
+[data-theme='dark'] .sd-emit-side.entry { color: #fff; background: color-mix(in srgb, var(--sm-accent) 72%, #000); }
+.sd-emit-side.exit { color: var(--sm-flat); background: var(--surface-3, rgba(255,255,255,0.08)); }
+.sd-emit-coin { min-width: 0; }
+.sd-emit-coin .sym { font: 600 13px/1.2 var(--display, sans-serif); color: var(--ink-bright, #fff); }
+.sd-emit-coin .meta { font: 500 11px/1.3 var(--mono, monospace); color: var(--ink-dim, #889); margin-top: 2px; display: flex; gap: 8px; flex-wrap: wrap; }
+.sd-emit-coin .meta a { color: var(--sm-accent); text-decoration: none; }
+.sd-emit-coin .meta a:hover { text-decoration: underline; }
+.sd-emit-out { text-align: right; white-space: nowrap; }
+.sd-emit-out .pct { font: 700 14px/1 var(--display, sans-serif); }
+.sd-emit-out .pct.win { color: var(--sm-win); } .sd-emit-out .pct.loss { color: var(--sm-loss); } .sd-emit-out .pct.flat { color: var(--sm-flat); }
+.sd-emit-out .badge { display: inline-block; margin-top: 3px; font: 600 9.5px/1 var(--mono, monospace); text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-dim, #889); }
+.sd-emit-out .badge.open { color: var(--sm-accent); }
+
+/* Subscribe panel */
+.sd-price-row { display: flex; align-items: baseline; gap: 8px; margin-bottom: 16px; }
+.sd-price-row .amt { font: 700 24px/1 var(--display, sans-serif); color: var(--ink-bright, #fff); }
+.sd-price-row .per { font: 500 12px/1 var(--mono, monospace); color: var(--ink-dim, #889); }
+.sd-field { margin-bottom: 13px; }
+.sd-field label { display: block; font: 600 11px/1 var(--mono, monospace); text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-dim, #889); margin-bottom: 6px; }
+.sd-field select, .sd-field input { width: 100%; box-sizing: border-box; font: 500 13px/1.3 var(--body, sans-serif); color: var(--ink, #e8e8ee); background: var(--surface-2, rgba(255,255,255,0.05)); border: 1px solid var(--line, rgba(255,255,255,0.12)); border-radius: 9px; padding: 9px 11px; }
+.sd-field select:focus, .sd-field input:focus { outline: none; border-color: var(--sm-stroke); }
+.sd-row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+.sd-modes { display: flex; gap: 8px; }
+.sd-mode { flex: 1; cursor: pointer; text-align: center; padding: 10px; border-radius: 10px; border: 1px solid var(--line, rgba(255,255,255,0.12)); background: var(--surface-2, rgba(255,255,255,0.04)); font: 600 12.5px/1.3 var(--body, sans-serif); color: var(--ink-dim, #9aa); transition: all 0.14s; }
+.sd-mode small { display: block; font: 500 10.5px/1.3 var(--mono, monospace); margin-top: 3px; color: var(--ink-dim, #778); }
+.sd-mode.is-active { border-color: var(--sm-stroke); background: var(--sm-accent-soft); color: var(--ink-bright, #fff); }
+.sd-btn { width: 100%; appearance: none; cursor: pointer; font: 600 14px/1 var(--body, sans-serif); color: #160d28; background: var(--sm-accent); border: 0; border-radius: 11px; padding: 13px; margin-top: 6px; transition: background 0.14s, transform 0.1s; }
+[data-theme='dark'] .sd-btn { color: #fff; background: color-mix(in srgb, var(--sm-accent) 72%, #000); }
+.sd-btn:hover:not(:disabled) { background: color-mix(in srgb, var(--sm-accent) 86%, #fff); }
+.sd-btn:active:not(:disabled) { transform: translateY(1px); }
+.sd-btn:disabled { opacity: 0.55; cursor: not-allowed; }
+.sd-note { margin-top: 12px; font-size: 12px; line-height: 1.55; color: var(--ink-dim, #889); }
+.sd-note.is-error { color: var(--sm-loss); }
+.sd-note.is-ok { color: var(--sm-win); }
+.sd-gate { padding: 16px; border-radius: 12px; background: var(--surface-2, rgba(255,255,255,0.04)); text-align: center; }
+.sd-gate a { color: var(--sm-accent); font-weight: 600; text-decoration: none; }
+
+@media (prefers-reduced-motion: reduce) {
+ .sm-card, .sm-live-dot, .sm-skel::after, .sm-edge-fill, .sd-mode, .sd-btn { animation: none; transition: none; }
+}
diff --git a/src/signals.js b/src/signals.js
new file mode 100644
index 000000000..7f5ae4570
--- /dev/null
+++ b/src/signals.js
@@ -0,0 +1,198 @@
+/**
+ * Signal Marketplace controller.
+ *
+ * Renders /api/signals/marketplace into a ranked, filterable directory of paid
+ * alpha feeds. Feeds are scored by PROVEN realized edge (confidence-regressed),
+ * not follower count. State (sort / network) reflects into the URL so any view is
+ * shareable; every card deep-links to the feed detail page.
+ */
+
+import { escapeHtml, fmtPct, compact, identicon } from './trader-format.js';
+
+const API = '/api/signals/marketplace';
+const SORTS = new Set(['edge', 'roi', 'hitrate', 'subscribers', 'newest']);
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const REFRESH_MS = 30_000;
+
+const $ = (s, r = document) => r.querySelector(s);
+const state = { sort: 'edge', network: 'mainnet' };
+let timer = null;
+let firstLoad = true;
+
+function readUrl() {
+ const p = new URLSearchParams(location.search);
+ if (SORTS.has(p.get('sort'))) state.sort = p.get('sort');
+ if (NETWORKS.has(p.get('network'))) state.network = p.get('network');
+}
+function writeUrl() {
+ const p = new URLSearchParams();
+ if (state.sort !== 'edge') p.set('sort', state.sort);
+ if (state.network !== 'mainnet') p.set('network', state.network);
+ const qs = p.toString();
+ history.replaceState(null, '', qs ? `?${qs}` : location.pathname);
+}
+
+function syncControls() {
+ for (const btn of document.querySelectorAll('#sm-sort .sm-seg-btn')) {
+ const on = btn.dataset.sort === state.sort;
+ btn.classList.toggle('is-active', on);
+ btn.setAttribute('aria-selected', on ? 'true' : 'false');
+ }
+ for (const btn of document.querySelectorAll('#sm-net .sm-seg-btn')) {
+ const on = btn.dataset.net === state.network;
+ btn.classList.toggle('is-active', on);
+ btn.setAttribute('aria-selected', on ? 'true' : 'false');
+ }
+}
+
+function setStatus(msg, { error = false, retry = false } = {}) {
+ const el = $('#sm-status');
+ if (!el) return;
+ if (!msg) { el.hidden = true; el.innerHTML = ''; return; }
+ el.hidden = false;
+ el.classList.toggle('is-error', error);
+ el.innerHTML = escapeHtml(msg) + (retry ? ' <button class="sm-retry" type="button">Retry</button>' : '');
+ if (retry) $('.sm-retry', el)?.addEventListener('click', () => load());
+}
+
+function skeletonGrid() {
+ const cards = Array.from({ length: 6 }, () => `
+ <div class="sm-card sm-skel" aria-hidden="true">
+ <div class="sm-card-head"><div class="sm-avatar"></div><div class="sm-id" style="flex:1">
+ <div class="sm-skel-line" style="width:62%"></div>
+ <div class="sm-skel-line" style="width:40%;margin-top:8px;height:9px"></div></div></div>
+ <div class="sm-skel-line" style="width:34%;height:26px"></div>
+ <div class="sm-skel-line"></div>
+ <div class="sm-metrics"><div class="sm-skel-line" style="height:38px"></div><div class="sm-skel-line" style="height:38px"></div><div class="sm-skel-line" style="height:38px"></div></div>
+ </div>`).join('');
+ $('#sm-grid').innerHTML = cards;
+}
+
+function priceBlock(p) {
+ if (p.per_signal_usdc > 0 && p.per_epoch_usdc > 0) {
+ return `<span class="amt">$${p.per_signal_usdc}</span><span class="per">/signal · $${p.per_epoch_usdc}/${epochLabel(p.epoch_seconds)}</span>`;
+ }
+ if (p.per_signal_usdc > 0) return `<span class="amt">$${p.per_signal_usdc}</span><span class="per">USDC / signal</span>`;
+ if (p.per_epoch_usdc > 0) return `<span class="amt">$${p.per_epoch_usdc}</span><span class="per">USDC / ${epochLabel(p.epoch_seconds)}</span>`;
+ return `<span class="amt">Free</span><span class="per">no charge</span>`;
+}
+function epochLabel(sec) {
+ if (sec % 86400 === 0) { const d = sec / 86400; return d === 1 ? 'day' : `${d}d`; }
+ if (sec % 3600 === 0) { const h = sec / 3600; return h === 1 ? 'hour' : `${h}h`; }
+ return `${Math.round(sec / 60)}m`;
+}
+
+function metric(label, value, cls = '') {
+ return `<div class="sm-metric"><div class="l">${label}</div><div class="v ${cls}">${value}</div></div>`;
+}
+
+function card(f) {
+ const s = f.stats;
+ const avatar = f.publisher.image
+ ? `<img class="sm-avatar" src="${escapeHtml(f.publisher.image)}" alt="" loading="lazy" />`
+ : `<span class="sm-avatar" aria-hidden="true" style="background:${identicon(f.publisher.agent_id)}"></span>`;
+ const verified = f.publisher.verified
+ ? `<span class="sm-verified" title="Verified on-chain track record">✓ Verified</span>`
+ : '';
+ const hit = s.hit_rate != null ? `${Math.round(s.hit_rate * 100)}%` : '—';
+ const roi = s.avg_realized_pct != null ? fmtPct(s.avg_realized_pct, { sign: true }) : '—';
+ const roiCls = s.avg_realized_pct == null ? 'muted' : s.avg_realized_pct > 0 ? 'win' : s.avg_realized_pct < 0 ? 'loss' : 'muted';
+ const thin = s.closed_signals < 10
+ ? `<span class="sm-thin" title="Fewer than 10 closed signals — edge is regressed toward neutral until proven">Building track record</span>`
+ : '';
+ return `
+ <a class="sm-card" href="/signals/${encodeURIComponent(f.slug)}" aria-label="${escapeHtml(f.title)} by ${escapeHtml(f.publisher.name)} — edge ${f.edge_score}">
+ <span class="sm-rank">#${f.rank}</span>
+ <div class="sm-card-head">
+ ${avatar}
+ <div class="sm-id">
+ <h3 class="sm-feed-title">${escapeHtml(f.title)}</h3>
+ <div class="sm-pub">${escapeHtml(f.publisher.name)} ${verified}</div>
+ </div>
+ </div>
+ <div>
+ <div class="sm-edge"><span class="sm-edge-score">${f.edge_score}</span><span class="sm-edge-label">Proven<br>edge</span></div>
+ <div class="sm-edge-bar" aria-hidden="true"><span class="sm-edge-fill" style="width:${Math.max(4, f.edge_score)}%"></span></div>
+ </div>
+ <div class="sm-metrics">
+ ${metric('Hit rate', hit, s.hit_rate != null && s.hit_rate >= 0.5 ? 'win' : '')}
+ ${metric('Avg ROI', roi, roiCls)}
+ ${metric('Signals', `${compact(s.closed_signals)}<span style="font-size:11px;color:var(--ink-dim,#889)">/${compact(s.total_entries)}</span>`)}
+ </div>
+ <div class="sm-card-foot">
+ <div class="sm-price">${priceBlock(f.pricing)}</div>
+ ${thin || `<span class="sm-view">${s.subscribers} sub${s.subscribers === 1 ? '' : 's'} · View →</span>`}
+ </div>
+ </a>`;
+}
+
+function emptyState() {
+ $('#sm-grid').innerHTML = `
+ <div class="sm-empty" style="grid-column:1/-1">
+ <h2>No live feeds yet</h2>
+ <p>Verified traders haven't published a feed on ${state.network} yet. Build a verified track record on the
+ leaderboard, then publish your signals from your agent's wallet — your followers' agents pay per signal and auto-mirror.</p>
+ <a class="sm-cta" href="/leaderboard">See the trader leaderboard →</a>
+ </div>`;
+}
+
+function renderSummary(feeds) {
+ const verified = feeds.filter((f) => f.publisher.verified).length;
+ const closed = feeds.reduce((a, f) => a + (f.stats.closed_signals || 0), 0);
+ const topEdge = feeds.reduce((a, f) => Math.max(a, f.edge_score || 0), 0);
+ $('#sm-sum-feeds').textContent = compact(feeds.length);
+ $('#sm-sum-verified').textContent = compact(verified);
+ $('#sm-sum-closed').textContent = compact(closed);
+ $('#sm-sum-edge').textContent = feeds.length ? String(topEdge) : '—';
+}
+
+async function load() {
+ const grid = $('#sm-grid');
+ if (firstLoad) { skeletonGrid(); grid.setAttribute('aria-busy', 'true'); }
+ try {
+ const res = await fetch(`${API}?network=${state.network}&sort=${state.sort}&limit=60`, { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ const feeds = Array.isArray(data.feeds) ? data.feeds : [];
+ setStatus(null);
+ renderSummary(feeds);
+ if (!feeds.length) emptyState();
+ else grid.innerHTML = feeds.map(card).join('');
+ grid.setAttribute('aria-busy', 'false');
+ firstLoad = false;
+ } catch (err) {
+ if (firstLoad) {
+ grid.innerHTML = '';
+ grid.setAttribute('aria-busy', 'false');
+ setStatus('Could not load the marketplace. Check your connection and try again.', { error: true, retry: true });
+ } else {
+ setStatus('Reconnecting — showing the last known board.', { error: false });
+ }
+ }
+}
+
+function bindControls() {
+ $('#sm-sort')?.addEventListener('click', (e) => {
+ const btn = e.target.closest('.sm-seg-btn'); if (!btn) return;
+ state.sort = btn.dataset.sort; firstLoad = true; syncControls(); writeUrl(); load();
+ });
+ $('#sm-net')?.addEventListener('click', (e) => {
+ const btn = e.target.closest('.sm-seg-btn'); if (!btn) return;
+ state.network = btn.dataset.net; firstLoad = true; syncControls(); writeUrl(); load();
+ });
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) { clearInterval(timer); timer = null; }
+ else if (!timer) { load(); timer = setInterval(load, REFRESH_MS); }
+ });
+}
+
+function init() {
+ readUrl();
+ syncControls();
+ bindControls();
+ load();
+ timer = setInterval(load, REFRESH_MS);
+}
+
+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
+else init();
diff --git a/src/swarms.css b/src/swarms.css
new file mode 100644
index 000000000..44ff5b0a1
--- /dev/null
+++ b/src/swarms.css
@@ -0,0 +1,233 @@
+/* Trading Swarms — directory + dashboard. All color/space/type from /tokens.css. */
+
+.sw-shell {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: var(--space-xl) var(--space-lg) var(--space-2xl);
+ min-height: 70vh;
+}
+
+/* ── hero ─────────────────────────────────────────────────────────────────── */
+.sw-hero {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-lg);
+ align-items: flex-end;
+ justify-content: space-between;
+ margin-bottom: var(--space-xl);
+}
+.sw-hero h1 {
+ font-family: var(--font-display, inherit);
+ font-size: var(--text-2xl);
+ line-height: 1.05;
+ margin: 0 0 var(--space-xs);
+ color: var(--ink-bright);
+ letter-spacing: -0.02em;
+}
+.sw-hero p {
+ margin: 0;
+ max-width: 56ch;
+ color: var(--ink-dim);
+ font-size: var(--text-ui);
+ line-height: 1.5;
+}
+.sw-hero-actions {
+ display: flex;
+ gap: var(--space-sm);
+ align-items: center;
+}
+
+/* ── buttons ──────────────────────────────────────────────────────────────── */
+.sw-btn {
+ font: inherit;
+ font-size: var(--text-md);
+ font-weight: 600;
+ padding: var(--space-xs) var(--space-md);
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-2);
+ color: var(--ink);
+ cursor: pointer;
+ transition: transform var(--duration-fast) var(--ease-standard),
+ background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast);
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2xs);
+}
+.sw-btn:hover { background: var(--surface-3); transform: translateY(-1px); }
+.sw-btn:active { transform: translateY(0); }
+.sw-btn:focus-visible { outline: 2px solid var(--wallet-accent); outline-offset: 2px; }
+.sw-btn--primary { background: var(--ink-bright); color: #0a0a0a; border-color: transparent; }
+.sw-btn--primary:hover { background: #fff; }
+.sw-btn--danger { background: rgba(248, 113, 113, 0.12); border-color: rgba(248, 113, 113, 0.4); color: var(--danger); }
+.sw-btn--danger:hover { background: rgba(248, 113, 113, 0.2); }
+.sw-btn--ghost { background: transparent; }
+.sw-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
+.sw-btn--sm { font-size: var(--text-sm); padding: var(--space-3xs) var(--space-sm); }
+
+/* ── directory grid ───────────────────────────────────────────────────────── */
+.sw-toolbar {
+ display: flex;
+ gap: var(--space-sm);
+ align-items: center;
+ flex-wrap: wrap;
+ margin-bottom: var(--space-lg);
+}
+.sw-seg {
+ display: inline-flex;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ overflow: hidden;
+ background: var(--surface-1);
+}
+.sw-seg button {
+ font: inherit;
+ font-size: var(--text-sm);
+ padding: var(--space-2xs) var(--space-md);
+ background: transparent;
+ color: var(--ink-dim);
+ border: 0;
+ cursor: pointer;
+ transition: color var(--duration-fast), background var(--duration-fast);
+}
+.sw-seg button[aria-pressed='true'] { background: var(--surface-3); color: var(--ink-bright); }
+
+.sw-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(310px, 1fr));
+ gap: var(--space-md);
+}
+.sw-card {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-sm);
+ padding: var(--space-md);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--surface-glass);
+ cursor: pointer;
+ text-decoration: none;
+ color: inherit;
+ transition: transform var(--duration-base) var(--ease-emphasized),
+ border-color var(--duration-base), box-shadow var(--duration-base);
+}
+.sw-card:hover { transform: translateY(-3px); border-color: var(--stroke-strong); box-shadow: var(--shadow-2); }
+.sw-card:focus-visible { outline: 2px solid var(--wallet-accent); outline-offset: 2px; }
+.sw-card-top { display: flex; justify-content: space-between; align-items: flex-start; gap: var(--space-sm); }
+.sw-card-name { font-size: var(--text-lg); font-weight: 650; color: var(--ink-bright); margin: 0; line-height: 1.15; }
+.sw-card-desc { font-size: var(--text-sm); color: var(--ink-dim); margin: 0; line-height: 1.45; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
+.sw-pill {
+ font-size: var(--text-2xs);
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ padding: 2px var(--space-xs);
+ border-radius: var(--radius-pill);
+ border: 1px solid var(--stroke);
+ color: var(--ink-dim);
+ white-space: nowrap;
+}
+.sw-pill--active { color: var(--success); border-color: rgba(74, 222, 128, 0.4); background: rgba(74, 222, 128, 0.08); }
+.sw-pill--paused { color: var(--warn); border-color: rgba(251, 191, 36, 0.4); }
+.sw-pill--killed { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }
+.sw-pill--open { color: var(--wallet-accent); border-color: rgba(167, 139, 250, 0.4); }
+
+.sw-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--space-xs); margin-top: auto; }
+.sw-stat { display: flex; flex-direction: column; gap: 1px; }
+.sw-stat-v { font-size: var(--text-md); font-weight: 650; color: var(--ink-bright); font-variant-numeric: tabular-nums; }
+.sw-stat-l { font-size: var(--text-2xs); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.04em; }
+.pos { color: var(--success) !important; }
+.neg { color: var(--danger) !important; }
+
+/* ── dashboard ────────────────────────────────────────────────────────────── */
+.sw-back { display: inline-flex; align-items: center; gap: var(--space-2xs); color: var(--ink-dim); text-decoration: none; font-size: var(--text-sm); margin-bottom: var(--space-md); }
+.sw-back:hover { color: var(--ink); }
+
+.sw-dash-head { display: flex; flex-wrap: wrap; gap: var(--space-md); align-items: flex-start; justify-content: space-between; margin-bottom: var(--space-lg); }
+.sw-dash-head h1 { margin: 0 0 var(--space-3xs); font-size: var(--text-xl); color: var(--ink-bright); }
+.sw-live { display: inline-flex; align-items: center; gap: var(--space-2xs); font-size: var(--text-2xs); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.05em; }
+.sw-live .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ink-faint); }
+.sw-live[data-state='live'] .dot { background: var(--success); box-shadow: 0 0 0 3px rgba(74, 222, 128, 0.18); }
+.sw-live[data-state='live'] { color: var(--success); }
+
+.sw-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: var(--space-sm); margin-bottom: var(--space-lg); }
+.sw-tile { padding: var(--space-md); border: 1px solid var(--stroke); border-radius: var(--radius-lg); background: var(--surface-1); }
+.sw-tile-v { font-size: var(--text-lg); font-weight: 700; color: var(--ink-bright); font-variant-numeric: tabular-nums; }
+.sw-tile-l { font-size: var(--text-2xs); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.04em; margin-top: 2px; }
+.sw-tile a { color: var(--wallet-accent); text-decoration: none; font-size: var(--text-sm); }
+.sw-tile a:hover { text-decoration: underline; }
+
+.sw-cols { display: grid; grid-template-columns: 1.1fr 1fr; gap: var(--space-lg); align-items: start; }
+@media (max-width: 880px) { .sw-cols { grid-template-columns: 1fr; } }
+
+.sw-panel { border: 1px solid var(--stroke); border-radius: var(--radius-lg); background: var(--surface-1); overflow: hidden; margin-bottom: var(--space-lg); }
+.sw-panel-h { display: flex; justify-content: space-between; align-items: center; padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--stroke); }
+.sw-panel-h h2 { margin: 0; font-size: var(--text-md); font-weight: 650; color: var(--ink); }
+.sw-panel-h .count { font-size: var(--text-2xs); color: var(--ink-faint); }
+.sw-panel-body { max-height: 420px; overflow-y: auto; }
+
+.sw-row { display: flex; align-items: center; gap: var(--space-sm); padding: var(--space-xs) var(--space-md); border-bottom: 1px solid var(--surface-1); font-size: var(--text-sm); }
+.sw-row:last-child { border-bottom: 0; }
+.sw-row .grow { flex: 1; min-width: 0; }
+.sw-row .mono { font-variant-numeric: tabular-nums; }
+.sw-row .muted { color: var(--ink-dim); }
+.sw-row .name { color: var(--ink-bright); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.sw-bar { height: 5px; border-radius: var(--radius-pill); background: var(--surface-3); overflow: hidden; margin-top: 3px; }
+.sw-bar > span { display: block; height: 100%; background: var(--wallet-accent-strong); border-radius: inherit; }
+
+.sw-vote { padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--surface-1); font-size: var(--text-sm); }
+.sw-vote:last-child { border-bottom: 0; }
+.sw-vote-top { display: flex; align-items: center; gap: var(--space-xs); }
+.sw-vote .verdict { font-size: var(--text-2xs); font-weight: 700; text-transform: uppercase; padding: 1px 6px; border-radius: var(--radius-pill); }
+.sw-vote .verdict.fire { color: var(--success); background: rgba(74, 222, 128, 0.1); }
+.sw-vote .verdict.skip { color: var(--ink-dim); background: var(--surface-2); }
+.sw-vote .mint { font-family: var(--font-mono, monospace); font-size: var(--text-2xs); color: var(--ink-dim); }
+.sw-vote .meter { display: flex; align-items: center; gap: var(--space-xs); margin-top: var(--space-2xs); }
+.sw-meter-track { flex: 1; height: 6px; border-radius: var(--radius-pill); background: var(--surface-3); position: relative; overflow: hidden; }
+.sw-meter-fill { position: absolute; inset: 0 auto 0 0; background: linear-gradient(90deg, var(--wallet-accent), var(--wallet-accent-strong)); border-radius: inherit; }
+.sw-meter-thresh { position: absolute; top: -2px; bottom: -2px; width: 2px; background: var(--ink-bright); opacity: 0.8; }
+.sw-vote .reason { color: var(--ink-faint); font-size: var(--text-2xs); margin-top: 2px; }
+
+/* ── disclosure ───────────────────────────────────────────────────────────── */
+.sw-disclose {
+ border: 1px solid rgba(251, 191, 36, 0.3);
+ background: rgba(251, 191, 36, 0.06);
+ border-radius: var(--radius-md);
+ padding: var(--space-sm) var(--space-md);
+ font-size: var(--text-sm);
+ color: var(--ink-dim);
+ line-height: 1.5;
+ margin-bottom: var(--space-md);
+}
+.sw-disclose strong { color: var(--warn); }
+
+/* ── modal ────────────────────────────────────────────────────────────────── */
+.sw-scrim { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(var(--blur-md)); display: flex; align-items: center; justify-content: center; padding: var(--space-md); z-index: 90; animation: swFade var(--duration-fast) var(--ease-standard); }
+@keyframes swFade { from { opacity: 0; } to { opacity: 1; } }
+.sw-modal { width: 100%; max-width: 520px; max-height: 90vh; overflow-y: auto; border: 1px solid var(--stroke-strong); border-radius: var(--radius-lg); background: var(--surface-glass); backdrop-filter: blur(var(--blur-lg)); box-shadow: var(--shadow-3); padding: var(--space-lg); }
+.sw-modal h2 { margin: 0 0 var(--space-xs); font-size: var(--text-lg); color: var(--ink-bright); }
+.sw-modal .sub { color: var(--ink-dim); font-size: var(--text-sm); margin: 0 0 var(--space-md); line-height: 1.45; }
+.sw-field { display: flex; flex-direction: column; gap: var(--space-3xs); margin-bottom: var(--space-sm); }
+.sw-field label { font-size: var(--text-sm); color: var(--ink); font-weight: 600; }
+.sw-field .hint { font-size: var(--text-2xs); color: var(--ink-faint); }
+.sw-field input, .sw-field select, .sw-field textarea {
+ font: inherit; font-size: var(--text-md); padding: var(--space-xs) var(--space-sm);
+ background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); color: var(--ink);
+}
+.sw-field input:focus, .sw-field select:focus, .sw-field textarea:focus { outline: none; border-color: var(--wallet-accent); }
+.sw-grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-sm); }
+.sw-modal-actions { display: flex; justify-content: flex-end; gap: var(--space-sm); margin-top: var(--space-md); }
+.sw-modal-err { color: var(--danger); font-size: var(--text-sm); margin-top: var(--space-xs); min-height: 1.2em; }
+
+/* ── states ───────────────────────────────────────────────────────────────── */
+.sw-msg { text-align: center; padding: var(--space-2xl) var(--space-md); color: var(--ink-dim); }
+.sw-msg h3 { color: var(--ink); font-size: var(--text-lg); margin: 0 0 var(--space-xs); }
+.sw-msg p { margin: 0 auto var(--space-md); max-width: 44ch; line-height: 1.5; }
+.sw-skel { border: 1px solid var(--stroke); border-radius: var(--radius-lg); height: 168px; background: linear-gradient(100deg, var(--surface-1) 30%, var(--surface-3) 50%, var(--surface-1) 70%); background-size: 200% 100%; animation: swShimmer 1.4s ease infinite; }
+@keyframes swShimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+@media (prefers-reduced-motion: reduce) { .sw-skel { animation: none; } .sw-card:hover { transform: none; } }
+
+.sw-toast { position: fixed; bottom: var(--space-lg); left: 50%; transform: translateX(-50%); background: var(--surface-3); border: 1px solid var(--stroke-strong); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); color: var(--ink-bright); font-size: var(--text-sm); box-shadow: var(--shadow-3); z-index: 95; animation: swToast var(--duration-base) var(--ease-emphasized); max-width: 90vw; }
+.sw-toast.err { border-color: rgba(248, 113, 113, 0.5); }
+@keyframes swToast { from { opacity: 0; transform: translate(-50%, 12px); } to { opacity: 1; transform: translate(-50%, 0); } }
diff --git a/src/swarms.js b/src/swarms.js
new file mode 100644
index 000000000..06e29da4f
--- /dev/null
+++ b/src/swarms.js
@@ -0,0 +1,579 @@
+// Trading Swarms — directory + live dashboard.
+//
+// A swarm pools multiple agents' SOL into one custodial treasury that trades on
+// reputation-weighted member consensus and distributes realized profit pro-rata.
+// This module renders the public directory, a per-swarm dashboard with a live SSE
+// feed of consensus votes + payouts, and the create / join / contribute / exit /
+// kill flows — every money action calls a real on-chain endpoint.
+
+const root = document.getElementById('sw-view');
+const SOL = (n) => (n == null ? '—' : `${Number(n).toLocaleString(undefined, { maximumFractionDigits: 4 })} SOL`);
+const PCT = (n) => (n == null ? '—' : `${(Number(n) * 100).toFixed(0)}%`);
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const short = (a) => (a ? `${a.slice(0, 4)}…${a.slice(-4)}` : '');
+
+const state = { network: 'mainnet', agents: null, authed: false };
+
+async function api(path, opts = {}) {
+ const ctrl = new AbortController();
+ const to = setTimeout(() => ctrl.abort(), opts.timeout || 20000);
+ try {
+ const res = await fetch(path, { credentials: 'include', signal: ctrl.signal, ...opts });
+ const data = await res.json().catch(() => null);
+ return { ok: res.ok, status: res.status, data: data?.data ?? data, error: res.ok ? null : data?.message || data?.error || `HTTP ${res.status}` };
+ } catch (e) {
+ return { ok: false, status: 0, data: null, error: e?.name === 'AbortError' ? 'request timed out' : 'network error' };
+ } finally {
+ clearTimeout(to);
+ }
+}
+
+function toast(msg, isErr = false) {
+ const t = document.createElement('div');
+ t.className = 'sw-toast' + (isErr ? ' err' : '');
+ t.textContent = msg;
+ document.body.appendChild(t);
+ setTimeout(() => { t.style.opacity = '0'; t.style.transition = 'opacity .3s'; setTimeout(() => t.remove(), 300); }, isErr ? 5200 : 3400);
+}
+
+async function loadAgents() {
+ if (state.agents) return state.agents;
+ const r = await api('/api/agents');
+ const list = Array.isArray(r.data) ? r.data : Array.isArray(r.data?.agents) ? r.data.agents : [];
+ state.agents = list.map((a) => ({ id: a.id, name: a.name || 'Agent' }));
+ state.authed = r.ok;
+ return state.agents;
+}
+
+// ── router ────────────────────────────────────────────────────────────────────
+
+function currentId() {
+ return new URL(location.href).searchParams.get('id');
+}
+function goto(id) {
+ const u = new URL(location.href);
+ if (id) u.searchParams.set('id', id); else u.searchParams.delete('id');
+ history.pushState({}, '', u);
+ render();
+}
+window.addEventListener('popstate', render);
+
+function render() {
+ const id = currentId();
+ if (id) renderDashboard(id);
+ else renderDirectory();
+}
+
+// ── directory ──────────────────────────────────────────────────────────────────
+
+async function renderDirectory() {
+ root.innerHTML = `
+ <section class="sw-hero">
+ <div>
+ <h1>Trading Swarms</h1>
+ <p>Pool capital with other agents into one auditable on-chain treasury. The swarm only fires when enough of its members' verified track record agrees — and pays realized profit back to every member pro-rata.</p>
+ </div>
+ <div class="sw-hero-actions">
+ <button class="sw-btn sw-btn--primary" id="sw-create">+ Create a swarm</button>
+ </div>
+ </section>
+ <div class="sw-toolbar">
+ <div class="sw-seg" role="tablist" aria-label="Network">
+ <button data-net="mainnet" aria-pressed="${state.network === 'mainnet'}">Mainnet</button>
+ <button data-net="devnet" aria-pressed="${state.network === 'devnet'}">Devnet</button>
+ </div>
+ <button class="sw-btn sw-btn--ghost sw-btn--sm" id="sw-mine">My swarms</button>
+ </div>
+ <div id="sw-list" class="sw-grid" aria-busy="true">${skeletons(6)}</div>`;
+
+ document.getElementById('sw-create').onclick = openCreateModal;
+ root.querySelectorAll('[data-net]').forEach((b) => {
+ b.onclick = () => { state.network = b.dataset.net; renderDirectory(); };
+ });
+ document.getElementById('sw-mine').onclick = () => loadList(true);
+
+ loadList(false);
+}
+
+function skeletons(n) {
+ return Array.from({ length: n }, () => '<div class="sw-skel"></div>').join('');
+}
+
+async function loadList(mine) {
+ const listEl = document.getElementById('sw-list');
+ if (!listEl) return;
+ listEl.setAttribute('aria-busy', 'true');
+ listEl.innerHTML = skeletons(6);
+ const path = mine ? `/api/swarms?mine=1&network=${state.network}` : `/api/swarms?network=${state.network}`;
+ const r = await api(path);
+ listEl.setAttribute('aria-busy', 'false');
+ if (!r.ok && r.status === 401 && mine) {
+ listEl.innerHTML = msg('Sign in to see your swarms', 'Your swarms — ones you created or funded — appear here once you sign in.');
+ return;
+ }
+ if (!r.ok) {
+ listEl.innerHTML = msg('Couldn’t load swarms', esc(r.error || 'Something went wrong.'), 'Retry', () => loadList(mine));
+ return;
+ }
+ const swarms = Array.isArray(r.data) ? r.data : [];
+ if (!swarms.length) {
+ listEl.innerHTML = mine
+ ? msg('No swarms yet', 'You haven’t created or joined a swarm. Start one and invite agents to pool capital.', 'Create a swarm', openCreateModal)
+ : msg('No open swarms yet', 'Be the first — create a swarm, set its consensus policy, and invite other agents to fund the treasury.', 'Create a swarm', openCreateModal);
+ return;
+ }
+ listEl.innerHTML = swarms.map(cardHTML).join('');
+ listEl.querySelectorAll('[data-swarm]').forEach((c) => {
+ c.onclick = () => goto(c.dataset.swarm);
+ c.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); goto(c.dataset.swarm); } };
+ });
+}
+
+function statusPill(s) {
+ const cls = { active: 'active', paused: 'paused', killed: 'killed', open: 'open', closed: 'killed' }[s] || '';
+ const label = { open: 'Funding', active: 'Live', paused: 'Paused', killed: 'Killed', closed: 'Closed' }[s] || s;
+ return `<span class="sw-pill sw-pill--${cls}">${esc(label)}</span>`;
+}
+
+function cardHTML(s) {
+ const pnlCls = s.realized_pnl_sol > 0 ? 'pos' : s.realized_pnl_sol < 0 ? 'neg' : '';
+ const wr = s.win_rate == null ? '—' : `${Math.round(s.win_rate * 100)}%`;
+ return `
+ <a class="sw-card" tabindex="0" role="button" data-swarm="${esc(s.id)}" aria-label="Open ${esc(s.name)}">
+ <div class="sw-card-top">
+ <h3 class="sw-card-name">${esc(s.name)}</h3>
+ ${statusPill(s.status)}
+ </div>
+ ${s.description ? `<p class="sw-card-desc">${esc(s.description)}</p>` : ''}
+ <div class="sw-stats">
+ <div class="sw-stat"><span class="sw-stat-v">${s.members}</span><span class="sw-stat-l">Members</span></div>
+ <div class="sw-stat"><span class="sw-stat-v">${SOL(s.contributed_sol)}</span><span class="sw-stat-l">Pooled</span></div>
+ <div class="sw-stat"><span class="sw-stat-v ${pnlCls}">${s.realized_pnl_sol >= 0 ? '+' : ''}${SOL(s.realized_pnl_sol)}</span><span class="sw-stat-l">Realized P&amp;L</span></div>
+ <div class="sw-stat"><span class="sw-stat-v">${s.closed_trades}</span><span class="sw-stat-l">Closed</span></div>
+ <div class="sw-stat"><span class="sw-stat-v">${wr}</span><span class="sw-stat-l">Win rate</span></div>
+ <div class="sw-stat"><span class="sw-stat-v">${PCT(s.policy?.min_consensus)}</span><span class="sw-stat-l">Min consensus</span></div>
+ </div>
+ </a>`;
+}
+
+function msg(title, body, action, onAction) {
+ const id = 'm' + Math.random().toString(36).slice(2);
+ queueMicrotask(() => { const b = document.getElementById(id); if (b && onAction) b.onclick = onAction; });
+ return `<div class="sw-msg" style="grid-column:1/-1"><h3>${esc(title)}</h3><p>${body}</p>${action ? `<button class="sw-btn sw-btn--primary" id="${id}">${esc(action)}</button>` : ''}</div>`;
+}
+
+// ── dashboard ──────────────────────────────────────────────────────────────────
+
+let activeStream = null;
+
+function closeStream() {
+ if (activeStream) { try { activeStream.close(); } catch {} activeStream = null; }
+}
+
+async function renderDashboard(id) {
+ closeStream();
+ root.innerHTML = `<a class="sw-back" id="sw-back" href="/swarms">← All swarms</a><div id="sw-dash" aria-busy="true">${skeletons(3)}</div>`;
+ document.getElementById('sw-back').onclick = (e) => { e.preventDefault(); goto(null); };
+
+ const r = await api(`/api/swarms/${id}`);
+ const dash = document.getElementById('sw-dash');
+ if (!dash) return;
+ dash.setAttribute('aria-busy', 'false');
+ if (!r.ok) {
+ dash.innerHTML = msg('Swarm not found', esc(r.error || 'This swarm doesn’t exist or was removed.'), 'Back to directory', () => goto(null));
+ return;
+ }
+ paintDashboard(dash, r.data);
+ subscribeStream(id);
+}
+
+function paintDashboard(dash, s) {
+ const sw = s.swarm;
+ const pol = s.policy;
+ const tr = s.treasury;
+ const rec = s.track_record;
+ const member = s.viewer_member;
+ const pnlCls = rec.realized_pnl_sol > 0 ? 'pos' : rec.realized_pnl_sol < 0 ? 'neg' : '';
+
+ dash.innerHTML = `
+ <div class="sw-dash-head">
+ <div>
+ <h1>${esc(sw.name)} ${statusPill(sw.status)}</h1>
+ ${sw.description ? `<p class="muted" style="color:var(--ink-dim);max-width:60ch;margin:.2rem 0 0">${esc(sw.description)}</p>` : ''}
+ ${sw.status === 'killed' && sw.kill_reason ? `<p style="color:var(--danger);font-size:var(--text-sm);margin:.4rem 0 0">Killed: ${esc(sw.kill_reason)}</p>` : ''}
+ </div>
+ <div class="sw-live" id="sw-livedot" data-state="connecting"><span class="dot"></span><span id="sw-livetxt">connecting</span></div>
+ </div>
+
+ <div class="sw-disclose">
+ <strong>Real money, real risk.</strong> The treasury holds real SOL and trades autonomously on member consensus — you can lose your entire contribution. Profit on each closed trade is split pro-rata by share${pol.creator_fee_bps ? `, after a ${(pol.creator_fee_bps / 100).toFixed(1)}% creator fee` : ' (no creator fee)'}. Exit policy: <strong>${pol.exit_policy === 'wait_to_close' ? 'wait-to-close' : 'settle-at-mark'}</strong> — ${pol.exit_policy === 'wait_to_close' ? 'you can redeem only when no positions are open.' : 'on exit you redeem your share of the treasury’s liquid SOL at current value.'} No member can hold more than ${(pol.max_member_share_bps / 100).toFixed(0)}% of the treasury.
+ </div>
+
+ <div class="sw-tiles">
+ <div class="sw-tile"><div class="sw-tile-v" id="sw-bal">${tr.balance_sol == null ? '—' : SOL(tr.balance_sol)}</div><div class="sw-tile-l">Treasury (on-chain)</div><a href="${esc(tr.explorer)}" target="_blank" rel="noopener">${short(tr.address)} ↗</a></div>
+ <div class="sw-tile"><div class="sw-tile-v">${SOL(tr.net_contributed_sol)}</div><div class="sw-tile-l">Net contributed</div></div>
+ <div class="sw-tile"><div class="sw-tile-v ${pnlCls}" id="sw-pnl">${rec.realized_pnl_sol >= 0 ? '+' : ''}${SOL(rec.realized_pnl_sol)}</div><div class="sw-tile-l">Realized P&amp;L</div></div>
+ <div class="sw-tile"><div class="sw-tile-v" id="sw-open">${rec.open_positions}</div><div class="sw-tile-l">Open positions</div></div>
+ <div class="sw-tile"><div class="sw-tile-v">${rec.win_rate == null ? '—' : Math.round(rec.win_rate * 100) + '%'}</div><div class="sw-tile-l">Win rate · ${rec.closed_trades} closed</div></div>
+ </div>
+
+ <div class="sw-hero-actions" id="sw-actions" style="margin-bottom:var(--space-lg);flex-wrap:wrap"></div>
+
+ <div class="sw-cols">
+ <div>
+ ${panel('Members & shares', s.members.length, membersHTML(s.members))}
+ ${panel('Open & closed positions', s.positions.length, positionsHTML(s.positions))}
+ </div>
+ <div>
+ ${panel('Consensus vote log', s.votes.length, votesHTML(s.votes), 'sw-votes')}
+ ${panel('Pro-rata payout ledger', s.payouts.length, payoutsHTML(s.payouts), 'sw-payouts')}
+ </div>
+ </div>`;
+
+ renderActions(s);
+}
+
+function panel(title, count, body, bodyId) {
+ return `<div class="sw-panel"><div class="sw-panel-h"><h2>${esc(title)}</h2><span class="count">${count}</span></div><div class="sw-panel-body"${bodyId ? ` id="${bodyId}"` : ''}>${body}</div></div>`;
+}
+
+function membersHTML(members) {
+ if (!members.length) return emptyRow('No members yet.');
+ return members.map((m) => `
+ <div class="sw-row">
+ <div class="grow">
+ <div class="name">${esc(m.name)}${m.is_creator ? ' <span class="sw-pill" style="font-size:9px">creator</span>' : ''}</div>
+ <div class="sw-bar"><span style="width:${Math.min(100, (m.share_bps || 0) / 100)}%"></span></div>
+ </div>
+ <div style="text-align:right">
+ <div class="mono name">${(m.share_bps / 100).toFixed(1)}%</div>
+ <div class="muted mono" style="font-size:var(--text-2xs)">${SOL(m.contribution_sol)} · rep ${m.reputation == null ? '—' : Math.round(m.reputation)}</div>
+ </div>
+ </div>`).join('');
+}
+
+function positionsHTML(positions) {
+ if (!positions.length) return emptyRow('No trades yet — the treasury fires when member consensus clears.');
+ return positions.map((p) => {
+ const closed = p.status === 'closed';
+ const pnl = p.pnl_sol;
+ const cls = pnl > 0 ? 'pos' : pnl < 0 ? 'neg' : '';
+ const link = (closed ? p.sell_url : p.buy_url);
+ return `<div class="sw-row">
+ <div class="grow"><span class="name">${esc(p.symbol || short(p.mint))}</span> <span class="muted" style="font-size:var(--text-2xs)">${closed ? esc(p.exit_reason || 'closed') : p.status}</span></div>
+ <div class="mono" style="text-align:right">${closed ? `<span class="${cls}">${pnl >= 0 ? '+' : ''}${SOL(pnl)}</span>` : `<span class="muted">${SOL(p.current_sol)}</span>`}${link ? ` <a href="${esc(link)}" target="_blank" rel="noopener" class="muted">↗</a>` : ''}</div>
+ </div>`;
+ }).join('');
+}
+
+function voteRowHTML(v) {
+ const pct = Math.min(100, (v.consensus || 0) * 100);
+ const thr = Math.min(100, (v.min_consensus || 0) * 100);
+ return `<div class="sw-vote">
+ <div class="sw-vote-top">
+ <span class="verdict ${v.decision}">${v.decision === 'fire' ? '✓ fire' : 'skip'}</span>
+ <span class="name grow">${esc(v.mint ? short(v.mint) : '')}</span>
+ <span class="muted mono" style="font-size:var(--text-2xs)">${v.members_long}/${v.members_total} long</span>
+ </div>
+ <div class="meter">
+ <div class="sw-meter-track"><div class="sw-meter-fill" style="width:${pct}%"></div><div class="sw-meter-thresh" style="left:${thr}%"></div></div>
+ <span class="mono muted" style="font-size:var(--text-2xs)">${Math.round(pct)}%</span>
+ </div>
+ <div class="reason">${esc(v.reason || '')}${v.smart_money_score ? ` · smart-money ${Math.round(v.smart_money_score)}` : ''}${v.size_sol ? ` · sized ${SOL(v.size_sol)}` : ''}</div>
+ </div>`;
+}
+
+function votesHTML(votes) {
+ if (!votes.length) return emptyRow('No consensus decisions yet. Each evaluation — fire or skip — logs here with the full weighted vote.');
+ return votes.map(voteRowHTML).join('');
+}
+
+function payoutRowHTML(p) {
+ const kindLabel = { profit: 'Profit', exit: 'Exit', fee: 'Creator fee' }[p.kind] || p.kind;
+ const stCls = p.status === 'confirmed' ? 'pos' : p.status === 'failed' ? 'neg' : 'muted';
+ return `<div class="sw-row">
+ <div class="grow"><span class="name">${esc(kindLabel)}</span> <span class="muted" style="font-size:var(--text-2xs)">${p.share_bps != null ? (p.share_bps / 100).toFixed(1) + '%' : ''}</span></div>
+ <div class="mono" style="text-align:right"><span class="${p.kind === 'fee' ? 'muted' : 'pos'}">${SOL(p.amount_sol)}</span> <span class="${stCls}" style="font-size:var(--text-2xs)">${p.status}</span>${p.tx_url ? ` <a href="${esc(p.tx_url)}" target="_blank" rel="noopener" class="muted">↗</a>` : ''}</div>
+ </div>`;
+}
+
+function payoutsHTML(payouts) {
+ if (!payouts.length) return emptyRow('No payouts yet. When a position closes in profit, each member’s pro-rata share is sent on-chain and listed here.');
+ return payouts.map(payoutRowHTML).join('');
+}
+
+function emptyRow(text) {
+ return `<div class="sw-row" style="color:var(--ink-dim);justify-content:center;padding:var(--space-lg);text-align:center;font-size:var(--text-sm)">${esc(text)}</div>`;
+}
+
+// ── actions ────────────────────────────────────────────────────────────────────
+
+async function renderActions(s) {
+ const el = document.getElementById('sw-actions');
+ if (!el) return;
+ await loadAgents();
+ const sw = s.swarm;
+ const member = s.viewer_member;
+ const isOwner = s.is_owner;
+ const killable = sw.status !== 'killed' && sw.status !== 'closed';
+
+ const btns = [];
+ if (killable && !member) btns.push(`<button class="sw-btn sw-btn--primary" data-act="join">Join & contribute</button>`);
+ if (killable && member) {
+ btns.push(`<button class="sw-btn sw-btn--primary" data-act="contribute">Add SOL</button>`);
+ btns.push(`<button class="sw-btn" data-act="exit">Exit & redeem</button>`);
+ }
+ if (isOwner && killable) {
+ btns.push(`<button class="sw-btn sw-btn--ghost sw-btn--sm" data-act="${sw.status === 'paused' ? 'resume' : 'pause'}">${sw.status === 'paused' ? 'Resume' : 'Pause'}</button>`);
+ }
+ if (killable) btns.push(`<button class="sw-btn sw-btn--danger sw-btn--sm" data-act="kill">Kill switch</button>`);
+
+ el.innerHTML = btns.join('') || `<span class="muted" style="color:var(--ink-dim);font-size:var(--text-sm)">This swarm is closed.</span>`;
+ el.querySelectorAll('[data-act]').forEach((b) => {
+ b.onclick = () => handleAction(b.dataset.act, s);
+ });
+}
+
+function handleAction(act, s) {
+ if (!state.authed || !state.agents?.length) {
+ toast('Sign in and create an agent first', true);
+ return;
+ }
+ if (act === 'join' || act === 'contribute') return openContributeModal(s, act);
+ if (act === 'exit') return openExitModal(s);
+ if (act === 'kill') return openKillModal(s);
+ if (act === 'pause' || act === 'resume') return doSimpleAction(act, s.swarm.id);
+}
+
+async function doSimpleAction(action, swarmId, extra = {}) {
+ const r = await api('/api/swarms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ action, swarm_id: swarmId, ...extra }) });
+ if (!r.ok) { toast(r.error || 'Action failed', true); return false; }
+ toast(`Done`);
+ renderDashboard(swarmId);
+ return true;
+}
+
+// ── modals ─────────────────────────────────────────────────────────────────────
+
+function modal(html) {
+ const scrim = document.createElement('div');
+ scrim.className = 'sw-scrim';
+ scrim.innerHTML = `<div class="sw-modal" role="dialog" aria-modal="true">${html}</div>`;
+ document.body.appendChild(scrim);
+ scrim.addEventListener('click', (e) => { if (e.target === scrim) close(); });
+ const close = () => { scrim.remove(); document.removeEventListener('keydown', onKey); };
+ const onKey = (e) => { if (e.key === 'Escape') close(); };
+ document.addEventListener('keydown', onKey);
+ return { scrim, close };
+}
+
+function agentOptions(selectedFirst = true) {
+ return (state.agents || []).map((a) => `<option value="${esc(a.id)}">${esc(a.name)}</option>`).join('');
+}
+
+async function openCreateModal() {
+ await loadAgents();
+ if (!state.authed) { toast('Sign in to create a swarm', true); return; }
+ if (!state.agents.length) { toast('Create an agent first', true); return; }
+ const { close } = modal(`
+ <h2>Create a trading swarm</h2>
+ <p class="sub">A dedicated custodial treasury wallet is provisioned on-chain. You set the consensus threshold and risk policy; members fund it with real SOL.</p>
+ <div class="sw-field"><label>Swarm name</label><input id="f-name" maxlength="80" placeholder="e.g. Alpha Hunters" /></div>
+ <div class="sw-field"><label>Description <span class="hint">(optional)</span></label><textarea id="f-desc" rows="2" maxlength="1000" placeholder="What does this swarm hunt?"></textarea></div>
+ <div class="sw-field"><label>Owner agent</label><select id="f-owner">${agentOptions()}</select></div>
+ <div class="sw-grid2">
+ <div class="sw-field"><label>Min consensus</label><input id="f-cons" type="number" min="5" max="100" step="5" value="60" /><span class="hint">% of weighted track record that must agree</span></div>
+ <div class="sw-field"><label>Network</label><select id="f-net"><option value="mainnet">Mainnet</option><option value="devnet">Devnet</option></select></div>
+ <div class="sw-field"><label>Max / trade (SOL)</label><input id="f-mpt" type="number" min="0.001" step="0.01" value="0.05" /></div>
+ <div class="sw-field"><label>Daily budget (SOL)</label><input id="f-budget" type="number" min="0.001" step="0.1" value="0.5" /></div>
+ <div class="sw-field"><label>Stop loss (%)</label><input id="f-sl" type="number" min="1" max="95" value="35" /></div>
+ <div class="sw-field"><label>Take profit (%)</label><input id="f-tp" type="number" min="5" value="80" /></div>
+ <div class="sw-field"><label>Creator fee (%)</label><input id="f-fee" type="number" min="0" max="20" step="0.5" value="0" /><span class="hint">on distributed profit</span></div>
+ <div class="sw-field"><label>Max member share (%)</label><input id="f-cap" type="number" min="10" max="100" value="50" /></div>
+ <div class="sw-field"><label>Exit policy</label><select id="f-exit"><option value="settle_at_mark">Settle at mark</option><option value="wait_to_close">Wait to close</option></select></div>
+ <div class="sw-field"><label>Join</label><select id="f-join"><option value="open">Open to anyone</option><option value="invite">Invite-only</option></select></div>
+ </div>
+ <div class="sw-modal-err" id="f-err"></div>
+ <div class="sw-modal-actions">
+ <button class="sw-btn sw-btn--ghost" id="f-cancel">Cancel</button>
+ <button class="sw-btn sw-btn--primary" id="f-go">Create swarm</button>
+ </div>`);
+
+ document.getElementById('f-cancel').onclick = close;
+ const errEl = document.getElementById('f-err');
+ document.getElementById('f-go').onclick = async (e) => {
+ const btn = e.currentTarget;
+ const name = document.getElementById('f-name').value.trim();
+ if (!name) { errEl.textContent = 'Name is required.'; return; }
+ btn.disabled = true; btn.textContent = 'Creating…'; errEl.textContent = '';
+ const policy = {
+ min_consensus: Number(document.getElementById('f-cons').value) / 100,
+ max_per_trade_lamports: Math.round(Number(document.getElementById('f-mpt').value) * 1e9),
+ daily_budget_lamports: Math.round(Number(document.getElementById('f-budget').value) * 1e9),
+ stop_loss_pct: Number(document.getElementById('f-sl').value),
+ take_profit_pct: Number(document.getElementById('f-tp').value),
+ creator_fee_bps: Math.round(Number(document.getElementById('f-fee').value) * 100),
+ max_member_share_bps: Math.round(Number(document.getElementById('f-cap').value) * 100),
+ exit_policy: document.getElementById('f-exit').value,
+ join_open: document.getElementById('f-join').value === 'open',
+ };
+ const r = await api('/api/swarms', {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ action: 'create', name,
+ description: document.getElementById('f-desc').value.trim() || null,
+ owner_agent_id: document.getElementById('f-owner').value,
+ network: document.getElementById('f-net').value, policy,
+ }),
+ });
+ if (!r.ok) { errEl.textContent = r.error || 'Could not create swarm.'; btn.disabled = false; btn.textContent = 'Create swarm'; return; }
+ close();
+ toast('Swarm created — fund the treasury to go live');
+ goto(r.data.swarm.id);
+ };
+}
+
+async function openContributeModal(s, mode) {
+ const sw = s.swarm;
+ const { close } = modal(`
+ <h2>${mode === 'join' ? 'Join' : 'Add to'} ${esc(sw.name)}</h2>
+ <p class="sub">Your agent sends real SOL from its custodial wallet to the swarm treasury. Your share is your net contribution ÷ the total pool, capped at ${(s.policy.max_member_share_bps / 100).toFixed(0)}%. You can exit and redeem any time.</p>
+ <div class="sw-field"><label>Your agent</label><select id="c-agent">${agentOptions()}</select></div>
+ <div class="sw-field"><label>Amount (SOL)</label><input id="c-amt" type="number" min="0.005" step="0.01" value="0.05" /><span class="hint">minimum 0.005 SOL</span></div>
+ <div class="sw-modal-err" id="c-err"></div>
+ <div class="sw-modal-actions">
+ <button class="sw-btn sw-btn--ghost" id="c-cancel">Cancel</button>
+ <button class="sw-btn sw-btn--primary" id="c-go">Send ${mode === 'join' ? '& join' : ''}</button>
+ </div>`);
+ document.getElementById('c-cancel').onclick = close;
+ const errEl = document.getElementById('c-err');
+ document.getElementById('c-go').onclick = async (e) => {
+ const btn = e.currentTarget;
+ const agentId = document.getElementById('c-agent').value;
+ const sol = Number(document.getElementById('c-amt').value);
+ if (!(sol > 0)) { errEl.textContent = 'Enter an amount.'; return; }
+ btn.disabled = true; btn.textContent = 'Sending…'; errEl.textContent = '';
+ const r = await api('/api/swarms', {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ action: 'contribute', swarm_id: sw.id, agent_id: agentId, sol }),
+ timeout: 60000,
+ });
+ if (!r.ok) { errEl.textContent = r.error || 'Contribution failed.'; btn.disabled = false; btn.textContent = 'Send'; return; }
+ close();
+ toast(`Contributed ${SOL(sol)} — share updated`);
+ renderDashboard(sw.id);
+ };
+}
+
+async function openExitModal(s) {
+ const sw = s.swarm;
+ const member = s.viewer_member;
+ const { close } = modal(`
+ <h2>Exit ${esc(sw.name)}</h2>
+ <p class="sub">${s.policy.exit_policy === 'wait_to_close'
+ ? 'This swarm redeems exits only when no positions are open. If positions are live, exit will be refused — wait for them to close or trigger the kill switch.'
+ : 'You’ll redeem your share of the treasury’s liquid SOL at current value, sent on-chain to your agent wallet. Open positions stay with the swarm — you forfeit claims on them after exit.'}</p>
+ <div class="sw-field"><label>Your member agent</label><select id="x-agent">${(s.members || []).filter((m) => m.status === 'active').map((m) => `<option value="${esc(m.agent_id)}">${esc(m.name)} · ${(m.share_bps / 100).toFixed(1)}%</option>`).join('') || agentOptions()}</select></div>
+ <div class="sw-modal-err" id="x-err"></div>
+ <div class="sw-modal-actions">
+ <button class="sw-btn sw-btn--ghost" id="x-cancel">Stay in</button>
+ <button class="sw-btn sw-btn--danger" id="x-go">Exit & redeem</button>
+ </div>`);
+ document.getElementById('x-cancel').onclick = close;
+ const errEl = document.getElementById('x-err');
+ document.getElementById('x-go').onclick = async (e) => {
+ const btn = e.currentTarget;
+ btn.disabled = true; btn.textContent = 'Redeeming…'; errEl.textContent = '';
+ const r = await api('/api/swarms', {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ action: 'exit', swarm_id: sw.id, agent_id: document.getElementById('x-agent').value }),
+ timeout: 60000,
+ });
+ if (!r.ok) { errEl.textContent = r.error || 'Exit failed.'; btn.disabled = false; btn.textContent = 'Exit & redeem'; return; }
+ close();
+ toast(`Redeemed ${SOL(r.data.redeemed_sol)}${r.data.capped ? ' (capped to liquid SOL)' : ''}`);
+ renderDashboard(sw.id);
+ };
+}
+
+function openKillModal(s) {
+ const sw = s.swarm;
+ const { close } = modal(`
+ <h2>Trigger the kill switch</h2>
+ <p class="sub">This halts all new consensus trades and forces every open position to liquidate on the next sweep. ${s.is_owner ? 'As the creator you can always kill.' : `You need ≥ ${(s.policy.kill_threshold_bps / 100).toFixed(0)}% of the treasury to kill.`} This cannot be undone.</p>
+ <div class="sw-field"><label>Reason <span class="hint">(optional)</span></label><input id="k-reason" maxlength="280" placeholder="Why are you killing this swarm?" /></div>
+ <div class="sw-modal-err" id="k-err"></div>
+ <div class="sw-modal-actions">
+ <button class="sw-btn sw-btn--ghost" id="k-cancel">Cancel</button>
+ <button class="sw-btn sw-btn--danger" id="k-go">Kill swarm</button>
+ </div>`);
+ document.getElementById('k-cancel').onclick = close;
+ const errEl = document.getElementById('k-err');
+ document.getElementById('k-go').onclick = async (e) => {
+ const btn = e.currentTarget;
+ btn.disabled = true; btn.textContent = 'Killing…'; errEl.textContent = '';
+ const r = await api('/api/swarms', {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ action: 'kill', swarm_id: sw.id, reason: document.getElementById('k-reason').value.trim() || null }),
+ });
+ if (!r.ok) { errEl.textContent = r.error || 'Kill failed.'; btn.disabled = false; btn.textContent = 'Kill swarm'; return; }
+ close();
+ toast('Swarm killed — positions liquidating');
+ renderDashboard(sw.id);
+ };
+}
+
+// ── live stream ────────────────────────────────────────────────────────────────
+
+function subscribeStream(id) {
+ if (typeof window.EventSource !== 'function') return;
+ let fails = 0;
+ const dot = () => document.getElementById('sw-livedot');
+ const setLive = (state, txt) => { const d = dot(); if (d) { d.dataset.state = state; const t = document.getElementById('sw-livetxt'); if (t) t.textContent = txt; } };
+
+ const connect = () => {
+ closeStream();
+ let es;
+ try { es = new EventSource(`/api/swarms/${id}/stream`); } catch { return; }
+ activeStream = es;
+ es.addEventListener('hello', () => { fails = 0; setLive('live', 'live'); });
+ es.addEventListener('vote', (e) => {
+ try {
+ const v = JSON.parse(e.data);
+ const box = document.getElementById('sw-votes');
+ if (box) { if (box.querySelector('.sw-msg, .sw-row')) box.innerHTML = ''; box.insertAdjacentHTML('afterbegin', voteRowHTML(v)); flash(box.firstElementChild); }
+ if (v.decision === 'fire') toast(`Consensus fired · ${short(v.mint)}`);
+ } catch {}
+ });
+ es.addEventListener('payout', (e) => {
+ try {
+ const p = JSON.parse(e.data);
+ const box = document.getElementById('sw-payouts');
+ if (box) { if (box.querySelector('.sw-msg, .sw-row[style]')) box.innerHTML = ''; box.insertAdjacentHTML('afterbegin', payoutRowHTML({ ...p, amount_sol: p.amount_sol })); flash(box.firstElementChild); }
+ } catch {}
+ });
+ es.addEventListener('tick', (e) => {
+ try {
+ const t = JSON.parse(e.data);
+ const bal = document.getElementById('sw-bal'); if (bal && t.balance_sol != null) bal.textContent = SOL(t.balance_sol);
+ const op = document.getElementById('sw-open'); if (op) op.textContent = t.open_positions;
+ const pnl = document.getElementById('sw-pnl'); if (pnl) { pnl.textContent = `${t.realized_pnl_sol >= 0 ? '+' : ''}${SOL(t.realized_pnl_sol)}`; pnl.className = 'sw-tile-v ' + (t.realized_pnl_sol > 0 ? 'pos' : t.realized_pnl_sol < 0 ? 'neg' : ''); }
+ } catch {}
+ });
+ es.onerror = () => { fails++; setLive('connecting', 'reconnecting'); try { es.close(); } catch {} activeStream = null; setTimeout(connect, Math.min(20000, 1000 * 2 ** fails)); };
+ };
+ connect();
+}
+
+function flash(el) {
+ if (!el) return;
+ el.style.background = 'var(--surface-3)';
+ el.style.transition = 'background 1.2s ease';
+ requestAnimationFrame(() => { el.style.background = ''; });
+}
+
+window.addEventListener('beforeunload', closeStream);
+
+// ── boot ────────────────────────────────────────────────────────────────────────
+
+loadAgents().finally(render);
diff --git a/tasks/next-gen-trading/04-prelaunch-creator-radar.md b/tasks/next-gen-trading/04-prelaunch-creator-radar.md
deleted file mode 100644
index 2ea381b62..000000000
--- a/tasks/next-gen-trading/04-prelaunch-creator-radar.md
+++ /dev/null
@@ -1,100 +0,0 @@
-# Task 04 — Pre-Launch Creator-Wallet Radar (block-zero pre-cog sniping)
-
-> **Operating bar (applies to the whole task).** Senior engineer + product thinker building
-> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no
-> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%
-> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**
-> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade
-> plumbing are the only exception and are never promoted. After it works, self-review and ship
-> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the
-> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.
->
-> **Depends on task 03 (smart-money graph).** Use its wallet reputation as the watchlist source.
-
-## The invention
-
-Everyone snipes *after* a coin appears in the PumpPortal feed — by then thousands of bots see
-it too. We go earlier: **watch the wallets of creators who have repeatedly graduated coins, and
-the smart-money wallets from task 03, in real time.** When a watched wallet funds a fresh wallet
-that then deploys a mint — or itself prepares a launch — we detect it at or before block-0 and
-pre-arm the snipe so our agent is first, legitimately, on signal rather than on luck. This is
-"pre-cog": acting on the on-chain *precursor* to a launch, not the launch event.
-
-## Context (real, verified)
-
-- Creator history already enriched per mint: `api/_lib/pumpfun-ws-feed.js#enrichMint`
- (`creator_launches`, `creator_graduated`, via `frontend-api-v3.pump.fun/coins/user-created-coins/`).
-- Funder edges + outcomes: `pump_coin_wallets.funder`, `pump_coin_outcomes` (task 03 turns these
- into `wallet_reputation`). The pump.fun program id and claim-scan RPC plumbing already exist:
- `api/_lib/pump-claims.js` (`scanFirstClaims`, program `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`).
-- Live feed + worker loop to extend: `workers/agent-sniper/index.js`, `first-claim-watch.js`
- (the existing pattern for a parallel watcher with its own poll cadence + dedupe set).
-- RPC: `api/_lib/solana/connection.js`; Helius (`HELIUS_API_KEY`) supports address-activity
- webhooks / `getSignaturesForAddress` for real-time wallet monitoring.
-- Pre-arm execution reuses `executor.js#executeBuy`, the firewall (task 01), and the MEV engine
- (task 02).
-
-## Goal
-
-A `workers/agent-sniper/prelaunch-radar.js` watcher that maintains a live, auto-curated watchlist
-of high-signal creator + smart-money wallets, detects launch precursors on-chain, and pre-arms a
-snipe through the existing executor — with a strategy trigger `prelaunch_radar` and full audit.
-
-## What to build
-
-1. **Watchlist builder** — derive the watched set from (a) creators with `creator_graduated >= N`
- (configurable) seen in recent feed history, and (b) top `wallet_reputation` addresses (task 03),
- excluding sybil clusters. Persist to a `radar_watchlist` table (address, reason, score,
- network, added_at, last_hit_at) and refresh on an interval. Cap the set; evict stale low-signal
- wallets.
-2. **Precursor detection** — monitor watched wallets in real time (Helius address webhook if
- configured, else polled `getSignaturesForAddress` with backoff). Detect two precursors:
- (a) a watched wallet **funds a brand-new wallet** that has no history (likely a fresh deploy
- wallet), and (b) a watched wallet **submits a pump.fun create instruction**. Correlate the
- resulting mint as soon as it lands and emit a `radar_event { trigger_wallet, new_wallet?, mint,
- confidence, ts }`. Dedupe via an in-process set like `first-claim-watch.js`.
-3. **Pre-arm + fire** — for each agent strategy with `trigger='prelaunch_radar'`, score the event
- (creator pedigree + smart-money + task-01 firewall the instant the mint exists), and if it
- passes, schedule `executeBuy` through the MEV engine with the strategy's size — racing to be in
- the first block. All spend guards, kill switch, and custody audit apply unchanged.
-4. **Schema** — add `trigger='prelaunch_radar'` support + radar-specific gates to
- `agent_sniper_strategies` (`min_creator_graduated_radar`, `require_smart_money_funder`,
- `radar_max_age_ms`). New `radar_watchlist` + `radar_events` tables via dated migration.
-5. **API + UI** — `GET /api/sniper/radar?network=…` (owner: their armed radar; public: anonymized
- live precursor stream count) and an SSE feed mirroring `api/sniper/stream.js`. Build a **Radar**
- view: live precursor events with confidence, which watched wallet triggered, and (for the owner)
- whether their agent fired. A "watchlist" panel showing why each wallet is watched. All states
- designed; empty state explains the radar is learning.
-
-## Constraints
-
-- Detection must be from **real on-chain reads** — real funding txs, real create instructions.
- Never fabricate a precursor or a confidence. If the webhook/RPC is unavailable, degrade to the
- normal feed-based snipe and report the radar as paused, honestly.
-- This is signal-based first-mover advantage, not exploitation: do not implement anything that
- front-runs another *user's pending transaction* in the mempool. We act on *public on-chain
- precursors* (funding, deploys), not on intercepting victims. Keep it clearly on that side.
-- Latency matters but safety wins: the firewall (task 01) still gates the buy the moment the mint
- is real; never buy a mint that can't be sold just to be first.
-- $THREE-only; synthetic placeholder addresses/mints in fixtures.
-
-## Success criteria
-
-- `radar_watchlist` auto-curates from real creator + smart-money data; precursors detected from
- real chain activity populate `radar_events`.
-- A `prelaunch_radar` strategy pre-arms and fires through the firewall + MEV engine with full
- spend-guard + custody audit coverage.
-- Radar UI + SSE render with all states. Build/typecheck/test clean. Changelog entry (tags:
- feature). Completionist passes.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-```bash
-git rm "tasks/next-gen-trading/04-prelaunch-creator-radar.md"
-```
-
-A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/01-conversational-trading-copilot.md b/tasks/trading-frontier/01-conversational-trading-copilot.md
deleted file mode 100644
index 48cf8f2b2..000000000
--- a/tasks/trading-frontier/01-conversational-trading-copilot.md
+++ /dev/null
@@ -1,90 +0,0 @@
-# Task 01 — Conversational Trading Copilot (voice + chat, in-world execution)
-
-> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
-> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
-> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
-> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
-> in generic trade plumbing are the only exception and are never promoted.
-
-## ⛓ Chain protocol — do this as STEP 0, before building
-
-This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
-build the feature below:
-1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
-2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
- three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
-3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
- structure exactly — including this Chain protocol section, so the chain continues.
-4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
-5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
- this file in the completion commit.
-
-## The invention
-
-three.ws agents are 3D characters with voices and personas. Make the agent a **conversational
-trading copilot**: the user talks (text or voice) — "what's the safest new launch right now?",
-"buy me 0.5 SOL of the one smart money is in, take profit at 2x", "how's my position?" — and the
-agent answers with real data and *executes real trades* through the guarded paths, narrating what
-it did and why. A trading terminal you can simply talk to, in-world. Nobody has that.
-
-## Context (real, verified)
-
-- Agent persona + voice: `agent_identities` (`persona_prompt`, `voice_provider`, `voice_id`,
- `voice_settings`); LLM access via the platform's existing worker proxy (CLAUDE.md: OpenAI/
- Anthropic via worker proxies — use it; no browser-side keys).
-- Trade execution (guarded, server-signed): `api/agents/agent-trade.js`, `api/agents/solana-trade.js`;
- spend guards `api/_lib/agent-trade-guards.js`; firewall `tasks/next-gen-trading/01`.
-- Live market context the copilot can cite: intel (`pump_coin_intel`), oracle
- (`oracle_conviction`), positions (`api/sniper/stream.js`), balances (`api/agents/solana-wallet.js`).
-- Chat UI surfaces + SDK: `sdk/src/index.js` (AgentKit panel), agent-detail chat, wallet hub.
-
-## Goal
-
-A tool-calling trading copilot: an LLM with a real **trade/quote/portfolio/intel toolset**, a
-confirm-before-execute safety model, optional voice in/out, surfaced as a conversation that can
-actually trade from the agent wallet.
-
-## What to build
-
-1. **Copilot tool layer** — define a real function/tool schema the LLM calls: `getQuote`,
- `assessSafety` (firewall), `getSmartMoney`, `getPositions`, `getBalance`, `placeBuy`,
- `placeSell`, `setStrategy`. Each maps to the existing guarded endpoints — the LLM never signs;
- it calls server endpoints that enforce spend limits + firewall + custody audit.
-2. **Confirm-before-execute** — any state-changing action (buy/sell/arm) returns a structured
- proposal the user must confirm (UI affirmation or explicit voice "confirm"); express mode after
- first confirm, per-session, never bypassing spend caps. Read-only queries run freely.
-3. **Voice** — optional speech-to-text in + the agent's configured voice out (use the existing
- voice provider config); text-only fully functional without voice.
-4. **Grounded answers** — the copilot cites real numbers (price, impact, safety verdict, smart-
- money count, PnL) pulled live; it never invents figures. If data is unavailable, it says so.
-5. **UI** — a copilot panel (in agent-detail + wallet hub): conversation with streamed responses,
- inline trade-proposal cards (showing quote + firewall verdict + confirm/cancel), voice toggle,
- and a transcript of executed actions linking to Solscan. All states designed; accessible
- (ARIA live regions, keyboard); responsive.
-
-## Constraints
-
-- The LLM proposes; the guarded server endpoints decide. Spend limits, kill switch, and firewall
- are never bypassable by conversation. Every execution is audited in `agent_custody_events`.
-- Real LLM + real market data only — no canned responses, no fake quotes. Honest degradation on
- failures with retry.
-- $THREE-only rule in all copilot copy/examples; runtime mints are trade data only.
-
-## Success criteria
-
-- A user can converse (text + optional voice) and the copilot answers with live data and executes
- a real, confirmed, firewall+spend-guarded trade from the agent wallet, audited.
-- Confirm-before-execute enforced; read-only queries free; data is real and cited.
-- Copilot UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
-- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
-
-```bash
-git rm "tasks/trading-frontier/01-conversational-trading-copilot.md"
-```
-A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/BACKLOG.md b/tasks/trading-frontier/BACKLOG.md
index bab2f7c69..f4b86f8be 100644
--- a/tasks/trading-frontier/BACKLOG.md
+++ b/tasks/trading-frontier/BACKLOG.md
@@ -8,7 +8,6 @@ Format: `- <slug> — <one-line hook> — proposed by <task>`
## Generation 0 (seeds — live in `tasks/trading-frontier/`)
-- 01-conversational-trading-copilot — talk/voice to your agent to trade, explain, manage risk — seed
- 02-programmable-orders-engine — limit/stop/DCA/TWAP/conditional triggers executed by a worker — seed
- 03-portfolio-intelligence-command — unified cross-wallet PnL attribution + risk dashboard — seed
- 04-graduation-predictor — calibrated ML probability a launch graduates, surfaced everywhere — seed
@@ -21,3 +20,36 @@ Format: `- <slug> — <one-line hook> — proposed by <task>`
## Generation 1+ (chained — live in `tasks/trading-frontier/next/`)
<!-- Agents append new prompt lines here. Confirm no duplicate above before adding. -->
+
+- liquidity-exit-router — split a large sell across bonding curve + AMM and micro-slices to minimize realized slippage — proposed by task 02
+- profit-taking-ladder — one action arms a ladder of limit-sell rungs at rising targets that scale out of a position — proposed by task 02
+- oco-bracket-orders — bracket a holding with a take-profit and a stop-loss that automatically cancel each other — proposed by task 02
+- curve-depth-heatmap — live depth/slippage curve for any mint + the optimal trade size before you click — proposed by task 02
+- watchlist-wallet-triggers — add a 'a watched wallet net-bought/sold this coin' signal to conditional orders + a watchlist — proposed by task 02
+- volatility-adaptive-stops — size trailing/stop distances from each coin's realized volatility so stops fit the chart — proposed by task 02
+- auto-compound-vault — auto-route a % of every realized profit back into $THREE or your winners — proposed by task 02
+- paper-trading-sandbox — run any order/strategy in paper mode against live prices and watch hypothetical P&L — proposed by task 02
+- order-health-monitor — surface exactly why each order isn't firing and fix it in one click; auto re-arm policies — proposed by task 02
+- triggered-order-sequences — chain orders by dependency: when one fills, auto-arm the next (entry→bracket, DCA→trail) — proposed by task 02
+
+
+- liquidity-aggregation-router — best-path execution across pump.fun curve, PumpSwap AMM, and Jupiter (single or split) — proposed by task 01
+- dynamic-position-sizing — regime + conviction-weighted automatic trade sizing (vol-target / fractional-Kelly) shared by copilot, orders, snipe — proposed by task 01
+- post-graduation-liquidity-monitor — track AMM pool depth + LP concentration after graduation, alert on LP-whale pulls — proposed by task 01
+- portfolio-hedging-correlation — real-time cross-position correlation matrix + auto-hedge suggestions + correlation-aware exposure caps — proposed by task 01
+- verifiable-onchain-backtest-attestation — publish replayable strategy backtests as Solana + ERC-8004 attestations anyone can verify — proposed by task 01
+- narrative-drift-sentinel — detect creator/narrative pivots + sentiment decay and red-flag launches whose story changed — proposed by task 01
+- gas-fee-forecaster-batcher — real-time Solana priority-fee forecasting + small-order auto-batching for land-rate and fee savings — proposed by task 01
+- agent-skill-reputation-leaderboard — multi-dimensional agent reputation beyond PnL (calibration, Sharpe/drawdown, loss-cutting speed, graduation accuracy) — proposed by task 01
+- creator-series-cross-chain-mint — mint sequel chapters of a creator narrative + a cross-chain creator directory with optional brand licensing — proposed by task 01
+- rug-loss-protection-vault — $THREE-denominated mutual pool that auto-compensates verified rug losses on firewall-cleared trades, settled via x402 — proposed by task 01
+- networth-history-recorder — scheduled net-worth snapshotter → real equity curve, true net-worth drawdown, windowed returns — proposed by task 03
+- exit-liquidity-radar — depth-aware true liquidatable net worth (sell-simulated vs paper value) per holding — proposed by task 03
+- fleet-treasury-console — owner-scoped roll-up of net worth/PnL/exposure/risk across ALL of a user's agents — proposed by task 03
+- dust-sweeper-rent-reclaimer — detect dead/dust SPL accounts + guarded batch closeAccount to reclaim SOL rent — proposed by task 03
+- counterfactual-replay — "held vs sold" held-to-now value on closed positions + a timing-edge score — proposed by task 03
+- token-approval-security-scanner — audit + one-click revoke of the agent wallet's own SPL delegate approvals/authorities — proposed by task 03
+- mev-sandwich-forensics — post-trade detection + SOL-cost quantification of sandwich/front-run extraction against the agent's swaps — proposed by task 03
+- trading-discipline-coach — behavioral pattern engine (disposition effect, revenge/overtrading) + number-backed nudges — proposed by task 03
+- proof-of-holdings-card — opt-in chain-verifiable live net-worth snapshot, share page + OG image + optional on-chain anchor — proposed by task 03
+- drawdown-circuit-breaker — book-level auto-freeze of all trade paths when net-worth/PnL drawdown crosses a threshold — proposed by task 03
diff --git a/tasks/trading-frontier/next/agent-skill-reputation-leaderboard.md b/tasks/trading-frontier/next/agent-skill-reputation-leaderboard.md
new file mode 100644
index 000000000..264c257b0
--- /dev/null
+++ b/tasks/trading-frontier/next/agent-skill-reputation-leaderboard.md
@@ -0,0 +1,93 @@
+# Task — Agent Skill Reputation Leaderboard (multi-dimensional skill, not raw PnL)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+Raw PnL crowns whoever got luckiest with the most capital. The existing sniper leaderboard ranks by
+profit; the arena runs PvP tournaments. Neither measures *skill*. Build a **multi-dimensional agent
+skill reputation**: rank agents on signal calibration (do their conviction calls actually hit?),
+risk-adjusted return (Sharpe, max-drawdown), speed-to-cut-losses (how fast they exit losers), and
+graduation-call accuracy (did the coins they bought pre-graduation actually graduate?). A composite,
+transparent skill score that surfaces genuinely good traders to copy and gives every agent a credible
+on-platform résumé — the foundation for copy-trading and the signal marketplace.
+
+## Context (real, verified)
+
+- Trader metrics: `api/_lib/trader-stats.js` (per-agent realized stats — the base to extend with
+ risk-adjusted and behavioral dimensions).
+- Trade-level data: `agent_sniper_positions` (entries/exits/holds to compute speed-to-cut-losses and
+ drawdown).
+- Outcome truth: `pump_coin_outcomes` (did a bought coin graduate / hit its ATH — the ground truth
+ for graduation-call accuracy and conviction calibration).
+- Existing ranking surface: `api/sniper/leaderboard.js` (the PnL leaderboard to add skill dimensions
+ alongside, not replace).
+
+## Goal
+
+A skill-reputation engine that computes per-agent calibration, risk-adjusted return, loss-cutting
+speed, and graduation-call accuracy, blends them into a transparent composite, and ranks agents by
+skill alongside the existing PnL board.
+
+## What to build
+
+1. **Skill metrics** — extend `api/_lib/trader-stats.js` to compute Sharpe, max-drawdown,
+ median-time-to-exit-losers, conviction calibration (predicted vs. realized via
+ `pump_coin_outcomes`), and graduation-call hit rate.
+2. **Composite + transparency** — a weighted skill score with each component visible and a per-agent
+ breakdown explaining why the score is what it is (no opaque black box).
+3. **Skill leaderboard API** — extend `api/sniper/leaderboard.js` with sortable skill dimensions and
+ filters (timeframe, min sample size to avoid small-sample inflation).
+4. **Profile résumé** — render the skill breakdown on agent profiles as a credible, shareable
+ trading résumé, feeding copy-trade/signal-marketplace surfaces.
+5. **UI** — a skill leaderboard with per-dimension sort, a radar/breakdown per agent, and
+ sample-size confidence badges. All states designed; responsive; accessible.
+6. **Anti-gaming** — minimum-sample gating + drawdown penalty so spray-and-pray and one-lucky-hit
+ agents can't top the skill board.
+
+## Constraints
+
+- This is read/scoring only; any copy-trade or follow action it enables honors spend guards
+ (`api/_lib/agent-trade-guards.js`), custody audit (`agent_custody_events`), and the firewall
+ (`api/_lib/trade-firewall.js`) on buys.
+- $THREE is the only promoted coin; mints in scored trade history are trade data only.
+- No mocks, stubs, or fake stats — real trader-stats, positions, and outcomes only.
+
+## Success criteria
+
+- Reachable in the UI as a skill leaderboard + profile résumé; rankings reflect real, explainable
+ multi-dimensional metrics over real trade history.
+- Real `trader-stats` / `agent_sniper_positions` / `pump_coin_outcomes` data; any enabled trade
+ action is guard-honored and custody-audited.
+- All states designed; responsive at 320/768/1440; accessible (ARIA, keyboard, focus, contrast,
+ reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/agent-skill-reputation-leaderboard.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/auto-compound-vault.md b/tasks/trading-frontier/next/auto-compound-vault.md
new file mode 100644
index 000000000..e4ec77f67
--- /dev/null
+++ b/tasks/trading-frontier/next/auto-compound-vault.md
@@ -0,0 +1,69 @@
+# Auto-Compounding Vault (reinvest realized profits automatically)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+
+## The invention
+
+Profits that sit idle as SOL are dead capital. The Auto-Compounding Vault watches realized gains
+from closed orders/positions and automatically reinvests a configurable share — into $THREE, or
+back into the best-performing open position — through the guarded trade path. Set a compounding
+policy once and the wallet grows its own book.
+
+## Context (real, verified)
+
+- Realized P&L sources: `order_fills` (this engine), `agent_sniper_positions` (`realized_pnl_
+ lamports`), `agent_custody_events` (the spend/settle ledger).
+- Execution: `executeAgentTrade` (`api/agents/agent-trade.js`); spend policy `agent-trade-guards.js`.
+- $THREE is the canonical reinvest target (CA in CLAUDE.md); winners come from open positions.
+
+## Goal
+
+A per-agent compounding policy (trigger: realized profit ≥ X; action: reinvest N% into target),
+a worker step that detects new realized gains and fires the reinvest buy through the guarded
+path, and a vault dashboard showing compounded total + history.
+
+## What to build
+
+1. **Policy model** — `compound_policies` (threshold, pct, target = $THREE | top_winner, caps).
+2. **Detector** — track newly-realized profit from `order_fills`/`agent_sniper_positions` since
+ the last compound; idempotent (never double-count a close).
+3. **Reinvest** — fire the buy via `executeAgentTrade`, firewall + spend-guard gated, audited;
+ record a `compound_events` receipt.
+4. **UI** — vault panel: policy editor, compounded-to-date, event log, all states.
+
+## Constraints
+
+Only reinvests REALIZED, settled profit (never unrealized/paper). Honors daily budget + per-trade
+caps + kill switch. Idempotent. $THREE-only as the default target; runtime mints are data.
+
+## Success criteria
+
+A realized profit triggers a real, guarded reinvest buy, audited and shown in the vault log;
+never double-compounds; kill switch halts it. Chain extended. Build/test clean. Changelog
+(feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/auto-compound-vault.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/counterfactual-replay.md b/tasks/trading-frontier/next/counterfactual-replay.md
new file mode 100644
index 000000000..c5e885fc1
--- /dev/null
+++ b/tasks/trading-frontier/next/counterfactual-replay.md
@@ -0,0 +1,83 @@
+# Task — Counterfactual Replay ("held vs sold" honesty engine)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+A trader's biggest leak is invisible: selling winners too early and bag-holding losers too long.
+Build a **Counterfactual Replay** that, for every *closed* position, computes what the position
+would be worth *now* if it had been held — surfacing "you left X SOL on the table" on premature
+exits and "you saved Y SOL by cutting" on good ones. Aggregate it into an honest **timing-edge**
+score: did the agent's exits, in hindsight, beat or trail simply holding? A mirror that turns the
+agent's own history into a coaching signal — no competitor confronts traders with this truth.
+
+## Context (real, verified)
+
+- Closed positions with entry/exit + on-chain proof: `agent_sniper_positions` via
+ `api/_lib/trader-stats.js` (`fetchTraderPositions`, `shapeClosed`; `mint`, `exit_quote_lamports`,
+ `base_amount`, `realized_pnl_lamports`, `closed_at`, `buy_sig`/`sell_sig`).
+- Live "price now" per mint: `api/_lib/balances.js#solanaMintUsdPrice` + curve quoting
+ `api/_lib/pump.js` (`getSellSolAmountFromTokenAmount`) for what the held base amount would fetch today.
+- SOL/USD: `api/_lib/pumpfun-ws-feed.js#getSolPrice`. Existing metric engine to extend for the
+ timing-edge aggregate: `computeTraderMetrics`.
+
+## Goal
+
+A counterfactual engine (`api/_lib/counterfactual.js`) + `/api/agents/:id/counterfactual` that, per
+closed position, computes held-to-now value and the exit delta, plus a portfolio timing-edge score,
+surfaced as a Replay panel in the wallet hub / trader profile.
+
+## What to build
+
+1. **Per-position replay** — for each closed position, value the original base amount at today's
+ live sell quote, compute `held_now_sol` and `exit_delta_sol` (realized − held-now), tag each as
+ `early_exit` / `well_timed` / `dodged_dump`. Gracefully handle dead mints (held-now = 0 → cutting
+ was correct).
+2. **Timing edge** — aggregate deltas into a 0–100 timing-edge score and plain-language verdict
+ ("your exits beat holding by N SOL over M trades"), survivorship-honest (count the dodged dumps).
+3. **API** — `/api/agents/:id/counterfactual?window=` returns per-position replays + the aggregate;
+ cached; concurrent live re-quoting; honest unpriceable handling.
+4. **UI** — a Replay panel: timing-edge header, a table of closed trades with realized vs held-now
+ vs delta and a tag, sortable by "most left on the table". All states designed (empty for no
+ closed trades); accessible; responsive.
+
+## Constraints
+
+- Every counterfactual uses a real live quote; dead/unpriceable mints handled honestly, never guessed.
+- Read-only reflection; no trades initiated. Survivorship-honest aggregation.
+- $THREE-only rule; runtime mints are trade data only.
+
+## Success criteria
+
+- For real closed positions, the replay shows accurate held-to-now value and exit deltas and an
+ honest timing-edge score with plain-language verdict.
+- Replay UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/counterfactual-replay.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/creator-series-cross-chain-mint.md b/tasks/trading-frontier/next/creator-series-cross-chain-mint.md
new file mode 100644
index 000000000..52b04a7ae
--- /dev/null
+++ b/tasks/trading-frontier/next/creator-series-cross-chain-mint.md
@@ -0,0 +1,95 @@
+# Task — Creator Series & Cross-Chain Mint (sequel chapters + a creator directory)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+A launch on three.ws is a one-shot event today. But the most valuable creators build a *body of
+work* — a recognizable brand across multiple drops. Build **creator series + a cross-chain creator
+directory**: let an agent mint sequel "chapters" of its own creator narrative (explicitly linked as a
+canonical series, so chapter 2 inherits the brand and audience of chapter 1), surface a cross-chain
+directory of every creator's body of work spanning Solana mints and ERC-8004 agent identities, and
+optionally let a creator license its brand to another agent for a series spin-off. It turns
+disposable launches into durable creator franchises — and gives buyers a verified creator lineage to
+trust instead of an anonymous one-off.
+
+## Context (real, verified)
+
+- Launch path: `api/_lib/pump-launch.js` (the existing launch logic to extend with series linkage).
+- Platform launch records: `pump_agent_mints` (the canonical record of coins launched through
+ three.ws — the source for a creator's body of work; a product feature, runtime data only).
+- Multichain primitives: `api/_lib/onchain.js` (the multichain helpers for spanning Solana + EVM).
+- Cross-chain identity: the `erc8004_agents_index` (ERC-8004 agent registry to tie a creator's EVM
+ identity to its Solana launches in the directory).
+
+## Goal
+
+A creator-series capability that links sequential mints into a canonical, verifiable series, a
+cross-chain creator directory rendering each creator's body of work, and an optional brand-licensing
+flow between agents.
+
+## What to build
+
+1. **Series linkage at mint** — extend `api/_lib/pump-launch.js` so a launch can declare itself
+ chapter N of a creator's series, recording the parent/series in `pump_agent_mints` so lineage is
+ canonical and verifiable, not just cosmetic.
+2. **Cross-chain creator directory** — aggregate a creator's body of work from `pump_agent_mints`
+ (Solana) and `erc8004_agents_index` (EVM identity) via `api/_lib/onchain.js`, with per-creator
+ series, outcomes, and verified-lineage badges.
+3. **Brand licensing** — let a creator grant another agent permission to mint an authorized spin-off
+ of its series, recorded on-chain/in the index so the license is verifiable and revocable.
+4. **Directory + series API** — endpoints for the creator directory, a single creator's series, and
+ a license grant/check, all reading real launch + identity records.
+5. **UI** — a creator-directory page + a creator profile showing the series timeline, body of work,
+ licensing controls, and lineage badges; a "mint next chapter" flow from a creator's own profile.
+ All states designed; responsive; accessible.
+6. **Cross-link** — wire lineage badges into launch detail + creator-reputation surfaces so series
+ provenance shows everywhere a coin appears.
+
+## Constraints
+
+- Any buy from the directory honors spend guards (`api/_lib/agent-trade-guards.js`), custody audit
+ (`agent_custody_events`), and the firewall (`api/_lib/trade-firewall.js`); minting honors the
+ existing launch guardrails.
+- $THREE is the only promoted coin; coins in the directory render from real platform launch records
+ (`pump_agent_mints`) as runtime trade data only — never hardcoded, marketed, or recommended.
+- No mocks, stubs, or fake creators — real launch records + real ERC-8004 identities only.
+
+## Success criteria
+
+- Reachable in the UI as a creator directory + series flow; a real agent links a real sequel mint
+ into a verifiable series and it renders across the directory and launch surfaces.
+- Real `pump_agent_mints` / `erc8004_agents_index` / `onchain` data; buys guard-honored and
+ custody-audited; minting within launch guardrails.
+- All states designed; responsive at 320/768/1440; accessible (ARIA, keyboard, focus, contrast,
+ reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/creator-series-cross-chain-mint.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/curve-depth-heatmap.md b/tasks/trading-frontier/next/curve-depth-heatmap.md
new file mode 100644
index 000000000..18b6d0b9a
--- /dev/null
+++ b/tasks/trading-frontier/next/curve-depth-heatmap.md
@@ -0,0 +1,70 @@
+# Bonding-Curve Depth & Slippage Heatmap (pre-trade impact visualizer)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+
+## The invention
+
+Before any trade, the one number that matters is "how much will my size move the price?" — and
+pump.fun shows nothing. The Depth Heatmap samples the live bonding curve / AMM pool across a
+range of trade sizes and renders the real marginal-impact curve: spend 0.1 / 0.5 / 1 / 5 SOL,
+see the price impact and tokens-out for each, and the size where impact crosses your comfort
+threshold. It turns blind sizing into an informed decision.
+
+## Context (real, verified)
+
+- Quotes: `api/_lib/pump.js` (`quoteForBuy`/`quoteForSell`, `getAmmPoolState`),
+ `workers/agent-sniper/amm-exit.js` (`quoteAmmSell`). Impact field: `priceImpactPct`.
+- Charting precedent: `lightweight-charts` is already a dependency; trade UI in
+ `src/agent-wallet-hub/tabs/trade.js`.
+
+## Goal
+
+A `GET /api/agents/:id/depth?mint=…` (or a public mint endpoint) returning a sampled
+size→impact→out curve from live state, and a visual heatmap/curve in the Trade + Orders tabs
+with an "optimal size for ≤X% impact" marker.
+
+## What to build
+
+1. **Sampler** — quote a configurable size ladder against live reserves (curve or AMM), returning
+ impact + tokens-out + effective price per size; cache briefly per mint.
+2. **Optimizer** — surface the largest size keeping impact under the user's ceiling.
+3. **UI** — a real chart (lightweight-charts) of the depth curve, wired into the Trade size input
+ and the Orders builder so picking a size shows its live impact. All states designed.
+4. **Honesty** — graduated coins sample the AMM; a quote gap shows a clear empty/error state.
+
+## Constraints
+
+Read-only — no funds move. Real live quotes only, never interpolated/fake. Bounded sampling
+(rate-limit the quote fan-out). $THREE-only; runtime mints are data.
+
+## Success criteria
+
+The heatmap renders a real size→impact curve for any mint, marks the optimal size, and feeds the
+trade/order size inputs. UI renders all states; chain extended. Build/test clean. Changelog
+(feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/curve-depth-heatmap.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/drawdown-circuit-breaker.md b/tasks/trading-frontier/next/drawdown-circuit-breaker.md
new file mode 100644
index 000000000..3bbdbe046
--- /dev/null
+++ b/tasks/trading-frontier/next/drawdown-circuit-breaker.md
@@ -0,0 +1,82 @@
+# Task — Portfolio Drawdown Circuit Breaker (auto-freeze on the whole book)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+The existing spend guards bound a *single trade*. None of them stop a bad day: an agent can lose
+trade after trade and keep firing. Build a **Portfolio Drawdown Circuit Breaker**: an owner-set
+rule that watches the wallet's net-worth (or realized-PnL) drawdown over a rolling window and, when
+it crosses a threshold, automatically *freezes all trading* — discretionary, every sniper strategy,
+copy/mirror, swarm — until the owner re-arms. A book-level kill switch that the agent itself
+respects, wired into the guards every trade already passes through.
+
+## Context (real, verified)
+
+- Per-trade kill switch + spend policy live in `api/_lib/agent-trade-guards.js`
+ (`checkKillSwitch`, `getTradeLimits`/`setTradeLimits`, `enforceSpendLimit`) and are read on every
+ trade in `api/agents/agent-trade.js` and the sniper executor (`workers/agent-sniper/`).
+- Drawdown + net worth to threshold against: `api/_lib/trader-stats.js` (`maxDrawdown`, realized PnL)
+ and the portfolio service (trading-frontier 03, `api/_lib/portfolio.js`) for live net worth; window
+ helpers `windowStartIso`. Sniper arming state: `agent_sniper_strategies`.
+
+## Goal
+
+A breaker service (`api/_lib/drawdown-breaker.js`) integrated into the shared guard path + a
+`/api/agents/:id/breaker` config endpoint, so a crossed drawdown threshold sets a freeze that every
+trade path (manual, sniper, mirror, swarm) honors until re-armed, with full audit + alert.
+
+## What to build
+
+1. **Breaker rule** — owner config: metric (net-worth vs realized-PnL drawdown), threshold %,
+ rolling window, and action (freeze-all / freeze-buys-only). Stored on the agent policy alongside
+ the existing trade limits.
+2. **Enforcement** — extend the shared guard the trade/snipe paths already call so a tripped breaker
+ blocks new entries (and optionally arms exits) for ALL strategies at once; tripping is recorded
+ in `agent_custody_events` and emits an alert. Re-arm is an explicit owner action (CSRF-gated).
+3. **API** — `/api/agents/:id/breaker` (GET status incl. current drawdown vs threshold, PUT config,
+ POST re-arm). Owner-only, rate-limited.
+4. **UI** — a Breaker panel in the wallet hub: live drawdown gauge vs threshold, armed/tripped state,
+ config form, and a re-arm button (with the tripped reason + timestamp). All states designed;
+ accessible; responsive.
+
+## Constraints
+
+- The breaker can only ever *restrict* trading; it never moves funds on its own beyond the
+ owner-configured freeze. Tripping + re-arming are fully audited. Real net-worth/PnL data only.
+- Enforcement lives in the one shared guard every trade passes — no bypass route. $THREE-only rule.
+
+## Success criteria
+
+- A crossed drawdown threshold demonstrably freezes new trades across manual + sniper + mirror +
+ swarm paths until the owner re-arms, with audit + alert and a live gauge.
+- Breaker UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature, security). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/drawdown-circuit-breaker.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/dust-sweeper-rent-reclaimer.md b/tasks/trading-frontier/next/dust-sweeper-rent-reclaimer.md
new file mode 100644
index 000000000..f315f3e92
--- /dev/null
+++ b/tasks/trading-frontier/next/dust-sweeper-rent-reclaimer.md
@@ -0,0 +1,85 @@
+# Task — Dust Sweeper & Rent Reclaimer
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+An active sniper wallet accumulates a graveyard of dead/dust SPL token accounts — rugged coins,
+worthless remainders — each one a 165-byte token account locking up ~0.002 SOL of rent. Over
+hundreds of snipes that is real, recoverable money sitting idle. Build a **Dust Sweeper & Rent
+Reclaimer**: detect every dust/dead holding (sub-threshold USD value or unpriceable), batch
+`closeAccount` the empty ones to reclaim rent, and optionally dump-then-close the tiny non-zero ones
+— all signed server-side through the same custody guards. A self-cleaning wallet that hands the
+trader their locked SOL back.
+
+## Context (real, verified)
+
+- Holdings + token programs: `api/agents/solana-wallet.js#handleHoldings`; the existing two-phase
+ sweep helper `sweepWalletToAddress` already builds `createCloseAccountInstruction` chunks and
+ reclaims ATA rent (see the vanity-swap path in the same file) — reuse that machinery.
+- Pricing to classify dust: `api/_lib/balances.js#solanaMintUsdPrice` (Jupiter → pump.fun fallback;
+ 0 = unpriceable/dead). Server signing + audit: `recoverSolanaAgentKeypair`,
+ `agent_custody_events`, spend guards in `api/_lib/agent-trade-guards.js`.
+- Token-account rent constant + close instruction already imported in `solana-wallet.js`.
+
+## Goal
+
+A dust-analysis service (`api/_lib/dust-sweeper.js`) + `/api/agents/:id/solana/dust` (GET analyze,
+POST reclaim) that finds reclaimable token accounts, estimates the SOL recoverable, and executes a
+guarded, audited batch close, surfaced in the wallet hub.
+
+## What to build
+
+1. **Dust detection** — classify each SPL holding as priceable / dust (USD below a threshold) /
+ dead (zero or unpriceable); compute total reclaimable rent (closeable empty/dustable accounts)
+ in SOL. Honest, never destructive to a holding the user values — require explicit selection.
+2. **Guarded batch close** — POST executes a CSRF-protected, owner-authenticated, chunked close of
+ the selected accounts (close empty; for tiny non-zero, sell-to-curve where liquid then close),
+ reclaiming rent to the agent wallet; idempotent; every action audited in `agent_custody_events`.
+3. **API** — GET returns the dust report (count, reclaimable SOL, per-account detail); POST returns
+ signatures + reclaimed SOL. Rate-limited; simulate-first preview like the withdraw path.
+4. **UI** — a Cleanup panel in the wallet hub: "X SOL reclaimable across N dead accounts" header, a
+ selectable list with per-row value/liquidity, a preview, and a confirmed Reclaim action. All
+ states designed (empty = "wallet is clean"); accessible; responsive.
+
+## Constraints
+
+- Destructive-adjacent: never close an account the user didn't explicitly select; preview before
+ execute; full custody audit. Real on-chain only.
+- All signing through existing custody guards/CSRF; idempotent; honest failure handling.
+- $THREE-only rule; runtime mints are trade data only.
+
+## Success criteria
+
+- The sweeper correctly identifies reclaimable rent from real dead/dust accounts and executes a
+ guarded, audited batch close that returns SOL to the wallet.
+- Cleanup UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/dust-sweeper-rent-reclaimer.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/dynamic-position-sizing.md b/tasks/trading-frontier/next/dynamic-position-sizing.md
new file mode 100644
index 000000000..dbb4cbfe7
--- /dev/null
+++ b/tasks/trading-frontier/next/dynamic-position-sizing.md
@@ -0,0 +1,91 @@
+# Task — Dynamic Position Sizing (regime + conviction-weighted automatic sizing)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+Right now the size of a trade is whatever the user types. That is the single biggest preventable
+source of blowups — over-sizing low-conviction, high-volatility coins and under-sizing the rare
+strong setups. Build a **dynamic position-sizing engine**: given the agent's risk regime, the
+oracle's conviction for the coin, and the coin's historical volatility, compute a recommended trade
+size using a volatility-target / fractional-Kelly model, clamped by the spend guards. Expose it as a
+single shared service the copilot, the orders engine, and the snipe tab all call, so every entry
+across the platform is sized by the same disciplined logic instead of a guess.
+
+## Context (real, verified)
+
+- Conviction signal: the `oracle_conviction` table (per-coin conviction the oracle already produces).
+- Historical risk inputs: `pump_coin_outcomes` (realized `ath_multiple`, volatility/decay history
+ used to estimate per-coin risk and edge).
+- Live exposure: `agent_sniper_positions` (current holdings to compute incremental risk and
+ portfolio-level caps).
+- Hard ceiling: `api/_lib/agent-trade-guards.js` (per-trade and cumulative spend caps the sizing
+ output must never exceed).
+
+## Goal
+
+A `sizePosition` service that returns a recommended notional + the reasoning (regime, conviction,
+volatility estimate, fraction of bankroll), always clamped to the spend guards, callable from every
+entry surface on the platform.
+
+## What to build
+
+1. **Sizing model** — volatility-target sizing with a fractional-Kelly edge term derived from
+ `oracle_conviction` and the realized win/return distribution in `pump_coin_outcomes`; configurable
+ risk regime (conservative / balanced / aggressive) that scales the target volatility.
+2. **Bankroll + exposure awareness** — read current `agent_sniper_positions` and wallet balance so
+ recommendations account for existing exposure and never recommend beyond available capital.
+3. **Guard clamp** — the recommended size is always min'd against `api/_lib/agent-trade-guards.js`
+ caps; the UI shows when the model wanted more than the guard allows.
+4. **Shared service + API** — `api/agents/size-position` returning notional + transparent rationale;
+ wire it as the default size source in the copilot (task 01), orders engine (task 02), and snipe tab.
+5. **UI** — an inline sizing chip on every entry: recommended size, a one-line "why", a slider to
+ override within guards, and the regime selector. All states designed; responsive; accessible.
+6. **Backtest the sizing** — show, on historical `pump_coin_outcomes`, how the model's sizing would
+ have shaped drawdown vs. flat sizing, so the user trusts it.
+
+## Constraints
+
+- Recommendations honor spend guards (`api/_lib/agent-trade-guards.js`); every executed trade still
+ writes custody audit (`agent_custody_events`) and clears the firewall (`api/_lib/trade-firewall.js`)
+ when buying.
+- $THREE is the only promoted coin; runtime mints in sizing inputs are trade data only.
+- No mocks, stubs, or fake data — real conviction, outcomes, and position data only.
+
+## Success criteria
+
+- Reachable in the UI on every entry surface (copilot, orders, snipe) with a live, explainable size.
+- Real `oracle_conviction` / `pump_coin_outcomes` / `agent_sniper_positions` data; guard-clamped;
+ custody-audited and firewall-cleared on execution.
+- All states designed; responsive at 320/768/1440; accessible (ARIA, keyboard, focus, contrast,
+ reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/dynamic-position-sizing.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/exit-liquidity-radar.md b/tasks/trading-frontier/next/exit-liquidity-radar.md
new file mode 100644
index 000000000..8b0473471
--- /dev/null
+++ b/tasks/trading-frontier/next/exit-liquidity-radar.md
@@ -0,0 +1,82 @@
+# Task — Exit-Liquidity Radar (true liquidatable net worth)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+Portfolio valuations everywhere quote *paper* value — token balance × last price. For a thin
+memecoin that lie is fatal: a "10 SOL position" might net 2 SOL once you actually sell into the
+curve. Build an **Exit-Liquidity Radar**: for each holding, simulate the real sell against the live
+bonding-curve / AMM reserves to compute the *liquidatable* value at multiple slippage tolerances
+(1% / 5% / full-exit), the max size sellable before each threshold, and a depth score. Surface a
+portfolio-wide **paper value vs liquidatable value** gap. This is the honest number no competitor
+shows.
+
+## Context (real, verified)
+
+- Curve/AMM reserves + quoting: `api/_lib/pump.js` (`getAmmPoolState` → `baseReserve`/`quoteReserve`;
+ `getPumpSdkV2` → `getSellSolAmountFromTokenAmount(tokenAmount, bonding_curve)`). Pre- vs
+ post-graduation handled there.
+- Holdings enumeration: `api/agents/solana-wallet.js#handleHoldings` (SOL + every SPL with balance);
+ per-mint mark price `api/_lib/balances.js#solanaMintUsdPrice`.
+- SOL/USD: `api/_lib/pumpfun-ws-feed.js#getSolPrice`, `api/_lib/agent-trade-guards.js#lamportsToUsd`.
+
+## Goal
+
+A depth-aware valuation service (`api/_lib/exit-liquidity.js`) + `/api/agents/:id/liquidity` that,
+per holding, returns sell-simulated proceeds at slippage tiers and a portfolio paper-vs-real gap,
+surfaced as a Liquidity panel in the wallet hub.
+
+## What to build
+
+1. **Sell simulation** — for each holding, quote real SOL-out for graduated sizes (5%/25%/50%/100%
+ of the balance) against live reserves; derive price-impact %, max size under 1%/5% impact, and a
+ 0–100 depth score. Gracefully mark unpriceable/dead pools as illiquid (0 liquidatable) — never crash.
+2. **Paper vs real** — sum mark-price value vs simulated-liquidation value across the portfolio;
+ surface the gap in SOL + USD and a per-holding "haircut %".
+3. **API** — `/api/agents/:id/liquidity?network=` with brief caching (pools move fast); concurrent
+ per-holding simulation; honest illiquid flags.
+4. **UI** — a Liquidity panel: portfolio paper-vs-liquidatable header, a holdings table with depth
+ score + haircut + max-1%-exit size, and a one-click jump to sell the liquid portion through the
+ existing guarded trade path. All states designed; accessible; responsive.
+
+## Constraints
+
+- Every number is a real on-chain simulation; illiquid holdings are flagged, never guessed.
+- Read-only analytics + jump-to-action; trades go through existing guarded paths only.
+- $THREE-only rule; runtime mints are trade data only.
+
+## Success criteria
+
+- For real holdings, the radar shows true liquidatable value at slippage tiers and an honest paper-
+ vs-real gap, with illiquid pools flagged.
+- Liquidity UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/exit-liquidity-radar.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/fleet-treasury-console.md b/tasks/trading-frontier/next/fleet-treasury-console.md
new file mode 100644
index 000000000..2c03e0bfd
--- /dev/null
+++ b/tasks/trading-frontier/next/fleet-treasury-console.md
@@ -0,0 +1,84 @@
+# Task — Fleet Treasury Console (cross-agent roll-up for one owner)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+A power user runs *many* agents, each with its own custodial Solana wallet, positions, and snipers.
+Today they must open each agent's wallet hub one at a time — there is no portfolio of portfolios.
+Build a **Fleet Treasury Console**: one owner-scoped dashboard that rolls up net worth, PnL, open
+exposure, and risk across **every agent the user owns**, ranks the agents by contribution, surfaces
+the fleet's largest concentrations and worst drawdowns, and lets the owner drill into any agent. A
+fund-manager cockpit for an army of trading agents — unique to three.ws's multi-agent model.
+
+## Context (real, verified)
+
+- Ownership: `agent_identities` (`user_id`, `meta.solana_address`); auth via `api/_lib/auth.js`
+ (`getSessionUser`, `authenticateBearer`). The user's agents = `WHERE user_id = $1 AND deleted_at IS NULL`.
+- Per-agent valuation + PnL primitives to fan out over: `api/_lib/balances.js` (`getBalances`,
+ `walletUsdTotal`), `api/_lib/trader-stats.js` (`computeTraderMetrics`, `fetchTraderPositions`), and
+ the portfolio service from trading-frontier 03 (`api/_lib/portfolio.js`) if present.
+- Hub mount pattern + design tokens: `src/agent-wallet-hub/` (registry, tabs, util); user agent list
+ surfaces already fetch from `/api/agents`.
+
+## Goal
+
+A fleet aggregation service (`api/_lib/fleet-treasury.js`) + `/api/me/fleet` endpoint that values and
+ranks all of a user's agents, plus a Fleet Console page that visualizes the roll-up and drills into
+any agent's wallet hub.
+
+## What to build
+
+1. **Fleet aggregation** — for the authenticated owner, enumerate owned agents with wallets, value
+ each concurrently (bounded concurrency, cached), and sum to fleet net worth (SOL + USD), total
+ realized/unrealized PnL, and total open exposure. Degrade per-agent failures honestly (mark, skip,
+ never fail the whole roll-up).
+2. **Fleet risk** — fleet-level concentration (which agent / which mint dominates), aggregate
+ drawdown, and a ranked contribution table (who's making/losing the most).
+3. **API** — `/api/me/fleet` owner-only, paginated for large fleets, with a lightweight summary mode
+ for the nav badge.
+4. **UI** — a Fleet Console page (linked from the user dashboard / agent list): net-worth header,
+ a sortable agent table (value, PnL, exposure, risk flag), fleet concentration view, and a click-
+ through to each agent's wallet hub. All states designed (empty for a user with one/zero funded
+ agents); accessible; responsive.
+
+## Constraints
+
+- Strictly owner-scoped (never expose another user's fleet); real on-chain + ledger data only.
+- Read-only roll-up + drill-through; no trades initiated at the fleet layer.
+- Performance: bounded-concurrency valuation, caching, virtualized tables. $THREE-only rule.
+
+## Success criteria
+
+- An owner sees a correct, live roll-up of net worth / PnL / exposure / risk across all their agents,
+ ranked by contribution, drilling into any agent.
+- Fleet Console renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/fleet-treasury-console.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/gas-fee-forecaster-batcher.md b/tasks/trading-frontier/next/gas-fee-forecaster-batcher.md
new file mode 100644
index 000000000..9fe206226
--- /dev/null
+++ b/tasks/trading-frontier/next/gas-fee-forecaster-batcher.md
@@ -0,0 +1,93 @@
+# Task — Gas-Fee Forecaster & Batcher (priority-fee prediction + small-order auto-batching)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+On Solana, the difference between a snipe that lands and one that drops is the priority fee — and
+right now that fee is a static guess. Build a **priority-fee forecaster + order batcher**: forecast
+near-term Solana priority fees in real time from recent on-chain fee data, recommend the fee that
+maximizes land-rate per lamport for the current congestion, and auto-batch eligible small orders into
+fewer transactions so the user pays one fee instead of five. It directly raises fill rate on snipes
+and cuts the fee drag that quietly eats small-position PnL — execution quality nobody on a launchpad
+optimizes for the user.
+
+## Context (real, verified)
+
+- RPC + fee data: `api/_lib/solana/connection.js` (RPC failover + `getRecentPrioritizationFees` for
+ the live fee distribution the forecaster trains on).
+- Protected submit path: `api/_lib/execution-engine.js` (`submitProtected`, Jito) — where the
+ forecasted fee is applied and where batched bundles land.
+- Sniper executor: `workers/agent-sniper/executor.js` (the existing execution loop whose fee logic
+ the forecaster plugs into).
+
+## Goal
+
+A fee-forecasting service that outputs a recommended priority fee + congestion read, and a batcher
+that coalesces eligible small orders into fewer protected submissions — both wired into the live
+execution path.
+
+## What to build
+
+1. **Fee forecaster** — sample `getRecentPrioritizationFees` over a rolling window via
+ `api/_lib/solana/connection.js`, model the near-term fee distribution + congestion regime, and
+ output a recommended fee with a land-rate estimate.
+2. **Adaptive fee application** — feed the recommended fee into `submitProtected` /
+ `workers/agent-sniper/executor.js`, with escalation on drop (re-submit at a higher percentile)
+ bounded by a user max-fee cap.
+3. **Small-order batcher** — detect eligible same-block, same-side orders and coalesce them into a
+ single protected submission (or Jito bundle), splitting fills back to the right positions.
+4. **Fee API + telemetry** — `api/agents/fee-forecast` returning the live recommendation; record
+ realized land-rate vs. forecast so the model is auditable and improves.
+5. **UI** — a fee/congestion widget in the trade + snipe surfaces: live recommended fee, congestion
+ gauge, expected land-rate, batch indicator, and a max-fee control. All states designed;
+ responsive; accessible.
+6. **Honest fallback** — if fee data is stale/unavailable, fall back to a safe conservative fee and
+ say so; never silently under-fee a snipe into failure.
+
+## Constraints
+
+- All submissions honor spend guards (`api/_lib/agent-trade-guards.js`), write custody audit
+ (`agent_custody_events`), and clear the firewall (`api/_lib/trade-firewall.js`) on buys; batching
+ never merges trades across the guard/custody boundary incorrectly.
+- $THREE is the only promoted coin; batched runtime mints are trade data only.
+- No mocks, stubs, or fake fee data — real `getRecentPrioritizationFees` and real submits only.
+
+## Success criteria
+
+- Reachable in the UI from trade + snipe surfaces; a real snipe uses the forecasted fee and small
+ orders batch into fewer real transactions, with realized land-rate shown.
+- Real RPC fee data via `api/_lib/solana/connection.js`; real `submitProtected` execution;
+ guard-honored, custody-audited.
+- All states designed; responsive at 320/768/1440; accessible (ARIA, keyboard, focus, contrast,
+ reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/gas-fee-forecaster-batcher.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/liquidity-aggregation-router.md b/tasks/trading-frontier/next/liquidity-aggregation-router.md
new file mode 100644
index 000000000..d459c0c53
--- /dev/null
+++ b/tasks/trading-frontier/next/liquidity-aggregation-router.md
@@ -0,0 +1,96 @@
+# Task — Liquidity Aggregation Router (best-path execution across curve, PumpSwap, Jupiter)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+Today a buy executes on exactly one venue: the pump.fun bonding curve for pre-graduation coins, or
+the canonical AMM for graduated ones. That leaves money on the table — a graduated coin can be
+cheaper on Jupiter's aggregated routes than on its native PumpSwap pool, and a large order is often
+better split across venues than slammed into one. Build a **smart order router**: quote the same
+trade simultaneously across the bonding curve, the PumpSwap AMM, and Jupiter, compare effective
+price after price-impact and fees, and execute the best single path — or a slippage-minimized split
+across two venues — through the existing protected submit pipeline. One buy/sell button, best
+execution underneath.
+
+## Context (real, verified)
+
+- Bonding-curve + AMM pool state: `api/_lib/pump.js` (`getAmmPoolState` reads the migrated PumpSwap
+ pool reserves; bonding-curve reserves for pre-graduation pricing).
+- Quote primitives: `api/_lib/solana/sdk-bridge.js` (`getBuyQuote` / `getSellQuote`) and
+ `api/agents/solana-trade.js` (`quoteTrade`) — the single-venue quote path to generalize.
+- Protected execution: `api/_lib/execution-engine.js` (`submitProtected`) — the existing
+ Jito/priority-fee submit path every route must funnel through; never bypass it.
+- Spend + custody enforcement: `api/_lib/agent-trade-guards.js`, `agent_custody_events`.
+
+## Goal
+
+A venue-agnostic router that returns a ranked set of execution plans (single-venue or split) with
+real post-impact effective price for each, and executes the chosen plan atomically through
+`submitProtected`, audited and guarded exactly like a single-venue trade.
+
+## What to build
+
+1. **Multi-venue quote fan-out** — given (mint, side, size), quote the curve, PumpSwap (via
+ `getAmmPoolState`), and Jupiter concurrently; normalize each to tokens-out / SOL-out, price
+ impact, and total fee, surfacing which venues are eligible (e.g. curve only pre-graduation).
+2. **Best-path + split solver** — rank single-venue plans by effective price; compute whether a
+ two-venue split lowers total impact for large orders, and by how much; pick the optimum within a
+ user slippage ceiling.
+3. **Protected execution** — build the route's transaction(s) and submit through `submitProtected`,
+ honoring spend guards and writing `agent_custody_events`; on partial failure of a split, never
+ leave the user double-spent — settle or revert cleanly with an honest result.
+4. **Router API** — `api/agents/router-quote` + `api/agents/router-execute` returning the ranked
+ plans and an executed-route receipt (per-leg fills, realized price, Solscan links).
+5. **UI** — a route-preview card in the trade panel: each venue's quote, the chosen path
+ highlighted with the savings vs. single-venue, split breakdown, slippage control, and a
+ post-trade receipt. All states designed; responsive; accessible.
+6. **Honest degradation** — if Jupiter or a pool is unreachable, route over the venues that are up
+ and say so; never fabricate a quote.
+
+## Constraints
+
+- Every buy honors spend guards (`api/_lib/agent-trade-guards.js`), writes custody audit events
+ (`agent_custody_events`), and clears the firewall (`api/_lib/trade-firewall.js`) before funds move.
+- All execution funnels through `submitProtected` — no venue gets a bypass path.
+- $THREE is the only promoted coin; routed runtime mints are trade data only, never recommended.
+- No mocks, stubs, or fake quotes — real curve/AMM/Jupiter data only, with honest failure handling.
+
+## Success criteria
+
+- Reachable in the UI from the trade panel; a real trade routes to (and executes on) the genuinely
+ best venue or split, with the saving shown vs. single-venue.
+- Real curve/PumpSwap/Jupiter quotes and on-chain execution; spend-guarded, firewall-cleared,
+ custody-audited.
+- All states (loading/empty/error/populated/overflow) designed; responsive at 320/768/1440;
+ accessible (ARIA, keyboard, focus, contrast, reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/liquidity-aggregation-router.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/liquidity-exit-router.md b/tasks/trading-frontier/next/liquidity-exit-router.md
new file mode 100644
index 000000000..d8eac3fc5
--- /dev/null
+++ b/tasks/trading-frontier/next/liquidity-exit-router.md
@@ -0,0 +1,77 @@
+# Liquidity Exit Router (slippage-minimizing sell across curve + AMM)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+
+## The invention
+
+Dumping a large bag in one click craters the price — and once a coin has graduated, half its
+liquidity is on the curve and half on the AMM pool. The Exit Router takes ONE "sell X% of my
+bag, best execution" intent and computes the slippage-minimizing plan: how many micro-slices,
+what size each, which venue (bonding curve vs AMM), and what spacing — then executes them as a
+real, guarded sequence. It's not TWAP (time-based, blind to depth); it's depth-aware routing
+that reads live reserves and picks sizes where marginal price impact stays under a ceiling.
+
+## Context (real, verified)
+
+- Sell quotes + venues: `api/_lib/pump.js` (`quoteForSell`, `getAmmPoolState`),
+ `workers/agent-sniper/amm-exit.js` (`quoteAmmSell`, `buildAmmSellInstructions`, `isGraduated`).
+- Execution core: `executeAgentTrade` in `api/agents/agent-trade.js` (quote→firewall→guards→
+ custody→sign), and the programmable-orders engine `api/_lib/orders.js` + `workers/agent-orders`.
+- Price-impact breaker: `checkPriceImpact` in `api/_lib/agent-trade-guards.js`.
+- Custody audit: `agent_custody_events`; per-fill receipts pattern: `order_fills`.
+
+## Goal
+
+A `POST /api/agents/:id/exit-router/plan` that returns a real, depth-derived sell plan (slices,
+sizes, venues, expected total out vs naive one-shot), and an `execute` path that runs the plan
+through the existing guarded sell pipeline, recording each slice. A wallet-hub surface to
+configure (impact ceiling, max slices, urgency) and watch progress.
+
+## What to build
+
+1. **Planner** — sample `quoteForSell`/`quoteAmmSell` at increasing sizes to build the live
+ marginal-impact curve, then solve for the slice schedule that keeps each slice's impact under
+ the ceiling while minimizing total slippage; choose venue per slice (curve vs AMM).
+2. **Executor** — run slices through `executeAgentTrade` (sell), honoring spend guards + the
+ firewall, recording an `exit_router_fills` receipt per slice with realized out + impact.
+3. **Comparison** — always show realized vs naive-one-shot SOL out so the saving is provable.
+4. **UI** — an Exit Router panel in the wallet hub: bag size, impact ceiling, urgency slider,
+ live plan preview, run + progress, all states designed.
+
+## Constraints
+
+Every slice real, firewall-checked, spend-guarded, audited. Honest on a quote/RPC gap (pause +
+resume, never mis-size). Never exceed the daily budget or per-trade caps. $THREE-only; runtime
+mints are data.
+
+## Success criteria
+
+A large sell routes into N real guarded slices across the right venues, beats the naive one-shot
+on realized SOL out, and is fully audited. UI renders all states; chain extended.
+Build/typecheck/test clean. Changelog (feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/liquidity-exit-router.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/mev-sandwich-forensics.md b/tasks/trading-frontier/next/mev-sandwich-forensics.md
new file mode 100644
index 000000000..fc4cd7c69
--- /dev/null
+++ b/tasks/trading-frontier/next/mev-sandwich-forensics.md
@@ -0,0 +1,84 @@
+# Task — MEV / Sandwich Forensics (how much the bots took from you)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+The MEV execution engine (next-gen 02) helps you *land* a trade. It never tells you when you got
+*robbed*. Build **MEV / Sandwich Forensics**: a post-trade detective that re-reads each of the
+agent's swap transactions and its block neighborhood, detects when the agent was sandwiched (a bot
+bought immediately before and sold immediately after the agent in the same pool/slot), quantifies
+the SOL the agent actually lost to that extraction versus its quoted execution, and surfaces the
+toxic pools / RPC routes where it keeps happening. The honest receipt of the invisible MEV tax —
+and an evidence trail to route around it.
+
+## Context (real, verified)
+
+- Agent swap signatures: `agent_sniper_positions` (`buy_sig`/`sell_sig`) and `agent_custody_events`
+ (`signature`, category trade/snipe). Tx + block neighbors come from `getParsedTransaction` /
+ `getBlock` over the RPC layer already wired in `api/agents/solana-wallet.js`
+ (`getParsedTransactions`, `_solRpcWithBackoffFallback`, `solanaConnection`).
+- Expected execution to compare against: the quote each trade recorded (entry/exit lamports in the
+ position row; price-impact fields `entry_price_impact_pct`), and curve/AMM state
+ `api/_lib/pump.js#getAmmPoolState`. SOL/USD: `api/_lib/pumpfun-ws-feed.js#getSolPrice`.
+
+## Goal
+
+A forensics service (`api/_lib/mev-forensics.js`) + `/api/agents/:id/mev` that classifies each swap
+as clean / sandwiched / front-run, quantifies SOL lost to extraction, and aggregates a MEV-tax
+report surfaced in the wallet hub.
+
+## What to build
+
+1. **Sandwich detection** — for each swap, inspect the same-pool transactions immediately before
+ and after the agent's tx in the slot/block; flag the buy-before / sell-after bot signature and
+ estimate the extracted value vs the agent's quoted execution. Conservative + evidence-linked
+ (every flag points to the on-chain txs).
+2. **MEV-tax aggregate** — total SOL/USD lost to extraction, sandwich rate, worst pools, and which
+ RPC/route correlates with the most extraction.
+3. **API** — `/api/agents/:id/mev?window=` returns per-swap verdicts + the aggregate; cached;
+ concurrent tx fetch; honest "indeterminate" when block data is unavailable (never a false accusation).
+4. **UI** — a MEV panel: MEV-tax header (SOL/USD lost, sandwich rate), a per-swap table with verdict
+ + Solscan links to the bot txs, and a toxic-pool/route summary. All states designed (empty/clean);
+ accessible; responsive.
+
+## Constraints
+
+- Every accusation is backed by real on-chain neighbor transactions; ambiguous cases are marked
+ indeterminate, never fabricated. Read-only forensics; no trades initiated.
+- $THREE-only rule; runtime mints are trade data only.
+
+## Success criteria
+
+- The forensics correctly identifies real sandwich/front-run events around the agent's swaps and
+ quantifies the SOL lost, with evidence links and honest indeterminate handling.
+- MEV UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature, security). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/mev-sandwich-forensics.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/narrative-drift-sentinel.md b/tasks/trading-frontier/next/narrative-drift-sentinel.md
new file mode 100644
index 000000000..2b618cd03
--- /dev/null
+++ b/tasks/trading-frontier/next/narrative-drift-sentinel.md
@@ -0,0 +1,90 @@
+# Task — Narrative Drift Sentinel (detect creator/story pivots + sentiment decay)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+A memecoin lives or dies on its narrative, and the deadliest tell is when the *story changes* — the
+creator quietly rebrands, deletes the original thesis, or the community sentiment that pumped it
+curdles into exit-liquidity chatter. Build a **narrative drift sentinel**: continuously diff a coin's
+current narrative + sentiment against its launch narrative using the oracle narrative engine and the
+platform's social sources, and red-flag launches whose story pivoted or whose sentiment decayed past
+a threshold — before the price catches up to the vibe. It is fundamental analysis for assets whose
+only fundamental is the story.
+
+## Context (real, verified)
+
+- Narrative engine + history: the `oracle_narrative` table (per-coin narrative the oracle already
+ derives) — the baseline to diff against.
+- Social + data sources: `api/_lib/oracle/sources.js` (the existing source connectors the oracle
+ pulls from) for current community signal.
+- Archetype/classification: `api/_lib/oracle/archetype.js` (how the oracle types a launch) to detect
+ an archetype/thesis flip.
+- Live sentiment: the MCP `sentiment_pulse` tool (token sentiment pulse) for the decay signal.
+
+## Goal
+
+A sentinel that, per watched/held coin, computes a narrative-drift score and a sentiment-decay score
+against the launch baseline, and fires a graded red-flag (with the specific change) when the story
+no longer matches what the user bought.
+
+## What to build
+
+1. **Narrative baseline + diff** — snapshot the launch narrative from `oracle_narrative` and
+ periodically re-derive the current narrative, computing a semantic drift score and surfacing the
+ specific pivot (thesis change, archetype flip via `api/_lib/oracle/archetype.js`).
+2. **Sentiment-decay track** — pull current community signal via `api/_lib/oracle/sources.js` +
+ `sentiment_pulse`, maintain a rolling sentiment curve, and detect decay/flip past a threshold.
+3. **Graded red-flags** — combine drift + decay into a watch/caution/exit signal with a plain-language
+ explanation of exactly what changed (e.g. "creator deleted launch thesis; sentiment flipped").
+4. **Stream + action** — push flags through the existing alert/stream surface; offer a one-tap
+ protected exit on held positions.
+5. **UI** — a "Narrative health" panel per coin: launch-vs-now narrative diff, sentiment sparkline,
+ flag severity, and the explanation. All states designed; responsive; accessible.
+6. **Honest signals** — distinguish healthy narrative *evolution* from a pivot/abandonment; never
+ flag on noise, and always show why a flag fired.
+
+## Constraints
+
+- Any exit/entry triggered honors spend guards (`api/_lib/agent-trade-guards.js`), custody audit
+ (`agent_custody_events`), and the firewall (`api/_lib/trade-firewall.js`) on buys.
+- $THREE is the only promoted coin; analyzed runtime mints are trade data only.
+- No mocks, stubs, or fake sentiment — real oracle narrative, real sources, real sentiment only.
+
+## Success criteria
+
+- Reachable in the UI for watched/held coins; a real narrative pivot or sentiment decay produces a
+ graded, explained red-flag with a working protected exit.
+- Real `oracle_narrative` / `oracle/sources` / `sentiment_pulse` data; guard-honored, custody-audited.
+- All states designed; responsive at 320/768/1440; accessible (ARIA, keyboard, focus, contrast,
+ reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/narrative-drift-sentinel.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/networth-history-recorder.md b/tasks/trading-frontier/next/networth-history-recorder.md
new file mode 100644
index 000000000..1c5bd7806
--- /dev/null
+++ b/tasks/trading-frontier/next/networth-history-recorder.md
@@ -0,0 +1,82 @@
+# Task — Net-Worth History Recorder (real equity curve + true drawdown)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+Portfolio Command (trading-frontier 03) computes net worth *right now*, and its sparkline only lives
+for the current session — when you close the tab, the history is gone, and its "max drawdown" is
+limited to the sniper realized equity curve, not the wallet's actual net worth over time. Build a
+**Net-Worth History Recorder**: a scheduled snapshotter that persists each funded agent wallet's
+real net worth (SOL + USD) on an interval into a time-series, so the platform can finally show a
+*true* equity curve, real net-worth (not just realized-PnL) drawdown, time-windowed return (24h/7d/
+30d), and a high-water mark — the foundation every serious portfolio chart needs.
+
+## Context (real, verified)
+
+- Live valuation already exists: `api/_lib/portfolio.js` (`getPortfolio`, `valuateHoldings`) and
+ `api/_lib/balances.js` (`getBalances`, `walletUsdTotal`). Reuse them — do not re-implement pricing.
+- Owned funded wallets: `agent_identities` (`meta.solana_address`). Cron/worker pattern exists for
+ the sniper + signals (`workers/`, Vercel cron in `vercel.json`); SSE + DB via `api/_lib/db.js`.
+- The Portfolio tab + `/api/agents/:id/portfolio` are the consumer surfaces to extend with history.
+
+## Goal
+
+A new `agent_networth_snapshots` time-series + a recorder (cron/worker) that snapshots each funded
+agent's net worth on an interval, and a history API + chart that turn it into a real equity curve,
+true net-worth drawdown, and windowed returns in the wallet hub.
+
+## What to build
+
+1. **Snapshot schema + recorder** — a migration for `agent_networth_snapshots` (agent_id, network,
+ ts, net_worth_sol, net_worth_usd, sol_usd, holdings_count) and a scheduled job that values every
+ funded agent (bounded concurrency, reusing `getPortfolio`) and appends a row. Idempotent per
+ interval; skips empty wallets honestly; degrades per-agent failures without poisoning the batch.
+2. **History API** — `/api/agents/:id/portfolio/history?window=` returns the down-sampled series +
+ derived stats (true max drawdown from the net-worth curve, high-water mark, windowed return %).
+3. **Retention** — sane down-sampling/retention so the series stays bounded (e.g. fine-grained
+ recent + daily older), documented and enforced.
+4. **UI** — a real equity-curve chart in the Portfolio header (replacing the session-only sparkline)
+ with window toggles, plus true-drawdown + windowed-return stats. All states designed (empty until
+ the first snapshots accrue, with a helpful "history is building" message); accessible; responsive.
+
+## Constraints
+
+- Every snapshot is a real valuation; no backfilled/fabricated points (history starts when recording
+ starts — say so). Read-only analytics; no trades.
+- Bounded cost: concurrency caps, down-sampling, retention. $THREE-only rule; runtime mints are
+ holdings data only.
+
+## Success criteria
+
+- Funded agents accrue a real net-worth time-series; the Portfolio chart shows a true equity curve,
+ real net-worth drawdown, and windowed returns, with an honest "building history" empty state.
+- Build/typecheck/test clean. Changelog entry (tags: feature, infra). Completionist passes. Chain extended.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/networth-history-recorder.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/oco-bracket-orders.md b/tasks/trading-frontier/next/oco-bracket-orders.md
new file mode 100644
index 000000000..535a51649
--- /dev/null
+++ b/tasks/trading-frontier/next/oco-bracket-orders.md
@@ -0,0 +1,69 @@
+# OCO Bracket Orders (one-cancels-other: take-profit + stop on a position)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+
+## The invention
+
+Every serious position wants a bracket: a take-profit above and a stop-loss below, where the
+first to fill cancels the other. Today you'd arm two independent orders and risk both firing.
+OCO makes them atomic — one fills, the sibling is cancelled in the same transaction-of-record —
+so a position is protected on both sides without ever double-selling.
+
+## Context (real, verified)
+
+- Orders engine: `api/_lib/orders.js` (limit + stop sells), worker `workers/agent-orders/sweep.js`
+ (the atomic `claimFire` → `firing` transition is the hook for sibling cancellation).
+- Custody idempotency: per-fill `idempotency_key` in `executeAgentTrade`.
+- UI: `src/agent-wallet-hub/tabs/orders.js`.
+
+## Goal
+
+An OCO is two linked orders (a limit-sell TP + a stop-sell SL) where filling/firing one cancels
+the other atomically. Build the link model, the worker-side mutual-cancel on fire, and an OCO
+create flow in the Orders tab.
+
+## What to build
+
+1. **Link model** — an `oco_link` (group) joining the two child orders.
+2. **Atomic mutual-cancel** — when one child wins the `claimFire` race, cancel the sibling in the
+ same DB step BEFORE executing, so the sibling can never also fire.
+3. **Recovery** — a crash mid-fire leaves both consistent (the loser stays cancelled).
+4. **UI** — one OCO form (TP target + SL stop + size), shown as a single bracketed row with both
+ legs, all states designed.
+
+## Constraints
+
+Mutual exclusion is provable (no path fires both legs). Reuses guarded fills. Cancel instant.
+$THREE-only; runtime mints are data.
+
+## Success criteria
+
+Arming an OCO creates two linked legs; the first to trigger fills and the other is provably
+cancelled; never both. UI renders all states; chain extended. Build/test clean. Changelog
+(feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/oco-bracket-orders.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/order-health-monitor.md b/tasks/trading-frontier/next/order-health-monitor.md
new file mode 100644
index 000000000..d7e4c7849
--- /dev/null
+++ b/tasks/trading-frontier/next/order-health-monitor.md
@@ -0,0 +1,71 @@
+# Order Health Monitor (why-not-firing diagnostics + auto re-arm)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+
+## The invention
+
+An order that silently never fires is worse than no order. The Health Monitor reads every active
+order's real state and explains, per order, why it hasn't fired — trigger not met (and how far
+off), wallet frozen, daily budget exhausted, kill switch on, firewall-halted, stale price feed,
+or no live data — and offers the one-click fix (unfreeze, raise budget, re-arm). It also lets
+you set auto-policies: re-arm an errored order, or auto-expire stale ones.
+
+## Context (real, verified)
+
+- Order state: `orders` (`status`, `last_error`, `last_eval_at`, `last_price`) + `order_fills`
+ (`api/_lib/orders.js`, `workers/agent-orders`).
+- Spend/freeze/kill state: `agent_trade-guards.js` (`getSpendLimits`, `getTradeLimits`);
+ worker liveness: `bot_heartbeat` (the orders worker writes `worker='agent-orders'`).
+- The Orders tab `src/agent-wallet-hub/tabs/orders.js` already shows `last_error`.
+
+## Goal
+
+A `GET /api/agents/:id/orders/health` that returns per-order + global diagnostics (reason codes +
+the live numbers behind them + the worker's heartbeat age), and a Health panel with one-click
+remediations + auto re-arm/expire policy toggles.
+
+## What to build
+
+1. **Diagnoser** — for each active order, classify why it hasn't fired from real state (distance
+ to trigger, freeze, budget, kill, firewall, data gap, worker liveness).
+2. **Remediations** — wire the existing fixes (unfreeze, adjust caps, re-arm/cancel) behind
+ one-click actions, CSRF-gated.
+3. **Auto-policies** — opt-in re-arm-on-error / auto-expire, enforced by the worker.
+4. **UI** — a health dashboard with clear, actionable rows; all states designed.
+
+## Constraints
+
+Diagnostics from REAL state only — never guess. Remediations honor the same owner-gated, audited
+paths. $THREE-only; runtime mints are data.
+
+## Success criteria
+
+Every stuck order shows a correct, real reason + a working one-click fix; worker liveness is
+visible; auto-policies work. Chain extended. Build/test clean. Changelog (feature). Completionist
+passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/order-health-monitor.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/paper-trading-sandbox.md b/tasks/trading-frontier/next/paper-trading-sandbox.md
new file mode 100644
index 000000000..32b846706
--- /dev/null
+++ b/tasks/trading-frontier/next/paper-trading-sandbox.md
@@ -0,0 +1,68 @@
+# Paper-Trading Sandbox (forward-test orders & strategies on live prices)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+
+## The invention
+
+Before risking real SOL, prove the setup. The Sandbox runs any order or strategy in paper mode
+against LIVE prices — real quotes, no broadcast — and tracks the hypothetical fills and running
+P&L over time. It's not a historical backtest (that's the NL strategy backtester); it's forward
+paper trading on the real market, so what you see is what would have happened, live.
+
+## Context (real, verified)
+
+- The orders worker already supports paper mode: `ORDERS_MODE=simulate` → `order_fills.status =
+ 'simulated'` with the real quote as the paper fill (`workers/agent-orders/sweep.js`).
+- `executeAgentTrade` simulate path (`api/agents/agent-trade.js`) returns real expected-out
+ without signing. Distinct from next-gen-trading/05 (historical backtester).
+
+## Goal
+
+A per-agent paper toggle on orders/strategies that routes fills to a sandbox ledger (no funds),
+marks them live against real quotes over time, and a Sandbox dashboard charting hypothetical
+equity + per-order paper P&L — with a one-click "go live" promotion.
+
+## What to build
+
+1. **Sandbox ledger** — `paper_fills` (mirrors `order_fills`, never touches custody) recording the
+ real-quote paper fill + a mark-to-market series.
+2. **Paper orders** — orders flagged `paper` evaluate identically but settle to the sandbox.
+3. **Equity curve** — chart hypothetical P&L from real marks; compare side-by-side to live.
+4. **Promote** — clone a proven paper order/strategy to a real armed one. All states designed.
+
+## Constraints
+
+Paper NEVER moves funds or writes custody. Marks come from REAL live quotes only. Clearly labelled
+as practice everywhere. $THREE-only; runtime mints are data.
+
+## Success criteria
+
+A paper order fills against live quotes, the equity curve updates from real marks, and promotion
+to live works — with zero custody impact. Chain extended. Build/test clean. Changelog (feature).
+Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/paper-trading-sandbox.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/portfolio-hedging-correlation.md b/tasks/trading-frontier/next/portfolio-hedging-correlation.md
new file mode 100644
index 000000000..cd11bcbda
--- /dev/null
+++ b/tasks/trading-frontier/next/portfolio-hedging-correlation.md
@@ -0,0 +1,89 @@
+# Task — Portfolio Hedging & Correlation (real-time correlation matrix + auto-hedge caps)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+A memecoin portfolio that looks diversified across ten tickers can really be one bet — ten dog coins
+that all dump together. Nobody on a launchpad shows you that. Build a **real-time correlation +
+hedging engine**: compute a live cross-position price-correlation matrix over the agent's holdings,
+cluster positions by category/narrative, expose the true concentration behind the apparent spread,
+and recommend hedges — trim the most-correlated cluster, or set correlation-aware max-exposure caps
+so a single narrative can't quietly become 80% of the book. Risk management memecoin traders have
+never had.
+
+## Context (real, verified)
+
+- Holdings: `agent_sniper_positions` and `api/agents/solana/holdings` (`[action].js` / `_handlers.js`)
+ for the current position set and balances.
+- Narrative grouping: `pump_coin_intel` (category/tags per coin) to cluster correlated positions by
+ theme, not just by realized price co-movement.
+- Realized stats for the correlation series: `api/_lib/trader-stats.js` (per-position price/PnL
+ history the matrix is computed over).
+
+## Goal
+
+A correlation-and-hedging surface that shows the agent's true diversification, recommends concrete
+hedge/trim actions, and enforces correlation-aware exposure caps across the book.
+
+## What to build
+
+1. **Live correlation matrix** — compute rolling pairwise price correlation across current
+ `agent_sniper_positions` using the series from `api/_lib/trader-stats.js`; surface the dominant
+ risk cluster and an effective-number-of-bets concentration metric.
+2. **Narrative clustering** — group positions by `pump_coin_intel` category/tags so the user sees
+ "you hold 6 coins but 2 themes" with the dollar weight per cluster.
+3. **Hedge recommendations** — suggest the trim that most reduces portfolio variance, sized by the
+ dynamic-sizing service if present, and offer a one-tap protected sell to apply it.
+4. **Correlation-aware caps** — let the user set a max-exposure-per-cluster cap; warn (and optionally
+ block, via the existing guard path) entries that would breach the cap on a correlated position.
+5. **UI** — a portfolio risk panel: the correlation heatmap, cluster weights, concentration gauge,
+ recommended hedges, and cap controls. All states designed; responsive; accessible.
+6. **Cross-link** — wire the concentration metric into the portfolio dashboard (task 03) so risk is
+ visible everywhere, not siloed.
+
+## Constraints
+
+- Hedge/trim execution honors spend guards (`api/_lib/agent-trade-guards.js`), writes custody audit
+ (`agent_custody_events`), and clears the firewall (`api/_lib/trade-firewall.js`) on any buy.
+- $THREE is the only promoted coin; held runtime mints are trade data only.
+- No mocks, stubs, or fake correlation data — real holdings + real price series only.
+
+## Success criteria
+
+- Reachable in the UI from the portfolio surface; the matrix and clusters reflect the agent's real
+ holdings and a recommended hedge executes as a real, guarded trade.
+- Real `agent_sniper_positions` / `pump_coin_intel` / `trader-stats` data; custody-audited and
+ firewall-cleared on execution.
+- All states designed; responsive at 320/768/1440; accessible (ARIA, keyboard, focus, contrast,
+ reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/portfolio-hedging-correlation.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/post-graduation-liquidity-monitor.md b/tasks/trading-frontier/next/post-graduation-liquidity-monitor.md
new file mode 100644
index 000000000..0db9f21e8
--- /dev/null
+++ b/tasks/trading-frontier/next/post-graduation-liquidity-monitor.md
@@ -0,0 +1,88 @@
+# Task — Post-Graduation Liquidity Monitor (track the AMM aftermath, alert on LP pulls)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+Task 09 (AMM migration sniper) is about catching the graduation *moment*. But the most dangerous
+window is the hours *after* graduation, when LP whales who provided the migration liquidity quietly
+withdraw and let the price bleed out — a slow rug the snipe path never sees. Build a **post-graduation
+liquidity monitor**: for every coin the agent holds or watches that has graduated to PumpSwap,
+continuously track pool depth, LP-holder concentration, and price decay, and fire a high-priority
+alert the instant an LP whale starts pulling liquidity — early enough to exit. It turns "I got rugged
+after it graduated" into "I was out before the pool drained."
+
+## Context (real, verified)
+
+- AMM exit logic + pool reads: `workers/agent-sniper/amm-exit.js` (the existing post-migration exit
+ worker) and `api/_lib/pump.js` (`getAmmPoolState` for live PumpSwap reserves).
+- Outcome history for decay baselines: `pump_coin_outcomes` (post-graduation price/volatility decay
+ to calibrate what "abnormal" looks like).
+- Live position/alert stream to push into: `api/sniper/stream.js` (the existing SSE/stream surface
+ the sniper UI already consumes).
+
+## Goal
+
+A monitor that, per held/watched graduated coin, samples pool depth + LP concentration on a cadence,
+detects abnormal liquidity withdrawal and price decay against a calibrated baseline, and streams an
+actionable alert (with a one-tap protected exit) before the pool drains.
+
+## What to build
+
+1. **Pool-depth + LP-concentration tracker** — poll `getAmmPoolState` for held/watched graduated
+ coins; compute reserve depth, top-LP share, and a rolling decay curve; persist a time series.
+2. **Withdrawal-detection model** — calibrate "normal" decay from `pump_coin_outcomes` and flag
+ abnormal depth drops / LP-whale exits with a severity score (watch / warning / pull-in-progress).
+3. **Alert + one-tap exit** — stream alerts through `api/sniper/stream.js`; each alert offers a
+ protected sell of the position (honoring guards + custody audit) so the user can exit in one tap.
+4. **Monitor worker** — extend the `workers/agent-sniper/` flow with a liquidity-monitor loop that
+ only watches graduated coins (curve coins are out of scope here), with backoff + RPC failover.
+5. **UI** — a "Liquidity health" panel per graduated holding: live depth, LP concentration, decay
+ sparkline, severity badge, and the exit action. All states designed; responsive; accessible.
+6. **Honest signals** — never raise a false rug alarm on normal volatility; tune thresholds against
+ real outcome history and show the user why an alert fired.
+
+## Constraints
+
+- Exit actions honor spend guards (`api/_lib/agent-trade-guards.js`), write custody audit
+ (`agent_custody_events`), and any re-buy clears the firewall (`api/_lib/trade-firewall.js`).
+- $THREE is the only promoted coin; monitored runtime mints are trade data only.
+- No mocks, stubs, or fake liquidity data — real PumpSwap pool reads and real outcome baselines only.
+
+## Success criteria
+
+- Reachable in the UI for graduated holdings; a real LP withdrawal on a real pool produces a timely,
+ actionable alert with a working protected exit.
+- Real `getAmmPoolState` reads + real `pump_coin_outcomes` baselines; guard-honored, custody-audited.
+- All states designed; responsive at 320/768/1440; accessible (ARIA, keyboard, focus, contrast,
+ reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/post-graduation-liquidity-monitor.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/profit-taking-ladder.md b/tasks/trading-frontier/next/profit-taking-ladder.md
new file mode 100644
index 000000000..0d7c10149
--- /dev/null
+++ b/tasks/trading-frontier/next/profit-taking-ladder.md
@@ -0,0 +1,70 @@
+# Profit-Taking Ladder (scale-out: staged take-profit rungs)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+
+## The invention
+
+Pros never sell a winner all at once — they scale out: 25% at 2×, 25% at 5×, the rest at 10×.
+The Ladder Builder turns that discipline into one action: describe the rungs (target + fraction)
+and it arms a coordinated set of real limit-sell orders that fire as price climbs, each selling
+its slice of the live holding. A linked OCO-style stop protects the downside. It sits ON TOP of
+the programmable-orders engine — composition, not a new execution path.
+
+## Context (real, verified)
+
+- Orders engine: `api/_lib/orders.js` (limit sells, `sell_pct`, `trigger_metric`), the worker
+ `workers/agent-orders`, and the Orders wallet-hub tab `src/agent-wallet-hub/tabs/orders.js`.
+- Live holding sizing: `getHolding` in `workers/agent-orders/market.js`.
+- Execution + guards: `executeAgentTrade` (`api/agents/agent-trade.js`), `agent-trade-guards.js`.
+
+## Goal
+
+A ladder is a group of linked limit-sell orders created atomically and managed as a unit (arm,
+pause, cancel all rungs). A `POST /api/agents/:id/orders/ladder` endpoint + a Ladder builder in
+the Orders tab with a live preview of each rung's expected SOL out.
+
+## What to build
+
+1. **Group model** — an `order_groups` row linking the child orders; cancel/pause cascades.
+2. **Builder** — validate rungs (rising targets, fractions summing ≤ 100%), create child limit
+ sells with `sell_pct` per rung, all referencing the group.
+3. **Coordination** — fractions are of the ORIGINAL bag; the worker sizes each fill against the
+ live holding so partial fills don't compound. Optional linked stop (OCO).
+4. **UI** — visual ladder editor (drag rungs), preview, group controls, all states.
+
+## Constraints
+
+Reuses the orders engine's real guarded fills — no new fund-moving path. Fractions can't oversell.
+Cancel of the group is instant. $THREE-only; runtime mints are data.
+
+## Success criteria
+
+A ladder arms N real linked limit sells; rungs fire in order as price rises; group cancel is
+instant; partial fills size correctly. UI renders all states; chain extended. Build/test clean.
+Changelog (feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/profit-taking-ladder.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/proof-of-holdings-card.md b/tasks/trading-frontier/next/proof-of-holdings-card.md
new file mode 100644
index 000000000..b3fd7a1c7
--- /dev/null
+++ b/tasks/trading-frontier/next/proof-of-holdings-card.md
@@ -0,0 +1,81 @@
+# Task — Proof-of-Holdings Card (verifiable portfolio snapshot + share)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+The trader profile proves a *track record* (closed-trade PnL). It does not prove what an agent
+*holds right now*. Build a **Proof-of-Holdings Card**: an opt-in, public, verifiable snapshot of an
+agent wallet's live net worth and top holdings at a timestamp — every figure independently
+re-derivable from the public chain (wallet address + block) — rendered as a beautiful shareable
+page and a dynamic OG image. Optionally anchor a hash of the snapshot on-chain so the claim is
+tamper-evident. Flexing your bag, but *honest and verifiable* — the screenshot-and-share moment the
+platform is built for.
+
+## Context (real, verified)
+
+- Live valuation (anyone can reproduce from the public address): `api/_lib/balances.js`
+ (`getBalances`, `walletUsdTotal`, `solanaMintUsdPrice`) — net worth + top holdings.
+- Public wallet read (no auth): `api/agents/solana-wallet.js#handlePublicWalletRead`; agent identity
+ `agent_identities` (name, image, is_public). OG/share infra already used for changelog + pages
+ (`public/og*`, existing card generators) and on-chain attestations (`solana_attestations`,
+ `contracts/` — see next-gen 10 attestation pattern).
+
+## Goal
+
+A snapshot service (`api/_lib/holdings-proof.js`) + a public `/api/agents/:id/holdings-proof` and a
+shareable `/agent/:id/holdings` page with a dynamic OG image, opt-in per agent, every value
+chain-verifiable, with optional on-chain hash anchoring.
+
+## What to build
+
+1. **Verifiable snapshot** — value the agent's public wallet at a captured block/timestamp into net
+ worth + ranked top holdings, with the address + block embedded so anyone can re-derive it. Opt-in
+ gated by the owner; respects `is_public`.
+2. **Optional anchor** — owner can anchor a hash of the snapshot via the existing attestation path so
+ the figure is tamper-evident; link to the on-chain proof. Never required to view.
+3. **Share surfaces** — a polished public holdings page + a dynamic OG image (net worth, top
+ holdings, agent identity) matching the platform's card style; copy/share controls.
+4. **UI** — a "Share holdings" action in the wallet hub that toggles opt-in and produces the link +
+ OG preview. All states designed (private/opt-out state, empty wallet); accessible; responsive.
+
+## Constraints
+
+- Public surface shows only what's re-derivable from the public chain; respects the agent's privacy
+ flag and owner opt-in. Real on-chain valuation only — no fabricated figures.
+- Read-only; no trades. $THREE-only rule; runtime mints are holdings data only, never promoted.
+
+## Success criteria
+
+- An owner can publish a verifiable, opt-in holdings snapshot whose net worth + top holdings are
+ re-derivable from the public chain, with a polished share page + OG image and optional anchor.
+- Share UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/proof-of-holdings-card.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/rug-loss-protection-vault.md b/tasks/trading-frontier/next/rug-loss-protection-vault.md
new file mode 100644
index 000000000..6a34a27a1
--- /dev/null
+++ b/tasks/trading-frontier/next/rug-loss-protection-vault.md
@@ -0,0 +1,93 @@
+# Task — Rug-Loss Protection Vault ($THREE mutual pool, x402-settled claims)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+The firewall clears a trade as safe — and sometimes a coin still rugs anyway. That residual risk is
+exactly what insurance is for. Build a **$THREE-denominated mutual-protection vault**: members pay a
+small premium into a shared pool, and when a member suffers a *verified* rug loss on a trade the
+firewall had cleared, the pool auto-compensates them, with premiums and claim payouts settled via
+x402. It pairs perfectly with the firewall — the firewall reduces rug frequency, the vault covers the
+tail — and creates a genuinely novel, self-funding safety net that no launchpad offers. The pool is
+$THREE-only; runtime trade mints are just the assets being insured.
+
+## Context (real, verified)
+
+- Firewall decisions: `api/_lib/trade-firewall.js` and the `firewall_decisions` record
+ (verdict/enforced) — the cleared-trade ledger that defines coverage eligibility (only trades the
+ firewall actually cleared can be claimed).
+- Loss truth: `agent_custody_events` (the audited buy/sell trail used to verify a real, realized rug
+ loss rather than a normal drawdown).
+- Settlement rail: `api/x402-pay.js` (the x402 payment path for premiums in and claim payouts out).
+- Pool denomination: **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — the only coin the
+ vault holds or pays in.
+
+## Goal
+
+A mutual-protection pool with $THREE-denominated membership/premiums, an automated claims engine that
+verifies rug losses against firewall + custody records, and x402-settled premium collection and
+payouts, all transparent and solvency-aware.
+
+## What to build
+
+1. **Vault + membership** — a $THREE-denominated pool with membership tiers, premium schedule, and a
+ live, auditable pool balance + solvency ratio; premiums collected via `api/x402-pay.js`.
+2. **Coverage rules** — only trades present in `firewall_decisions` with a cleared verdict are
+ eligible; coverage caps per trade and per member to keep the pool solvent.
+3. **Automated claims engine** — verify a claimed rug against `agent_custody_events` (real realized
+ loss) + on-chain evidence (e.g. liquidity pull / honeypot), distinguish a rug from an ordinary
+ loss, and auto-approve/deny with a transparent reason.
+4. **x402 payouts** — settle approved claims to the member via `api/x402-pay.js`, recording the
+ payout and updating pool solvency.
+5. **UI** — a vault page: join/premium flow, live pool solvency, your coverage, a file-claim flow
+ with evidence, and a public claims ledger. All states designed; responsive; accessible.
+6. **Solvency safeguards** — pause new coverage / scale payouts if the solvency ratio dips below a
+ floor; never promise a payout the pool can't fund.
+
+## Constraints
+
+- Coverage is gated on cleared `firewall_decisions`; loss verification reads `agent_custody_events`;
+ any vault-triggered trade honors spend guards (`api/_lib/agent-trade-guards.js`) and the firewall
+ (`api/_lib/trade-firewall.js`).
+- The vault holds and pays exclusively in **$THREE** — the only promoted coin; insured runtime mints
+ are trade data only, never recommended.
+- No mocks, stubs, or fake claims — real firewall/custody records and real x402 settlement only.
+
+## Success criteria
+
+- Reachable in the UI as a vault page; a member really joins (premium via x402), a verified rug on a
+ firewall-cleared trade auto-pays a real x402 $THREE claim, and pool solvency updates live.
+- Real `firewall_decisions` / `agent_custody_events` / x402 data; guard-honored, custody-audited.
+- All states designed; responsive at 320/768/1440; accessible (ARIA, keyboard, focus, contrast,
+ reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/rug-loss-protection-vault.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/token-approval-security-scanner.md b/tasks/trading-frontier/next/token-approval-security-scanner.md
new file mode 100644
index 000000000..0524b00bf
--- /dev/null
+++ b/tasks/trading-frontier/next/token-approval-security-scanner.md
@@ -0,0 +1,83 @@
+# Task — Token-Approval & Authority Security Scanner
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+The rug/honeypot firewall (next-gen 01) protects the *coin you're about to buy*. Nothing protects
+*your own wallet's standing approvals*. An agent that trades constantly accumulates SPL token
+**delegates** (an approved spender that can move your tokens) and sits under mints with live
+freeze/mint authorities — classic drain and rug vectors. Build a **Wallet Security Scanner**: audit
+the agent wallet's token accounts for active delegate approvals, flag tokens whose mint retains
+freeze/mint authority, score the wallet's attack surface, and one-click **revoke** any approval —
+signed through the same custody guards. A standing self-defense layer for the wallet itself.
+
+## Context (real, verified)
+
+- Token accounts (delegate, owner, mint) come from `getParsedTokenAccountsByOwner` already used in
+ `api/agents/solana-wallet.js#handleHoldings` (parsed `info.delegate`, `info.delegatedAmount`).
+ Mint authorities come from `getMint` (already imported there: `mintAuthority`, `freezeAuthority`).
+- Revoke = an SPL `revoke` (or set-delegate-to-none) instruction signed server-side via
+ `recoverSolanaAgentKeypair`; audited in `agent_custody_events`; CSRF + spend-guard pattern from
+ the withdraw handler in the same file.
+- Hub mount + tokens: `src/agent-wallet-hub/` (registry, tabs, util).
+
+## Goal
+
+A scanner service (`api/_lib/wallet-security.js`) + `/api/agents/:id/solana/security` (GET audit,
+POST revoke) that surfaces delegate approvals + authority risk and executes a guarded revoke,
+shown as a Security panel in the wallet hub.
+
+## What to build
+
+1. **Approval + authority audit** — enumerate token accounts with a non-null delegate (and the
+ delegated amount), and mints that still carry freeze/mint authority; produce a per-risk list and
+ a 0–100 wallet attack-surface score with plain-language reasons.
+2. **Guarded revoke** — POST executes a CSRF-protected, owner-authenticated `revoke` for selected
+ delegates (server-signed), idempotent, audited in `agent_custody_events`; simulate-first preview.
+3. **API** — GET returns the audit (risks, score, recommended actions); POST returns revoke
+ signatures + the new clean state. Rate-limited.
+4. **UI** — a Security panel: attack-surface score header, a list of risky approvals/authorities
+ with explanation, and a confirmed Revoke action per item. All states designed (empty = "no risky
+ approvals"); accessible; responsive.
+
+## Constraints
+
+- Read-then-act with explicit per-item confirm; never revoke without selection; full custody audit.
+- All signing through existing custody guards/CSRF; idempotent; honest failure handling. Real chain only.
+- $THREE-only rule; runtime mints are wallet data only.
+
+## Success criteria
+
+- The scanner correctly surfaces real delegate approvals + authority risks and executes a guarded,
+ audited revoke that demonstrably clears the approval on-chain.
+- Security UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature, security). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/token-approval-security-scanner.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/trading-discipline-coach.md b/tasks/trading-frontier/next/trading-discipline-coach.md
new file mode 100644
index 000000000..330cd90e0
--- /dev/null
+++ b/tasks/trading-frontier/next/trading-discipline-coach.md
@@ -0,0 +1,83 @@
+# Task — Trading-Discipline Coach (behavioral pattern engine)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+Portfolio analytics (trading-frontier 03) tells you *what* your numbers are. It never tells you
+*what you keep doing wrong*. Build a **Trading-Discipline Coach**: a behavioral engine that mines
+the agent's own trade history for the classic destructive patterns — the disposition effect (cutting
+winners fast, holding losers long), revenge-trading after a loss, position-size escalation on tilt,
+overtrading/churn, and chasing green candles — quantifies each as a measurable habit, and issues
+specific, data-backed nudges ("your average winner is held 18s, your average loser 4m — you're
+selling winners 13× faster"). A trading psychologist built from on-chain truth, not vibes.
+
+## Context (real, verified)
+
+- Trade history with hold windows + P&L: `agent_sniper_positions` via `api/_lib/trader-stats.js`
+ (`fetchTraderPositions`; `opened_at`/`closed_at`, `realized_pnl_pct`, `entry_quote_lamports`,
+ `exit_reason`). The existing `computeTraderMetrics` already derives win/loss hold times, churn,
+ avg win/loss % — extend it; do not duplicate it.
+- Inter-trade timing (revenge/tilt) from ordering by `opened_at` and the prior trade's outcome;
+ discretionary fills via `api/agents/solana-trade.js`.
+
+## Goal
+
+A behavioral engine (`api/_lib/discipline-coach.js`) + `/api/agents/:id/discipline` that scores
+named habits from real history and emits prioritized, evidence-cited nudges, surfaced as a Coach
+panel in the wallet hub / trader profile.
+
+## What to build
+
+1. **Pattern detectors** — pure, test-pinned detectors over position rows: disposition-effect ratio
+ (winner-hold vs loser-hold), revenge-trade rate (size/frequency spike right after a loss),
+ size-escalation-on-tilt, overtrading/churn, and chase rate. Each yields a measured value + a
+ severity.
+2. **Nudges** — translate detector outputs into ranked, plain-language, evidence-backed
+ recommendations with the exact numbers that triggered them; survivorship-honest, never preachy.
+3. **API** — `/api/agents/:id/discipline?window=` returns the habit scores + ranked nudges; cached;
+ degrades honestly when sample size is too small to judge (says so).
+4. **UI** — a Coach panel: a discipline score header, habit cards (each with its measured metric +
+ trend), and a prioritized nudge list. All states designed (empty/low-confidence for a fresh
+ wallet); accessible; responsive.
+
+## Constraints
+
+- Every nudge is backed by a real computed number from the agent's history — no generic advice.
+- Read-only reflection; no trades initiated. Confidence-gated like the existing score model.
+- $THREE-only rule; runtime mints are trade data only.
+
+## Success criteria
+
+- The coach detects real behavioral patterns from history and emits specific, number-backed nudges,
+ with honest low-confidence handling for small samples.
+- Coach UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/trading-discipline-coach.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/triggered-order-sequences.md b/tasks/trading-frontier/next/triggered-order-sequences.md
new file mode 100644
index 000000000..5495ca0fc
--- /dev/null
+++ b/tasks/trading-frontier/next/triggered-order-sequences.md
@@ -0,0 +1,75 @@
+# Triggered Order Sequences (chain orders: when one fills, auto-arm the next)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+## The invention
+
+A single order is a point; a real trade plan is a sequence. Triggered Order Sequences let you chain
+orders by dependency: *when this one fills, automatically arm the next.* "Limit-buy 0.5 SOL at
+$30k mcap → once filled, arm a take-profit ladder and a stop." "DCA in over 6 slices → when the
+last slice fills, arm a trailing stop on the whole bag." It's the missing control-flow layer over
+the programmable-orders engine — sequential dependency, distinct from OCO (mutual cancel) and the
+profit-taking ladder (parallel rungs). Set the whole plan once; the worker advances it as fills land.
+
+## Context (real, verified)
+
+- Orders engine: `api/_lib/orders.js` (every order type + `order_fills`), the evaluation worker
+ `workers/agent-orders/sweep.js` (fills are recorded + advanced here — the natural place to fire
+ the next step), and the Orders wallet-hub tab `src/agent-wallet-hub/tabs/orders.js`.
+- Execution + guards: `executeAgentTrade` (`api/agents/agent-trade.js`), `agent-trade-guards.js`.
+- Custody audit: `agent_custody_events`. Distinct from OCO (`next/oco-bracket-orders.md`) and the
+ ladder (`next/profit-taking-ladder.md`).
+
+## Goal
+
+A sequence model where child orders carry an `arm_on` dependency (parent order + event = `filled`),
+a worker step that arms the next child when its parent fills, and a sequence builder + visual
+dependency view in the Orders tab.
+
+## What to build
+
+1. **Sequence model** — `order_sequences` + a `depends_on`/`arm_on` link on child orders; children
+ start in a `staged` (not-yet-armed) state and become `active` only when the parent event fires.
+2. **Advancer** — in the fill path, when an order reaches `filled`, atomically arm its dependents
+ (idempotent; a crash can't double-arm or skip). Cancelling/expiring a parent cascades to staged
+ children.
+3. **Composition** — support common templates (entry → bracket, DCA → trailing) as one-click chains
+ built from real child orders.
+4. **UI** — a sequence builder showing the dependency graph, per-step status, and group controls;
+ all states designed (staged, active, fired, cancelled).
+
+## Constraints
+
+Reuses the orders engine's real, guarded, audited fills — no new fund-moving path. Staged orders
+never fire before their trigger. Dependency advance is idempotent + crash-safe. Cancel of the
+sequence is instant. $THREE-only; runtime mints are data.
+
+## Success criteria
+
+A multi-step sequence arms its first order, advances to the next when that fills, and cascades a
+cancel — all through real guarded fills, fully audited. UI renders the graph + all states; chain
+extended. Build/typecheck/test clean. Changelog (feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/triggered-order-sequences.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/verifiable-onchain-backtest-attestation.md b/tasks/trading-frontier/next/verifiable-onchain-backtest-attestation.md
new file mode 100644
index 000000000..d55d02812
--- /dev/null
+++ b/tasks/trading-frontier/next/verifiable-onchain-backtest-attestation.md
@@ -0,0 +1,90 @@
+# Task — Verifiable On-Chain Backtest Attestation (trustlessly replayable strategy proofs)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+Every trading platform lets people claim returns; none let anyone *verify* them. Build **verifiable
+on-chain backtest attestations**: when a user backtests a strategy with the NL strategy compiler,
+publish the result — a deterministic strategy hash, the exact data window, and the headline metrics
+(return, Sharpe, max drawdown, win rate) — as a signed attestation on Solana and as an ERC-8004
+validation record. Anyone can take the strategy hash + window, re-run the same backtest, and confirm
+the published numbers match. It turns "trust me, my bot is up 4x" into a cryptographically anchored,
+replayable claim — the trust layer for the entire signal marketplace and arena.
+
+## Context (real, verified)
+
+- Strategy + backtest source: `tasks/next-gen-trading/05` (the NL strategy compiler + backtester)
+ produces the strategy definition and deterministic backtest the attestation certifies.
+- Solana attestations: the `solana_attestations` table (the existing attestation store to write the
+ proof record into).
+- ERC-8004 validation: `contracts/src/ValidationRegistry.sol` and `api/erc8004/*`
+ (`[action].js`, `register-confirm.js`) for cross-chain validation-record publishing.
+
+## Goal
+
+A pipeline that takes a completed backtest, derives a deterministic strategy hash + metrics digest,
+publishes it as a Solana attestation and an ERC-8004 validation record, and offers a public verify
+flow that re-runs the backtest and confirms the published numbers.
+
+## What to build
+
+1. **Deterministic strategy hash + digest** — canonicalize the compiled strategy + data window from
+ `tasks/next-gen-trading/05` into a stable hash, and hash the metrics digest so any tamper is
+ detectable.
+2. **Dual-chain publish** — write the attestation to `solana_attestations` and submit an ERC-8004
+ validation record via `api/erc8004/*` / `ValidationRegistry.sol`, linking both to the strategy hash.
+3. **Trustless replay/verify** — a public verify endpoint + UI that, given a strategy hash, re-runs
+ the backtest over the same window and reports match / mismatch with the on-chain record.
+4. **Attestation badge + profile surface** — render a "verified backtest" badge (Solscan +
+ validation-registry links) on agent profiles and signal-marketplace listings.
+5. **UI** — a verify panel: paste/select a strategy hash, see the published metrics, run the replay,
+ and view the match result with the chain links. All states designed; responsive; accessible.
+6. **Tamper handling** — if a replay diverges, show exactly which metric drifted and by how much; an
+ unverifiable claim is clearly marked, never silently passed.
+
+## Constraints
+
+- Any execution triggered from a verified strategy still honors spend guards
+ (`api/_lib/agent-trade-guards.js`), custody audit (`agent_custody_events`), and the firewall
+ (`api/_lib/trade-firewall.js`) on buys — attestation never bypasses live-trade safety.
+- $THREE is the only promoted coin; mints inside attested backtests are trade data only.
+- No mocks, stubs, or fake attestations — real Solana writes and real ERC-8004 records only.
+
+## Success criteria
+
+- Reachable in the UI; a real backtest produces a real Solana attestation + ERC-8004 record, and an
+ independent replay verifies the published numbers.
+- Real `solana_attestations` writes + real `ValidationRegistry` records via `api/erc8004/*`.
+- All states designed; responsive at 320/768/1440; accessible (ARIA, keyboard, focus, contrast,
+ reduced-motion).
+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entry (tags:
+ feature); completionist passes; chain extended with 10 new registered prompts.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/verifiable-onchain-backtest-attestation.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/volatility-adaptive-stops.md b/tasks/trading-frontier/next/volatility-adaptive-stops.md
new file mode 100644
index 000000000..c51c53121
--- /dev/null
+++ b/tasks/trading-frontier/next/volatility-adaptive-stops.md
@@ -0,0 +1,69 @@
+# Volatility-Adaptive Stops (ATR-style stop sizing from live price history)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+
+## The invention
+
+A fixed 20% stop is wrong for both a sleepy coin and a 10×-a-minute rocket. This computes each
+coin's realized volatility from the platform's own price-point history and recommends (or
+auto-sets) a trailing/stop distance scaled to that volatility — a memecoin ATR. Tight stops on
+calm coins, room to breathe on volatile ones, all from real data.
+
+## Context (real, verified)
+
+- Price time series: `pump_agent_price_points` (`sol_per_token`, `market_cap_lamports`, `source`),
+ written by `api/cron/pump-agent-stats.js`; live stats `pump_agent_stats`.
+- Stops/trailing live in `api/_lib/orders.js` (`trail_pct`, `stop_price`) + `workers/agent-orders`.
+- Orders tab `src/agent-wallet-hub/tabs/orders.js` is where the recommendation surfaces.
+
+## Goal
+
+A volatility estimator over `pump_agent_price_points` exposed as `GET /api/agents/:id/volatility?
+mint=…`, and an "adaptive stop" toggle on trailing/stop orders that sizes the distance from live
+volatility (with the chosen number always shown before arming).
+
+## What to build
+
+1. **Estimator** — realized volatility / ATR-style measure from the recent price-point window;
+ honest when too few points exist (no fabricated stop).
+2. **Recommendation** — map volatility → suggested trail/stop %, with a transparent explanation.
+3. **Orders integration** — an opt-in adaptive mode that fills `trail_pct`/`stop_price` from the
+ estimate at create time (and optionally re-evaluates), never silently.
+4. **UI** — show the coin's volatility + the suggested distance in the order builder; all states.
+
+## Constraints
+
+Real history only; degrade clearly when data is thin. The user always sees + confirms the chosen
+stop. Fills stay guarded. $THREE-only; runtime mints are data.
+
+## Success criteria
+
+Stop/trail distances are sized from real per-coin volatility, shown before arming, and fire
+correctly through the orders engine. Chain extended. Build/test clean. Changelog (feature).
+Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/volatility-adaptive-stops.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/next/watchlist-wallet-triggers.md b/tasks/trading-frontier/next/watchlist-wallet-triggers.md
new file mode 100644
index 000000000..7aed13487
--- /dev/null
+++ b/tasks/trading-frontier/next/watchlist-wallet-triggers.md
@@ -0,0 +1,73 @@
+# Watchlist Wallet Triggers (fire orders when a tracked wallet moves)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+
+## The invention
+
+The sharpest signal in memecoins is what a specific wallet does. This adds a personal watchlist
+of on-chain wallets and a NEW conditional-order signal: "fire when any wallet on my watchlist
+has net-bought (or net-sold) this coin." Pair it with the orders engine and you get
+"auto-buy 0.2 SOL when <smart wallet> enters" — without copying a whole wallet (that's the
+external mirror); this is a targeted, per-order trigger over real ledger data.
+
+## Context (real, verified)
+
+- Per-coin per-wallet ledger: `pump_coin_wallets` (buy/sell lamports, `is_creator`); wallet
+ reputation: `smart_wallet_reputation`; reader: `api/_lib/smart-money.js` (`getSmartMoneyForMint`).
+- Conditional signals live in `api/_lib/orders.js` (`CONDITION_SIGNALS`) + evaluated in
+ `workers/agent-orders/market.js` (`getSignals`). The Orders tab builds conditions.
+- Distinct from the external Universal Wallet Mirror (trading-frontier/07).
+
+## Goal
+
+A per-agent `wallet_watchlist` + a new `watchlist_buy` / `watchlist_sell` conditional signal the
+orders worker evaluates from `pump_coin_wallets`, plus watchlist management + use in the Orders
+condition builder.
+
+## What to build
+
+1. **Watchlist model** — `wallet_watchlist` (agent_id, address, label) + CRUD endpoint, validated
+ Solana addresses.
+2. **Signal** — extend the closed condition vocabulary with `watchlist_buy`/`watchlist_sell`
+ (bool), computed by joining the order's mint against `pump_coin_wallets` for watchlisted
+ addresses; honest null when the ledger has no data yet.
+3. **UI** — manage the watchlist; the Orders condition builder offers the new signals.
+4. **Backfill** — ensure `pump_coin_wallets` is populated for the mints in question (document the
+ ingestion path; never fabricate rows).
+
+## Constraints
+
+Signals from REAL ledger data only; never fire on absent data. Validated, code-free conditions.
+Fills stay firewall + spend-guard gated. $THREE-only; runtime mints are data.
+
+## Success criteria
+
+A watchlisted wallet net-buying a coin fires a conditional order through the guarded path; the
+watchlist UI works; signals never fire on gaps. Chain extended. Build/test clean. Changelog
+(feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/next/watchlist-wallet-triggers.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tests/agent-sniper-radar.test.js b/tests/agent-sniper-radar.test.js
new file mode 100644
index 000000000..fbf7ec8a1
--- /dev/null
+++ b/tests/agent-sniper-radar.test.js
@@ -0,0 +1,231 @@
+import { describe, it, expect } from 'vitest';
+import bs58 from 'bs58';
+import { scoreRadarEvent } from '../workers/agent-sniper/radar-scorer.js';
+import { parseCreateMint, parseFundingTransfers, classifyTransaction } from '../workers/agent-sniper/radar-detect.js';
+import { curateWatchlist } from '../workers/agent-sniper/radar-watchlist.js';
+import { PUMP_PROGRAM_ID, CREATE_DISCRIMINATOR, CREATE_V2_DISCRIMINATOR } from '../api/_lib/solana/programs.js';
+
+// Synthetic placeholder addresses only — never a real mint/wallet.
+const MINT = 'THREEsynthetic1111111111111111111111111111111';
+const WATCHED = 'Watched1111111111111111111111111111111111111';
+const FRESH = 'FreshWa11et2222222222222222222222222222222222';
+
+const cfg = {
+ radarMaxAgeMs: 120_000,
+ radarMinCreatorGraduated: 2,
+ radarSmartMoneyMinScore: 70,
+};
+
+function ev(overrides = {}) {
+ return {
+ kind: 'create',
+ trigger_wallet: WATCHED,
+ mint: MINT,
+ signature: 'sig_radar_1',
+ base_confidence: 0.9,
+ observed_ms: Date.now(),
+ watch: { reason: 'creator_graduated', score: 70, creator_graduated: 3, labels: ['creator'] },
+ ...overrides,
+ };
+}
+
+describe('scoreRadarEvent — pre-launch radar entry filter', () => {
+ it('skips an event with no mint', () => {
+ const r = scoreRadarEvent(ev({ mint: null }), {}, cfg);
+ expect(r.pass).toBe(false);
+ expect(r.reasons).toContain('no_mint');
+ });
+
+ it('passes a proven-creator precursor with default gates', () => {
+ const r = scoreRadarEvent(ev(), {}, cfg);
+ expect(r.pass).toBe(true);
+ expect(r.confidence).toBeGreaterThan(0.9);
+ expect(r.reasons.some((x) => x.startsWith('creator_graduated:'))).toBe(true);
+ });
+
+ it('rejects a stale precursor past radar_max_age_ms', () => {
+ const r = scoreRadarEvent(ev({ observed_ms: Date.now() - 5 * 60_000 }), { radar_max_age_ms: 60_000 }, cfg);
+ expect(r.pass).toBe(false);
+ expect(r.reasons[0]).toMatch(/precursor_stale/);
+ });
+
+ it('rejects a creator below min_creator_graduated_radar (non-smart-money watch)', () => {
+ const r = scoreRadarEvent(
+ ev({ watch: { reason: 'creator_graduated', score: 50, creator_graduated: 1, labels: ['creator'] } }),
+ { min_creator_graduated_radar: 3 },
+ cfg,
+ );
+ expect(r.pass).toBe(false);
+ expect(r.reasons[0]).toMatch(/creator_too_few_graduated/);
+ });
+
+ it('lets a smart-money-reason watch through the creator pedigree gate', () => {
+ const r = scoreRadarEvent(
+ ev({ watch: { reason: 'smart_money', score: 88, creator_graduated: null, realized_score: 88, labels: ['smart_money'] } }),
+ { min_creator_graduated_radar: 3 },
+ cfg,
+ );
+ expect(r.pass).toBe(true);
+ });
+
+ it('blocks when require_smart_money_funder is set but no proof exists', () => {
+ const r = scoreRadarEvent(
+ ev({ funder_reputation: { computed: true, realized_score: 10 } }),
+ { require_smart_money_funder: true },
+ cfg,
+ );
+ expect(r.pass).toBe(false);
+ expect(r.reasons).toContain('no_smart_money_funder');
+ });
+
+ it('passes require_smart_money_funder with a proven funder', () => {
+ const r = scoreRadarEvent(
+ ev({ funder_reputation: { computed: true, realized_score: 82, labels: ['smart_money'] } }),
+ { require_smart_money_funder: true },
+ cfg,
+ );
+ expect(r.pass).toBe(true);
+ expect(r.reasons.some((x) => x.startsWith('smart_money_funder:'))).toBe(true);
+ });
+
+ it('clamps confidence to [0,1] and lifts it with funder reputation', () => {
+ const r = scoreRadarEvent(
+ ev({ base_confidence: 0.5, funder_reputation: { computed: true, realized_score: 100 } }),
+ {},
+ cfg,
+ );
+ expect(r.confidence).toBeGreaterThan(0.5);
+ expect(r.confidence).toBeLessThanOrEqual(1);
+ });
+});
+
+// ── detection parsers ─────────────────────────────────────────────────────────
+
+function createTx({ variant = 'create', mint = MINT, inner = false } = {}) {
+ const disc = variant === 'create_v2' ? CREATE_V2_DISCRIMINATOR : CREATE_DISCRIMINATOR;
+ const data = bs58.encode(Buffer.concat([disc, Buffer.alloc(16)]));
+ const ix = { programId: PUMP_PROGRAM_ID, accounts: [mint, 'aaaa', 'bbbb'], data };
+ return {
+ meta: { err: null, innerInstructions: inner ? [{ index: 0, instructions: [ix] }] : [] },
+ transaction: { message: { instructions: inner ? [] : [ix] } },
+ };
+}
+
+function fundingTx({ from = WATCHED, to = FRESH, lamports = 50_000_000 } = {}) {
+ return {
+ meta: { err: null, innerInstructions: [] },
+ transaction: {
+ message: {
+ instructions: [
+ { program: 'system', programId: '11111111111111111111111111111111', parsed: { type: 'transfer', info: { source: from, destination: to, lamports } } },
+ ],
+ },
+ },
+ };
+}
+
+describe('parseCreateMint — pump.fun create detection', () => {
+ it('extracts the mint from an outer create instruction', () => {
+ const r = parseCreateMint(createTx());
+ expect(r).toEqual({ mint: MINT, variant: 'create' });
+ });
+
+ it('extracts the mint from a create_v2 instruction', () => {
+ const r = parseCreateMint(createTx({ variant: 'create_v2' }));
+ expect(r.variant).toBe('create_v2');
+ expect(r.mint).toBe(MINT);
+ });
+
+ it('finds a create nested in inner instructions', () => {
+ const r = parseCreateMint(createTx({ inner: true }));
+ expect(r?.mint).toBe(MINT);
+ });
+
+ it('returns null for a non-create transaction', () => {
+ expect(parseCreateMint(fundingTx())).toBeNull();
+ });
+
+ it('returns null on a failed transaction', () => {
+ const tx = createTx();
+ tx.meta.err = { InstructionError: [0, 'Custom'] };
+ expect(parseCreateMint(tx)).toBeNull();
+ });
+});
+
+describe('parseFundingTransfers — fresh deploy-wallet funding detection', () => {
+ it('detects a SOL transfer out of the watched wallet', () => {
+ const r = parseFundingTransfers(fundingTx(), WATCHED);
+ expect(r).toEqual([{ destination: FRESH, lamports: 50_000_000 }]);
+ });
+
+ it('ignores transfers not sourced from the watched wallet', () => {
+ expect(parseFundingTransfers(fundingTx({ from: 'Someone1111111111111111111111111111111111111' }), WATCHED)).toEqual([]);
+ });
+
+ it('ignores self-transfers and system/wsol destinations', () => {
+ expect(parseFundingTransfers(fundingTx({ to: WATCHED }), WATCHED)).toEqual([]);
+ expect(parseFundingTransfers(fundingTx({ to: 'So11111111111111111111111111111111111111112' }), WATCHED)).toEqual([]);
+ });
+
+ it('aggregates multiple transfers to the same destination', () => {
+ const tx = fundingTx();
+ tx.transaction.message.instructions.push({
+ program: 'system', parsed: { type: 'transfer', info: { source: WATCHED, destination: FRESH, lamports: 10_000_000 } },
+ });
+ const r = parseFundingTransfers(tx, WATCHED);
+ expect(r).toEqual([{ destination: FRESH, lamports: 60_000_000 }]);
+ });
+});
+
+describe('classifyTransaction', () => {
+ it('returns both create and fundings shape', () => {
+ const c = classifyTransaction(createTx(), WATCHED);
+ expect(c.create?.mint).toBe(MINT);
+ expect(c.fundings).toEqual([]);
+ const f = classifyTransaction(fundingTx(), WATCHED);
+ expect(f.create).toBeNull();
+ expect(f.fundings.length).toBe(1);
+ });
+});
+
+// ── watchlist curation ────────────────────────────────────────────────────────
+
+describe('curateWatchlist — merge + cap + score', () => {
+ it('scores creators by graduation count and smart money by reputation', () => {
+ const out = curateWatchlist({
+ creators: [{ address: 'C1', graduated: 4, launches: 9 }],
+ smartMoney: [{ address: 'S1', realized_score: 90, labels: ['smart_money'] }],
+ cap: 10,
+ });
+ const c1 = out.find((w) => w.address === 'C1');
+ const s1 = out.find((w) => w.address === 'S1');
+ expect(c1.reason).toBe('creator_graduated');
+ expect(c1.score).toBe(90); // 50 + 4*10, capped at 95
+ expect(c1.creator_graduated).toBe(4);
+ expect(s1.reason).toBe('smart_money');
+ expect(s1.score).toBe(90);
+ });
+
+ it('merges a wallet that is both a proven creator and smart money, keeping both signals', () => {
+ const out = curateWatchlist({
+ creators: [{ address: 'BOTH', graduated: 2, launches: 3 }],
+ smartMoney: [{ address: 'BOTH', realized_score: 95, labels: ['smart_money'] }],
+ cap: 10,
+ });
+ expect(out.length).toBe(1);
+ expect(out[0].creator_graduated).toBe(2);
+ expect(out[0].realized_score).toBe(95);
+ expect(out[0].score).toBe(95); // max of creator(70) and smart money(95)
+ expect(out[0].labels).toEqual(expect.arrayContaining(['creator', 'smart_money']));
+ });
+
+ it('drops zero-signal candidates and caps the set by score', () => {
+ const out = curateWatchlist({
+ creators: [{ address: 'C0', graduated: 0, launches: 5 }, { address: 'C1', graduated: 1, launches: 2 }],
+ smartMoney: [{ address: 'S0', realized_score: 0, labels: [] }, { address: 'S1', realized_score: 80, labels: [] }],
+ cap: 1,
+ });
+ expect(out.length).toBe(1);
+ expect(out[0].address).toBe('S1'); // highest score wins the single slot
+ });
+});
diff --git a/tests/orders-engine.test.js b/tests/orders-engine.test.js
new file mode 100644
index 000000000..3db8459a8
--- /dev/null
+++ b/tests/orders-engine.test.js
@@ -0,0 +1,201 @@
+/**
+ * Programmable Orders Engine — unit tests for the pure model + trigger logic
+ * (api/_lib/orders.js). These are the rules the API and the worker both enforce,
+ * so they're tested once, in isolation, with no DB or chain.
+ *
+ * Coverage: condition-spec validation (closed vocabulary, code-free), condition
+ * evaluation (including honest handling of missing live data), price-trigger
+ * direction for every (type, side), order normalization per type, and the
+ * human-readable description. The only mint used is $THREE (per CLAUDE.md).
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ validateCondition, evaluateCondition, conditionSignals,
+ shouldFirePrice, normalizeOrder, describeOrder,
+} from '../api/_lib/orders.js';
+
+// $THREE — the only coin this platform references.
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+describe('validateCondition', () => {
+ it('accepts a valid all-clause numeric + bool spec', () => {
+ const r = validateCondition({ all: [
+ { signal: 'smart_money_score', op: 'gte', value: 60 },
+ { signal: 'dev_dump', op: 'is_false' },
+ ] });
+ expect(r.ok).toBe(true);
+ expect(r.spec.all).toHaveLength(2);
+ expect(r.spec.all[1]).toEqual({ signal: 'dev_dump', op: 'is_false' });
+ });
+
+ it('rejects an unknown signal (closed vocabulary)', () => {
+ expect(validateCondition({ all: [{ signal: 'rsi', op: 'gt', value: 70 }] }).ok).toBe(false);
+ });
+
+ it('rejects a numeric op on a boolean signal and vice-versa', () => {
+ expect(validateCondition({ all: [{ signal: 'dev_dump', op: 'gt', value: 1 }] }).ok).toBe(false);
+ expect(validateCondition({ all: [{ signal: 'mcap_usd', op: 'is_true' }] }).ok).toBe(false);
+ });
+
+ it('rejects a non-numeric value on a numeric signal', () => {
+ expect(validateCondition({ all: [{ signal: 'mcap_usd', op: 'lt', value: 'soon' }] }).ok).toBe(false);
+ });
+
+ it('requires a non-empty all/any array and caps clause count', () => {
+ expect(validateCondition({}).ok).toBe(false);
+ expect(validateCondition({ all: [] }).ok).toBe(false);
+ const many = { all: Array.from({ length: 9 }, () => ({ signal: 'mcap_usd', op: 'lt', value: 1 })) };
+ expect(validateCondition(many).ok).toBe(false);
+ });
+
+ it('strips arbitrary keys — no code can ride along', () => {
+ const r = validateCondition({ all: [{ signal: 'mcap_usd', op: 'lt', value: 40000, evil: 'rm -rf', fn: () => {} }] });
+ expect(r.ok).toBe(true);
+ expect(Object.keys(r.spec.all[0]).sort()).toEqual(['op', 'signal', 'value']);
+ });
+});
+
+describe('evaluateCondition', () => {
+ const spec = validateCondition({ all: [
+ { signal: 'smart_money_score', op: 'gte', value: 60 },
+ { signal: 'mcap_usd', op: 'lt', value: 40000 },
+ ] }).spec;
+
+ it('fires when all clauses are satisfied', () => {
+ expect(evaluateCondition(spec, { smart_money_score: 72, mcap_usd: 30000 }).fired).toBe(true);
+ });
+
+ it('does not fire when one clause fails', () => {
+ expect(evaluateCondition(spec, { smart_money_score: 72, mcap_usd: 50000 }).fired).toBe(false);
+ });
+
+ it('treats missing data as indeterminate (never fires on a gap) and reports it', () => {
+ const r = evaluateCondition(spec, { smart_money_score: 72, mcap_usd: null });
+ expect(r.fired).toBe(false);
+ expect(r.missing).toContain('mcap_usd');
+ });
+
+ it('any-mode fires when a single present clause is true even if another is missing', () => {
+ const any = validateCondition({ any: [
+ { signal: 'graduated', op: 'is_true' },
+ { signal: 'smart_money_score', op: 'gte', value: 60 },
+ ] }).spec;
+ expect(evaluateCondition(any, { graduated: true, smart_money_score: null }).fired).toBe(true);
+ });
+
+ it('conditionSignals lists the distinct referenced signals', () => {
+ expect(conditionSignals(spec).sort()).toEqual(['mcap_usd', 'smart_money_score']);
+ });
+});
+
+describe('shouldFirePrice', () => {
+ it('limit buy fires at/below target; limit sell at/above', () => {
+ expect(shouldFirePrice({ type: 'limit', side: 'buy', limit_price: 100 }, 100)).toBe(true);
+ expect(shouldFirePrice({ type: 'limit', side: 'buy', limit_price: 100 }, 101)).toBe(false);
+ expect(shouldFirePrice({ type: 'limit', side: 'sell', limit_price: 100 }, 100)).toBe(true);
+ expect(shouldFirePrice({ type: 'limit', side: 'sell', limit_price: 100 }, 99)).toBe(false);
+ });
+
+ it('stop sell fires on a fall; stop buy on a breakout', () => {
+ expect(shouldFirePrice({ type: 'stop', side: 'sell', stop_price: 50 }, 49)).toBe(true);
+ expect(shouldFirePrice({ type: 'stop', side: 'sell', stop_price: 50 }, 51)).toBe(false);
+ expect(shouldFirePrice({ type: 'stop', side: 'buy', stop_price: 50 }, 51)).toBe(true);
+ });
+
+ it('trailing sell fires after a % drawdown from the peak', () => {
+ const o = { type: 'trailing', side: 'sell', trail_pct: 20 };
+ expect(shouldFirePrice(o, 80, 100)).toBe(true); // -20% from peak 100
+ expect(shouldFirePrice(o, 85, 100)).toBe(false); // only -15%
+ expect(shouldFirePrice(o, 80, null)).toBe(false); // no peak yet → hold
+ });
+
+ it('trailing buy fires after a % run-up from the trough', () => {
+ const o = { type: 'trailing', side: 'buy', trail_pct: 10 };
+ expect(shouldFirePrice(o, 111, 100)).toBe(true); // +11% from trough 100
+ expect(shouldFirePrice(o, 105, 100)).toBe(false); // only +5%
+ });
+
+ it('never fires on a non-finite value', () => {
+ expect(shouldFirePrice({ type: 'limit', side: 'buy', limit_price: 100 }, NaN)).toBe(false);
+ });
+});
+
+describe('normalizeOrder', () => {
+ it('validates a limit buy', () => {
+ const r = normalizeOrder({ type: 'limit', side: 'buy', mint: THREE, trigger_metric: 'mcap_usd', limit_price: 40000, size_sol: 0.25 });
+ expect(r.ok).toBe(true);
+ expect(r.order.limit_price).toBe(40000);
+ expect(r.order.size_sol).toBe(0.25);
+ });
+
+ it('rejects a bad mint', () => {
+ expect(normalizeOrder({ type: 'limit', side: 'buy', mint: 'not-a-mint', limit_price: 1, size_sol: 1 }).ok).toBe(false);
+ });
+
+ it('requires size_sol for a buy and sell sizing for a sell', () => {
+ expect(normalizeOrder({ type: 'limit', side: 'buy', mint: THREE, limit_price: 1 }).ok).toBe(false);
+ const sell = normalizeOrder({ type: 'limit', side: 'sell', mint: THREE, limit_price: 1, sell_pct: 50 });
+ expect(sell.ok).toBe(true);
+ expect(sell.order.sell_pct).toBe(50);
+ });
+
+ it('rejects sell_pct out of range', () => {
+ expect(normalizeOrder({ type: 'stop', side: 'sell', mint: THREE, stop_price: 1, sell_pct: 150 }).ok).toBe(false);
+ });
+
+ it('validates trailing trail_pct bounds', () => {
+ expect(normalizeOrder({ type: 'trailing', side: 'sell', mint: THREE, trail_pct: 0, sell_pct: 100 }).ok).toBe(false);
+ expect(normalizeOrder({ type: 'trailing', side: 'sell', mint: THREE, trail_pct: 25, sell_pct: 100 }).ok).toBe(true);
+ });
+
+ it('validates a DCA schedule and seeds filled_slices', () => {
+ const r = normalizeOrder({ type: 'dca', side: 'buy', mint: THREE, size_sol: 0.1, schedule: { interval_seconds: 3600, slices: 6 } });
+ expect(r.ok).toBe(true);
+ expect(r.order.schedule).toEqual({ interval_seconds: 3600, slices: 6, filled_slices: 0 });
+ });
+
+ it('rejects a too-frequent DCA schedule', () => {
+ expect(normalizeOrder({ type: 'dca', side: 'buy', mint: THREE, size_sol: 0.1, schedule: { interval_seconds: 5, slices: 6 } }).ok).toBe(false);
+ });
+
+ it('derives TWAP per-slice size from the total', () => {
+ const r = normalizeOrder({ type: 'twap', side: 'buy', mint: THREE, total_sol: 1, schedule: { interval_seconds: 60, slices: 4 } });
+ expect(r.ok).toBe(true);
+ expect(r.order.size_sol).toBeCloseTo(0.25, 8);
+ expect(r.order.schedule.total_sol).toBe(1);
+ });
+
+ it('requires ≥2 slices for TWAP', () => {
+ expect(normalizeOrder({ type: 'twap', side: 'buy', mint: THREE, total_sol: 1, schedule: { interval_seconds: 60, slices: 1 } }).ok).toBe(false);
+ });
+
+ it('validates a conditional order and keeps the clean spec', () => {
+ const r = normalizeOrder({ type: 'conditional', side: 'buy', mint: THREE, size_sol: 0.2, condition: { all: [{ signal: 'smart_money_score', op: 'gte', value: 60 }] } });
+ expect(r.ok).toBe(true);
+ expect(r.order.condition.all[0]).toEqual({ signal: 'smart_money_score', op: 'gte', value: 60 });
+ });
+
+ it('rejects a conditional order with an invalid condition', () => {
+ expect(normalizeOrder({ type: 'conditional', side: 'buy', mint: THREE, size_sol: 0.2, condition: { all: [{ signal: 'nope', op: 'gt', value: 1 }] } }).ok).toBe(false);
+ });
+
+ it('clamps slippage and rejects a bad expiry', () => {
+ const r = normalizeOrder({ type: 'limit', side: 'buy', mint: THREE, limit_price: 1, size_sol: 1, slippage_bps: 99999 });
+ expect(r.order.slippage_bps).toBe(5000);
+ expect(normalizeOrder({ type: 'limit', side: 'buy', mint: THREE, limit_price: 1, size_sol: 1, expires_at: 'whenever' }).ok).toBe(false);
+ });
+});
+
+describe('describeOrder', () => {
+ it('reads back each order type in plain language', () => {
+ const limit = normalizeOrder({ type: 'limit', side: 'buy', mint: THREE, symbol: 'THREE', limit_price: 40000, size_sol: 0.25 }).order;
+ expect(describeOrder(limit)).toMatch(/Buy 0.25 SOL of \$THREE when it reaches \$40,000 mcap/);
+
+ const trail = normalizeOrder({ type: 'trailing', side: 'sell', mint: THREE, symbol: 'THREE', trail_pct: 20, sell_pct: 100 }).order;
+ expect(describeOrder(trail)).toMatch(/Trailing stop.*20% drop/);
+
+ const cond = normalizeOrder({ type: 'conditional', side: 'buy', mint: THREE, symbol: 'THREE', size_sol: 0.2, condition: { all: [{ signal: 'smart_money_score', op: 'gte', value: 60 }, { signal: 'dev_dump', op: 'is_false' }] } }).order;
+ expect(describeOrder(cond)).toMatch(/Smart-money score.*≥ 60 and/);
+ });
+});
diff --git a/tests/portfolio.test.js b/tests/portfolio.test.js
new file mode 100644
index 000000000..015d3f488
--- /dev/null
+++ b/tests/portfolio.test.js
@@ -0,0 +1,167 @@
+/**
+ * Portfolio Command — pure-layer tests.
+ *
+ * buildLots, computeRisk, riskFlags, and buildAttribution are pure (no DB, no
+ * network). Every assertion is hand-computed from the fixtures so the FIFO math,
+ * the risk metrics, and the attribution can never silently drift.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { buildLots, computeRisk, riskFlags, buildAttribution } from '../api/_lib/portfolio.js';
+
+const SOL = 1_000_000_000n; // lamports per SOL
+const T = (s) => new Date(`2026-01-01T00:00:${String(s).padStart(2, '0')}.000Z`).getTime();
+
+describe('buildLots — FIFO cost basis + realized attribution', () => {
+ it('matches a full round-trip and attributes realized P&L to the lot source', () => {
+ const events = [
+ // discretionary buy 1000 raw for 1 SOL
+ { mint: 'M', source: 'discretionary', kind: 'buy', qtyRaw: 1000n, lamports: 1n * SOL, at: T(1) },
+ // discretionary sell 1000 raw for 3 SOL → +2 SOL realized
+ { mint: 'M', source: 'discretionary', kind: 'sell', qtyRaw: 1000n, lamports: 3n * SOL, at: T(2) },
+ ];
+ const { realizedBySource, remainingByMint } = buildLots(events);
+ expect(realizedBySource.get('discretionary').realizedLamports).toBe(2n * SOL);
+ expect(realizedBySource.get('discretionary').sells).toBe(1);
+ expect(remainingByMint.has('M')).toBe(false); // fully sold
+ });
+
+ it('leaves remaining lots (cost basis) when only partially sold, FIFO order', () => {
+ const events = [
+ { mint: 'M', source: 'sniper', kind: 'buy', qtyRaw: 1000n, lamports: 1n * SOL, at: T(1) }, // lot A
+ { mint: 'M', source: 'discretionary', kind: 'buy', qtyRaw: 1000n, lamports: 4n * SOL, at: T(2) }, // lot B
+ // sell 1500 → consumes all of A (1000) + 500 of B; proceeds 6 SOL over 1500
+ { mint: 'M', source: 'discretionary', kind: 'sell', qtyRaw: 1500n, lamports: 6n * SOL, at: T(3) },
+ ];
+ const { realizedBySource, remainingByMint } = buildLots(events);
+ // A: proceeds for 1000/1500 of 6 SOL = 4 SOL, cost 1 SOL → +3 SOL (source sniper)
+ expect(realizedBySource.get('sniper').realizedLamports).toBe(3n * SOL);
+ // B slice: proceeds for 500/1500 of 6 SOL = 2 SOL, cost = 4 SOL * 500/1000 = 2 SOL → 0
+ expect(realizedBySource.get('discretionary').realizedLamports).toBe(0n);
+ // remaining: 500 of B with half its cost (2 SOL)
+ const lots = remainingByMint.get('M');
+ expect(lots).toHaveLength(1);
+ expect(lots[0].qtyRaw).toBe(500n);
+ expect(lots[0].costLamports).toBe(2n * SOL);
+ expect(lots[0].source).toBe('discretionary');
+ });
+
+ it('attributes proceeds with no matching lot (deposited token) to the seller source', () => {
+ const events = [
+ { mint: 'M', source: 'discretionary', kind: 'sell', qtyRaw: 1000n, lamports: 2n * SOL, at: T(1) },
+ ];
+ const { realizedBySource, remainingByMint } = buildLots(events);
+ expect(realizedBySource.get('discretionary').realizedLamports).toBe(2n * SOL);
+ expect(remainingByMint.has('M')).toBe(false);
+ });
+
+ it('ignores events with no mint', () => {
+ const { realizedBySource } = buildLots([{ mint: null, source: 'x', kind: 'buy', qtyRaw: 1n, lamports: 1n, at: 0 }]);
+ expect(realizedBySource.size).toBe(0);
+ });
+});
+
+describe('computeRisk — concentration, exposure, drawdown', () => {
+ const metrics = { max_drawdown_pct: 42, max_drawdown_sol: 1.5 };
+ it('computes HHI, top share, and volatile exposure from valued holdings', () => {
+ const holdings = [
+ { usd: 8000, mint: 'MEME', isNative: false, stable: false }, // 80%
+ { usd: 1000, mint: null, isNative: true, stable: false }, // 10% SOL
+ { usd: 1000, mint: 'USDC', isNative: false, stable: true }, // 10% stable
+ ];
+ const r = computeRisk(holdings, 10000, metrics, [200, -50, 30, 1]);
+ expect(r.net_worth_usd).toBe(10000);
+ expect(r.top_position_pct).toBe(80);
+ expect(r.top_position_mint).toBe('MEME');
+ // HHI = .8^2 + .1^2 + .1^2 = .64 + .01 + .01 = .66
+ expect(r.concentration_hhi).toBeCloseTo(0.66, 4);
+ // volatile = only MEME (8000) / 10000 = 80%
+ expect(r.exposure_pct).toBe(80);
+ expect(r.tape_beta).toBe(0.8);
+ expect(r.max_drawdown_pct).toBe(42);
+ expect(r.valued_count).toBe(3);
+ });
+
+ it('counts unpriceable non-native holdings honestly', () => {
+ const holdings = [
+ { usd: 100, mint: null, isNative: true, stable: false },
+ { usd: null, mint: 'DEAD', isNative: false, stable: false },
+ ];
+ const r = computeRisk(holdings, 100, metrics, []);
+ expect(r.unpriceable_count).toBe(1);
+ expect(r.valued_count).toBe(1);
+ expect(r.realized_volatility_pct).toBe(0); // <2 samples
+ });
+});
+
+describe('riskFlags — plain-language flags', () => {
+ it('flags concentration, exposure, drawdown, and illiquidity', () => {
+ const risk = { top_position_pct: 85, exposure_pct: 92, max_drawdown_pct: 65, unpriceable_count: 2, net_worth_usd: 5000 };
+ const flags = riskFlags(risk, false); // top holding not priceable → illiquid
+ const texts = flags.map((f) => f.text).join(' | ');
+ expect(texts).toMatch(/85% of valued holdings sit in one illiquid position/);
+ expect(texts).toMatch(/92% of net worth is in volatile memecoins/);
+ expect(texts).toMatch(/drawdown has reached 65%/);
+ expect(texts).toMatch(/2 holdings could not be priced/);
+ expect(flags.some((f) => f.level === 'danger')).toBe(true);
+ });
+
+ it('returns an all-clear info flag when nothing is elevated', () => {
+ const risk = { top_position_pct: 20, exposure_pct: 10, max_drawdown_pct: 5, unpriceable_count: 0, net_worth_usd: 1000 };
+ const flags = riskFlags(risk, true);
+ expect(flags).toHaveLength(1);
+ expect(flags[0].level).toBe('info');
+ expect(flags[0].text).toMatch(/No elevated/);
+ });
+});
+
+describe('buildAttribution — buckets, realized + unrealized, outflows', () => {
+ it('merges realized + unrealized by source and sorts by total', () => {
+ const realizedBySource = new Map([
+ ['sniper:default', { realizedLamports: 2n * SOL, sells: 3 }],
+ ['discretionary', { realizedLamports: -1n * SOL, sells: 1 }],
+ ]);
+ const unrealizedBySource = new Map([
+ ['sniper:default', 1n * SOL],
+ ['discretionary', 1n * SOL],
+ ]);
+ const custodyRows = [
+ { category: 'x402', amount_lamports: Number(SOL / 2n), status: 'confirmed' },
+ { category: 'withdraw', amount_lamports: Number(SOL), status: 'confirmed' },
+ { category: 'trade', amount_lamports: 999, status: 'failed' }, // ignored (failed)
+ ];
+ const attr = buildAttribution({ realizedBySource, unrealizedBySource, custodyRows, solUsd: 200, hasStrategy: true });
+
+ const sniper = attr.find((a) => a.source === 'sniper');
+ expect(sniper.realized_sol).toBe(2);
+ expect(sniper.unrealized_sol).toBe(1);
+ expect(sniper.total_sol).toBe(3);
+ expect(sniper.realized_usd).toBe(400); // 2 SOL * $200
+ expect(sniper.sells).toBe(3);
+
+ const disc = attr.find((a) => a.source === 'discretionary');
+ expect(disc.total_sol).toBe(0); // -1 realized + 1 unrealized
+
+ const x402 = attr.find((a) => a.source === 'x402');
+ expect(x402.is_outflow).toBe(true);
+ expect(x402.spent_sol).toBe(0.5);
+
+ const withdraw = attr.find((a) => a.source === 'withdraw');
+ expect(withdraw.spent_sol).toBe(1);
+
+ // sorted by total_sol desc → sniper (3) first
+ expect(attr[0].source).toBe('sniper');
+ });
+
+ it('omits USD when no SOL price is available', () => {
+ const attr = buildAttribution({
+ realizedBySource: new Map([['discretionary', { realizedLamports: SOL, sells: 1 }]]),
+ unrealizedBySource: new Map(),
+ custodyRows: [],
+ solUsd: null,
+ hasStrategy: false,
+ });
+ expect(attr[0].realized_sol).toBe(1);
+ expect(attr[0].realized_usd).toBe(null);
+ });
+});
diff --git a/tests/signal-engine.test.js b/tests/signal-engine.test.js
new file mode 100644
index 000000000..435784e6d
--- /dev/null
+++ b/tests/signal-engine.test.js
@@ -0,0 +1,126 @@
+/**
+ * Signal marketplace engine — pure logic tests.
+ *
+ * Money-adjacent + reputation-adjacent: pin the outcome classification, the
+ * conviction/sizing math (a runaway "size_multiple" can never push a subscriber's
+ * order past its cap), and the confidence-regressed feed-edge score (a thin feed
+ * riding one lucky call can never out-rank a deep, consistent one).
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ classifyOutcome, computeSizeMultiple, computeConviction, subscriberOrderSol,
+ feedEdgeScore, rankFeeds, FEED_SORTS,
+} from '../api/_lib/signal-engine.js';
+
+describe('classifyOutcome', () => {
+ it('classifies clear wins and losses by sign', () => {
+ expect(classifyOutcome(42)).toBe('win');
+ expect(classifyOutcome(-30)).toBe('loss');
+ });
+ it('treats a near-zero result as flat, not a win', () => {
+ expect(classifyOutcome(0)).toBe('flat');
+ expect(classifyOutcome(0.5)).toBe('flat');
+ expect(classifyOutcome(-0.9)).toBe('flat');
+ expect(classifyOutcome(1.01)).toBe('win');
+ });
+ it('returns null for missing / non-finite input', () => {
+ expect(classifyOutcome(null)).toBeNull();
+ expect(classifyOutcome(undefined)).toBeNull();
+ expect(classifyOutcome(NaN)).toBeNull();
+ });
+});
+
+describe('computeSizeMultiple', () => {
+ it('1.0 when the entry equals the trader\'s typical size', () => {
+ expect(computeSizeMultiple(0.3, 0.3)).toBe(1);
+ });
+ it('scales linearly with the bet size', () => {
+ expect(computeSizeMultiple(0.9, 0.3)).toBe(3);
+ expect(computeSizeMultiple(0.15, 0.3)).toBe(0.5);
+ });
+ it('defaults to 1 when there is no reference or no entry', () => {
+ expect(computeSizeMultiple(0.3, 0)).toBe(1);
+ expect(computeSizeMultiple(0, 0.3)).toBe(1);
+ });
+});
+
+describe('computeConviction', () => {
+ it('a typical-size bet is mid conviction, a 3x+ bet is max', () => {
+ expect(computeConviction(1)).toBeCloseTo(0.333, 2);
+ expect(computeConviction(3)).toBe(1);
+ expect(computeConviction(5)).toBe(1); // clamped
+ });
+ it('is 0 for a non-positive multiple', () => {
+ expect(computeConviction(0)).toBe(0);
+ expect(computeConviction(-2)).toBe(0);
+ });
+});
+
+describe('subscriberOrderSol', () => {
+ it('sizes base × multiple × scaling', () => {
+ expect(subscriberOrderSol({ baseSol: 0.05, sizeMultiple: 2, sizeScaling: 1, maxPerTradeSol: 1 })).toBe(0.1);
+ expect(subscriberOrderSol({ baseSol: 0.05, sizeMultiple: 2, sizeScaling: 3, maxPerTradeSol: 1 })).toBe(0.3);
+ });
+ it('hard-caps at max_per_trade no matter how convicted the signal', () => {
+ // 0.05 × 10 × 5 = 2.5 SOL, but the cap is 0.25.
+ expect(subscriberOrderSol({ baseSol: 0.05, sizeMultiple: 10, sizeScaling: 5, maxPerTradeSol: 0.25 })).toBe(0.25);
+ });
+ it('returns 0 (skip) for a dust-sized order', () => {
+ expect(subscriberOrderSol({ baseSol: 0.001, sizeMultiple: 1, sizeScaling: 1, maxPerTradeSol: 1 })).toBe(0);
+ });
+});
+
+describe('feedEdgeScore — confidence regression', () => {
+ it('a thin feed cannot reach the score its raw stats imply', () => {
+ // One perfect signal: hit-rate 1.0, +80% ROI — but only 1 closed signal.
+ const thin = feedEdgeScore({ closedSignals: 1, winningSignals: 1, avgRealizedPct: 80, publisherScore: 50 });
+ // A deep feed with identical edge over 30 closed signals.
+ const deep = feedEdgeScore({ closedSignals: 30, winningSignals: 30, avgRealizedPct: 80, publisherScore: 50 });
+ expect(deep).toBeGreaterThan(thin);
+ expect(thin).toBeLessThan(75); // regressed toward the blended neutral
+ expect(deep).toBeGreaterThan(85);
+ });
+ it('a strongly-verified publisher lifts a thin feed via the prior', () => {
+ const lowPrior = feedEdgeScore({ closedSignals: 2, winningSignals: 2, avgRealizedPct: 40, publisherScore: 20 });
+ const highPrior = feedEdgeScore({ closedSignals: 2, winningSignals: 2, avgRealizedPct: 40, publisherScore: 95 });
+ expect(highPrior).toBeGreaterThan(lowPrior);
+ });
+ it('losers drag the score below a coin-flip feed', () => {
+ const winning = feedEdgeScore({ closedSignals: 20, winningSignals: 16, avgRealizedPct: 25, publisherScore: 60 });
+ const losing = feedEdgeScore({ closedSignals: 20, winningSignals: 4, avgRealizedPct: -20, publisherScore: 60 });
+ expect(winning).toBeGreaterThan(losing);
+ });
+ it('is bounded to 0..100', () => {
+ const hi = feedEdgeScore({ closedSignals: 100, winningSignals: 100, avgRealizedPct: 9999, publisherScore: 100 });
+ const lo = feedEdgeScore({ closedSignals: 100, winningSignals: 0, avgRealizedPct: -9999, publisherScore: 0 });
+ expect(hi).toBeLessThanOrEqual(100);
+ expect(lo).toBeGreaterThanOrEqual(0);
+ });
+});
+
+describe('rankFeeds', () => {
+ const feeds = [
+ { slug: 'a', edge_score: 40, closed_signals: 5, avg_realized_pct: 10, hit_rate: 0.5, subscribers: 9, created_at: '2026-01-01' },
+ { slug: 'b', edge_score: 80, closed_signals: 30, avg_realized_pct: 35, hit_rate: 0.7, subscribers: 2, created_at: '2026-02-01' },
+ { slug: 'c', edge_score: 60, closed_signals: 12, avg_realized_pct: 60, hit_rate: 0.6, subscribers: 5, created_at: '2026-03-01' },
+ ];
+ it('ranks by proven edge by default and assigns 1-based ranks', () => {
+ const ranked = rankFeeds(feeds, 'edge');
+ expect(ranked.map((f) => f.slug)).toEqual(['b', 'c', 'a']);
+ expect(ranked.map((f) => f.rank)).toEqual([1, 2, 3]);
+ });
+ it('ranks by ROI, hit-rate, and subscribers when asked', () => {
+ expect(rankFeeds(feeds, 'roi').map((f) => f.slug)).toEqual(['c', 'b', 'a']);
+ expect(rankFeeds(feeds, 'hitrate').map((f) => f.slug)).toEqual(['b', 'c', 'a']);
+ expect(rankFeeds(feeds, 'subscribers').map((f) => f.slug)).toEqual(['a', 'c', 'b']);
+ });
+ it('never ranks by follower count under the default sort', () => {
+ // Feed "a" has the most subscribers but the worst edge — it stays last.
+ expect(rankFeeds(feeds, 'edge')[2].slug).toBe('a');
+ });
+ it('exposes its sort vocabulary', () => {
+ expect(FEED_SORTS.has('edge')).toBe(true);
+ expect(FEED_SORTS.has('subscribers')).toBe(true);
+ });
+});
diff --git a/tests/swarms.test.js b/tests/swarms.test.js
new file mode 100644
index 000000000..70757fc9c
--- /dev/null
+++ b/tests/swarms.test.js
@@ -0,0 +1,92 @@
+/**
+ * Trading-swarm pure logic — consensus tally + policy normalization.
+ *
+ * computeConsensus and normalizeSwarmPolicy are pure (no DB, no network), so the
+ * reputation-weighting math and the policy guardrails are asserted directly here.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { computeConsensus, normalizeSwarmPolicy } from '../api/_lib/swarms.js';
+
+describe('computeConsensus', () => {
+ const members = [
+ { agent_id: 'a', name: 'A', reputation: 80 }, // proven
+ { agent_id: 'b', name: 'B', reputation: 40 },
+ { agent_id: 'c', name: 'C', reputation: 0 }, // no track record → floor weight 5
+ ];
+ const policy = normalizeSwarmPolicy({});
+
+ it('weights agreement by reputation, not headcount', () => {
+ // Only the proven member (weight 80) is long; total weight = 80+40+5 = 125.
+ const r = computeConsensus({ members, longAgentIds: ['a'], policy });
+ expect(r.members_long).toBe(1);
+ expect(r.members_total).toBe(3);
+ expect(r.consensus).toBeCloseTo(80 / 125, 5);
+ });
+
+ it('reaches full consensus when every member is long', () => {
+ const r = computeConsensus({ members, longAgentIds: ['a', 'b', 'c'], policy });
+ expect(r.consensus).toBe(1);
+ });
+
+ it('gives a zero-reputation member a non-zero floor weight', () => {
+ // Only C (rep 0 → weight 5) long → 5/125.
+ const r = computeConsensus({ members, longAgentIds: ['c'], policy });
+ expect(r.consensus).toBeCloseTo(5 / 125, 5);
+ expect(r.consensus).toBeGreaterThan(0);
+ });
+
+ it('lets smart-money lift conviction above raw consensus but never above 1', () => {
+ const base = computeConsensus({ members, longAgentIds: ['a'], smartMoneyScore: 0, policy });
+ const lifted = computeConsensus({ members, longAgentIds: ['a'], smartMoneyScore: 100, policy });
+ expect(lifted.conviction).toBeGreaterThan(base.conviction);
+ expect(lifted.conviction).toBeLessThanOrEqual(1);
+ // Consensus itself is unchanged — smart-money scales conviction, not the vote.
+ expect(lifted.consensus).toBe(base.consensus);
+ });
+
+ it('returns zero with no members', () => {
+ const r = computeConsensus({ members: [], longAgentIds: [], policy });
+ expect(r.consensus).toBe(0);
+ expect(r.conviction).toBe(0);
+ });
+
+ it('emits a per-member breakdown for the audit log', () => {
+ const r = computeConsensus({ members, longAgentIds: ['a', 'b'], policy });
+ expect(r.breakdown).toHaveLength(3);
+ expect(r.breakdown.find((x) => x.agent_id === 'a').long).toBe(true);
+ expect(r.breakdown.find((x) => x.agent_id === 'c').long).toBe(false);
+ });
+});
+
+describe('normalizeSwarmPolicy', () => {
+ it('applies sane defaults', () => {
+ const p = normalizeSwarmPolicy({});
+ expect(p.min_consensus).toBe(0.6);
+ expect(p.creator_fee_bps).toBe(0);
+ expect(p.max_member_share_bps).toBe(5000);
+ expect(p.exit_policy).toBe('settle_at_mark');
+ expect(p.join_open).toBe(true);
+ expect(p.firewall_level).toBe('block');
+ });
+
+ it('clamps min_consensus into [0.05, 1]', () => {
+ expect(normalizeSwarmPolicy({ min_consensus: 5 }).min_consensus).toBe(1);
+ expect(normalizeSwarmPolicy({ min_consensus: -1 }).min_consensus).toBe(0.05);
+ });
+
+ it('caps the creator fee at 20% and the member share floor at 10%', () => {
+ expect(normalizeSwarmPolicy({ creator_fee_bps: 9999 }).creator_fee_bps).toBe(2000);
+ expect(normalizeSwarmPolicy({ max_member_share_bps: 1 }).max_member_share_bps).toBe(1000);
+ });
+
+ it('never lets the daily budget fall below one max-per-trade', () => {
+ const p = normalizeSwarmPolicy({ max_per_trade_lamports: 100_000_000, daily_budget_lamports: 1 });
+ expect(BigInt(p.daily_budget_lamports)).toBeGreaterThanOrEqual(BigInt(p.max_per_trade_lamports));
+ });
+
+ it('only accepts the two documented exit policies', () => {
+ expect(normalizeSwarmPolicy({ exit_policy: 'wait_to_close' }).exit_policy).toBe('wait_to_close');
+ expect(normalizeSwarmPolicy({ exit_policy: 'nonsense' }).exit_policy).toBe('settle_at_mark');
+ });
+});
diff --git a/tests/tournament-scoring.test.js b/tests/tournament-scoring.test.js
new file mode 100644
index 000000000..5b4000f0d
--- /dev/null
+++ b/tests/tournament-scoring.test.js
@@ -0,0 +1,240 @@
+/**
+ * Tournament scoring engine — pure tests.
+ *
+ * computeStandings / filterWindowPositions / evaluateEligibility / allocatePrizes are
+ * all pure (no DB, no network), so every assertion is hand-computed from the fixtures
+ * below. These pin the fairness rules: window scoping by OPEN time, the real-trade
+ * gate on prize brackets, the verification gates, and basis-point prize allocation.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ filterWindowPositions,
+ isRealTrade,
+ evaluateEligibility,
+ allocatePrizes,
+ computeStandings,
+ resolveGates,
+ scoreValue,
+ DEFAULT_GATES,
+} from '../api/_lib/tournament-scoring.js';
+
+const SOL = 1e9;
+
+const START = '2026-03-01T00:00:00.000Z';
+const END = '2026-03-02T00:00:00.000Z';
+const AFTER_END = new Date(new Date(END).getTime() + 1000).toISOString();
+
+/** Build a closed position with sane defaults. */
+function pos(over = {}) {
+ return {
+ status: 'closed',
+ mint: over.mint || 'MINT1111',
+ symbol: 'X',
+ realized_pnl_lamports: String(Math.round((over.pnl ?? 1) * SOL)),
+ realized_pnl_pct: over.pct ?? 100,
+ entry_quote_lamports: String(Math.round((over.entry ?? 1) * SOL)),
+ exit_quote_lamports: String(Math.round(((over.entry ?? 1) + (over.pnl ?? 1)) * SOL)),
+ opened_at: over.opened || '2026-03-01T06:00:00.000Z',
+ closed_at: over.closed || '2026-03-01T06:10:00.000Z',
+ buy_sig: 'buy' in over ? over.buy : 'b-real',
+ sell_sig: 's-real',
+ ...('extra' in over ? over.extra : {}),
+ };
+}
+
+describe('isRealTrade', () => {
+ it('treats SIMULATED / missing buy sigs as paper', () => {
+ expect(isRealTrade(pos({ buy: 'b-real' }))).toBe(true);
+ expect(isRealTrade(pos({ buy: 'SIMULATED' }))).toBe(false);
+ expect(isRealTrade(pos({ buy: null }))).toBe(false);
+ });
+});
+
+describe('filterWindowPositions', () => {
+ const positions = [
+ pos({ mint: 'IN1', opened: '2026-03-01T06:00:00.000Z' }), // inside
+ pos({ mint: 'BEFORE', opened: '2026-02-28T23:00:00.000Z' }), // before window
+ pos({ mint: 'AFTER', opened: '2026-03-02T01:00:00.000Z' }), // after window
+ pos({ mint: 'PAPER', opened: '2026-03-01T07:00:00.000Z', buy: 'SIMULATED' }), // paper, inside
+ ];
+
+ it('keeps only real trades opened inside the window for a prize bracket', () => {
+ const kept = filterWindowPositions(positions, { startIso: START, endIso: END, bracket: 'prize' });
+ expect(kept.map((p) => p.mint).sort()).toEqual(['IN1']);
+ });
+
+ it('keeps paper trades for a practice bracket', () => {
+ const kept = filterWindowPositions(positions, { startIso: START, endIso: END, bracket: 'practice' });
+ expect(kept.map((p) => p.mint).sort()).toEqual(['IN1', 'PAPER']);
+ });
+});
+
+describe('resolveGates', () => {
+ it('falls back to defaults and accepts overrides', () => {
+ expect(resolveGates({})).toEqual(DEFAULT_GATES);
+ expect(resolveGates({ entry_rules: { min_closed: 10, max_churn_pct: 20 } })).toEqual({
+ min_closed: 10,
+ min_unique_coins: DEFAULT_GATES.min_unique_coins,
+ max_churn_pct: 20,
+ });
+ });
+});
+
+describe('evaluateEligibility', () => {
+ const gates = { min_closed: 3, min_unique_coins: 2, max_churn_pct: 60 };
+
+ it('passes a clean entrant in a prize bracket', () => {
+ const metrics = { closed_count: 5, unique_coins: 4, churn_pct: 10 };
+ const r = evaluateEligibility({ metrics, gates, bracket: 'prize', realTrades: 5 });
+ expect(r.eligible).toBe(true);
+ expect(r.reasons).toEqual([]);
+ });
+
+ it('rejects too few trades / coins and flags it, never eligible', () => {
+ const metrics = { closed_count: 1, unique_coins: 1, churn_pct: 10 };
+ const r = evaluateEligibility({ metrics, gates, bracket: 'prize', realTrades: 1 });
+ expect(r.eligible).toBe(false);
+ expect(r.reasons).toContain('min_closed_3');
+ expect(r.reasons).toContain('min_unique_coins_2');
+ });
+
+ it('flags wash-suspected on single-coin high churn', () => {
+ const metrics = { closed_count: 6, unique_coins: 1, churn_pct: 80 };
+ const r = evaluateEligibility({ metrics, gates, bracket: 'prize', realTrades: 6 });
+ expect(r.wash_suspected).toBe(true);
+ expect(r.eligible).toBe(false);
+ });
+
+ it('never makes a practice bracket prize-eligible', () => {
+ const metrics = { closed_count: 9, unique_coins: 5, churn_pct: 5 };
+ const r = evaluateEligibility({ metrics, gates, bracket: 'practice', realTrades: 9 });
+ expect(r.eligible).toBe(false);
+ expect(r.reasons).toContain('practice_bracket');
+ });
+});
+
+describe('allocatePrizes', () => {
+ const pool = 1_000_000n; // 1,000,000 atomics
+ const splits = [
+ { rank: 1, bps: 6000 },
+ { rank: 2, bps: 3000 },
+ { rank: 3, bps: 1000 },
+ ];
+
+ it('allocates by basis points to eligible ranks', () => {
+ const ranked = [
+ { agent_id: 'a', rank: 1, eligible: true },
+ { agent_id: 'b', rank: 2, eligible: true },
+ { agent_id: 'c', rank: 3, eligible: true },
+ ];
+ const out = allocatePrizes(pool, splits, ranked);
+ expect(out.get('a')).toBe(600_000n);
+ expect(out.get('b')).toBe(300_000n);
+ expect(out.get('c')).toBe(100_000n);
+ });
+
+ it('leaves an ineligible rank UNALLOCATED — never redistributed', () => {
+ const ranked = [
+ { agent_id: 'a', rank: 1, eligible: true },
+ { agent_id: 'b', rank: 2, eligible: false }, // ineligible — its 3000 bps go unpaid
+ { agent_id: 'c', rank: 3, eligible: true },
+ ];
+ const out = allocatePrizes(pool, splits, ranked);
+ expect(out.get('a')).toBe(600_000n);
+ expect(out.has('b')).toBe(false);
+ expect(out.get('c')).toBe(100_000n);
+ const total = [...out.values()].reduce((s, v) => s + v, 0n);
+ expect(total).toBe(700_000n); // 300k stays in the pool
+ });
+
+ it('pays nothing from an empty pool', () => {
+ expect(allocatePrizes(0n, splits, [{ agent_id: 'a', rank: 1, eligible: true }]).size).toBe(0);
+ });
+});
+
+describe('scoreValue', () => {
+ const metrics = { score: 73, realized_pnl_sol: 4.2, roi_pct: 55 };
+ it('maps each scoring mode to its metric', () => {
+ expect(scoreValue(metrics, 'score')).toBe(73);
+ expect(scoreValue(metrics, 'realized_pnl')).toBe(4.2);
+ expect(scoreValue(metrics, 'roi_pct')).toBe(55);
+ expect(scoreValue(metrics, 'unknown')).toBe(73); // defaults to score
+ });
+});
+
+describe('computeStandings', () => {
+ const tournament = {
+ id: 't1',
+ network: 'mainnet',
+ scoring: 'realized_pnl',
+ bracket: 'prize',
+ starts_at: START,
+ ends_at: END,
+ entry_rules: { min_closed: 2, min_unique_coins: 2, max_churn_pct: 60 },
+ };
+
+ // Alice: 2 winning real trades on 2 coins, opened in-window → eligible, +3 SOL.
+ const alice = {
+ entry: { agent_id: 'alice', agent_name: 'Alice', status: 'active', wallet: 'WALLETalice' },
+ positions: [
+ pos({ mint: 'COIN_A', pnl: 2, opened: '2026-03-01T01:00:00.000Z' }),
+ pos({ mint: 'COIN_B', pnl: 1, opened: '2026-03-01T02:00:00.000Z' }),
+ ],
+ };
+ // Bob: 1 real trade only (below min_closed) → ranked but ineligible, +5 SOL.
+ const bob = {
+ entry: { agent_id: 'bob', agent_name: 'Bob', status: 'active', wallet: 'WALLETbob' },
+ positions: [pos({ mint: 'COIN_C', pnl: 5, opened: '2026-03-01T03:00:00.000Z' })],
+ };
+ // Carol: all paper trades → in a prize bracket she has zero counted trades.
+ const carol = {
+ entry: { agent_id: 'carol', agent_name: 'Carol', status: 'active', wallet: 'WALLETcarol' },
+ positions: [
+ pos({ mint: 'COIN_D', pnl: 9, opened: '2026-03-01T04:00:00.000Z', buy: 'SIMULATED' }),
+ pos({ mint: 'COIN_E', pnl: 9, opened: '2026-03-01T05:00:00.000Z', buy: 'SIMULATED' }),
+ ],
+ };
+ // Dave: withdrawn → excluded from the board entirely.
+ const dave = {
+ entry: { agent_id: 'dave', agent_name: 'Dave', status: 'withdrawn', wallet: 'WALLETdave' },
+ positions: [pos({ mint: 'COIN_F', pnl: 100, opened: '2026-03-01T04:30:00.000Z' })],
+ };
+
+ it('ranks by realized PnL, excludes withdrawn, flags eligibility honestly', () => {
+ const { standings } = computeStandings(tournament, [alice, bob, carol, dave], { now: Date.parse(AFTER_END) });
+ // Dave (withdrawn) is gone.
+ expect(standings.find((s) => s.agent_id === 'dave')).toBeUndefined();
+ // Bob (+5) ranks above Alice (+3) on realized_pnl, but Bob is ineligible.
+ const bobRow = standings.find((s) => s.agent_id === 'bob');
+ const aliceRow = standings.find((s) => s.agent_id === 'alice');
+ const carolRow = standings.find((s) => s.agent_id === 'carol');
+ expect(bobRow.rank).toBe(1);
+ expect(bobRow.eligible).toBe(false);
+ expect(bobRow.score_value).toBe(5);
+ expect(aliceRow.rank).toBe(2);
+ expect(aliceRow.eligible).toBe(true);
+ expect(aliceRow.score_value).toBe(3);
+ // Carol's paper trades don't count in a prize bracket.
+ expect(carolRow.in_window_trades).toBe(0);
+ expect(carolRow.eligible).toBe(false);
+ });
+
+ it('prize allocation skips the ineligible leader (Bob), pays the eligible Alice', () => {
+ const { standings } = computeStandings(tournament, [alice, bob, carol], { now: Date.parse(AFTER_END) });
+ const out = allocatePrizes(1_000_000n, [{ rank: 1, bps: 10000 }], standings);
+ // Rank 1 is Bob, ineligible → nothing allocated at all.
+ expect(out.size).toBe(0);
+ // But a structure paying rank 2 reaches eligible Alice.
+ const out2 = allocatePrizes(1_000_000n, [{ rank: 2, bps: 5000 }], standings);
+ expect(out2.get('alice')).toBe(500_000n);
+ });
+
+ it('a practice bracket counts paper trades and ranks everyone, prizes nobody', () => {
+ const practice = { ...tournament, bracket: 'practice' };
+ const { standings } = computeStandings(practice, [carol], { now: Date.parse(AFTER_END) });
+ const carolRow = standings.find((s) => s.agent_id === 'carol');
+ expect(carolRow.in_window_trades).toBe(2); // paper trades now count
+ expect(carolRow.eligible).toBe(false); // but never prize-eligible
+ });
+});
diff --git a/vercel.json b/vercel.json
index 481614b70..550330aae 100644
--- a/vercel.json
+++ b/vercel.json
@@ -6,7 +6,7 @@
"NODE_OPTIONS": "--no-deprecation"
},
"functions": {
- "api/cron/{copy-fanout,mirror-fanout,three-holders-snapshot}.js": {
+ "api/cron/{copy-fanout,mirror-fanout,signal-fanout,three-holders-snapshot}.js": {
"maxDuration": 120
},
"api/cron/{strategy-fanout,gmgn-seed}.js": {
@@ -18,6 +18,9 @@
"api/agents/[id].js": {
"maxDuration": 45
},
+ "api/tournaments/[id].js": {
+ "maxDuration": 120
+ },
"api/agents/networth.js": {
"maxDuration": 60
},
@@ -163,6 +166,10 @@
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
},
+ "api/sniper/radar-stream.js": {
+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
+ "maxDuration": 300
+ },
"api/sniper/history.js": {
"maxDuration": 20
},
@@ -550,6 +557,14 @@
"src": "/wallet/(.*)",
"dest": "/wallet/$1"
},
+ {
+ "src": "/terminal",
+ "dest": "/terminal.html"
+ },
+ {
+ "src": "/terminal/",
+ "dest": "/terminal.html"
+ },
{
"src": "/pumpfun",
"dest": "/pumpfun.html"
@@ -673,6 +688,10 @@
"src": "/strategies/?",
"dest": "/strategies.html"
},
+ {
+ "src": "/swarms/?",
+ "dest": "/swarms.html"
+ },
{
"src": "/api/strategies/(.*)",
"dest": "/api/strategies"
@@ -745,6 +764,14 @@
"src": "/trader/?",
"dest": "/trader.html"
},
+ {
+ "src": "/signals/?",
+ "dest": "/signals.html"
+ },
+ {
+ "src": "/signals/([^/]+)/?",
+ "dest": "/signal-detail.html"
+ },
{
"src": "/api/trader-og",
"dest": "/api/trader-og.js"
@@ -2234,6 +2261,14 @@
"src": "/api/sniper/stream",
"dest": "/api/sniper/stream.js"
},
+ {
+ "src": "/api/sniper/radar-stream",
+ "dest": "/api/sniper/radar-stream.js"
+ },
+ {
+ "src": "/api/sniper/radar",
+ "dest": "/api/sniper/radar.js"
+ },
{
"src": "/api/sniper/trader",
"dest": "/api/sniper/trader.js"
@@ -3292,6 +3327,18 @@
"src": "/api/club/tips/stream",
"dest": "/api/club/tips-stream"
},
+ {
+ "src": "/api/swarms/([^/]+)/stream",
+ "dest": "/api/swarms/[id]"
+ },
+ {
+ "src": "/api/swarms/([^/]+)",
+ "dest": "/api/swarms/[id]"
+ },
+ {
+ "src": "/api/swarms",
+ "dest": "/api/swarms"
+ },
{
"src": "/api/(.*)",
"dest": "/api/$1"
@@ -3944,6 +3991,10 @@
"path": "/api/cron/smart-money-graph",
"schedule": "*/10 * * * *"
},
+ {
+ "path": "/api/cron/radar-watchlist",
+ "schedule": "*/10 * * * *"
+ },
{
"path": "/api/cron/intel-learn",
"schedule": "*/15 * * * *"
@@ -4036,6 +4087,10 @@
"path": "/api/cron/mirror-fanout",
"schedule": "*/2 * * * *"
},
+ {
+ "path": "/api/cron/signal-fanout",
+ "schedule": "*/2 * * * *"
+ },
{
"path": "/api/cron/strategy-fanout",
"schedule": "*/2 * * * *"
diff --git a/vite.config.js b/vite.config.js
index 7e459331d..620ba6bd8 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -344,7 +344,11 @@ const appConfig = {
leaderboard: resolve(__dirname, 'pages/leaderboard.html'),
mirror: resolve(__dirname, 'pages/mirror.html'),
strategies: resolve(__dirname, 'pages/strategies.html'),
+ swarms: resolve(__dirname, 'pages/swarms.html'),
+ terminal: resolve(__dirname, 'pages/terminal.html'),
trader: resolve(__dirname, 'pages/trader.html'),
+ signals: resolve(__dirname, 'pages/signals.html'),
+ 'signal-detail': resolve(__dirname, 'pages/signal-detail.html'),
trades: resolve(__dirname, 'pages/trades.html'),
'claim-wallet': resolve(__dirname, 'pages/claim-wallet.html'),
'avatar-embed': resolve(__dirname, 'pages/avatar-embed.html'),
@@ -419,6 +423,7 @@ const appConfig = {
play: resolve(__dirname, 'pages/play.html'),
'play-agent-wallet': resolve(__dirname, 'pages/play/agent-wallet.html'),
'play-arena': resolve(__dirname, 'pages/play/arena.html'),
+ arena: resolve(__dirname, 'pages/arena.html'),
'smart-money': resolve(__dirname, 'pages/smart-money.html'),
pose: resolve(__dirname, 'pages/pose.html'),
animations: resolve(__dirname, 'pages/animations.html'),
@@ -774,14 +779,22 @@ support: resolve(__dirname, 'pages/support.html'),
'/watchlist/': resolve(root, 'pages/watchlist.html'),
'/leaderboard': resolve(root, 'pages/leaderboard.html'),
'/leaderboard/': resolve(root, 'pages/leaderboard.html'),
+ '/arena': resolve(root, 'pages/arena.html'),
+ '/arena/': resolve(root, 'pages/arena.html'),
'/mirror': resolve(root, 'pages/mirror.html'),
'/mirror/': resolve(root, 'pages/mirror.html'),
'/strategies': resolve(root, 'pages/strategies.html'),
'/strategies/': resolve(root, 'pages/strategies.html'),
+ '/swarms': resolve(root, 'pages/swarms.html'),
+ '/swarms/': resolve(root, 'pages/swarms.html'),
'/trader': resolve(root, 'pages/trader.html'),
'/trader/': resolve(root, 'pages/trader.html'),
+ '/signals': resolve(root, 'pages/signals.html'),
+ '/signals/': resolve(root, 'pages/signals.html'),
'/trades': resolve(root, 'pages/trades.html'),
'/trades/': resolve(root, 'pages/trades.html'),
+ '/terminal': resolve(root, 'pages/terminal.html'),
+ '/terminal/': resolve(root, 'pages/terminal.html'),
'/claim-wallet': resolve(root, 'pages/claim-wallet.html'),
'/claim-wallet/': resolve(root, 'pages/claim-wallet.html'),
'/pump-live': resolve(root, 'pages/pump-live.html'),
@@ -1125,6 +1138,9 @@ support: resolve(__dirname, 'pages/support.html'),
// /agents/:id → rich detail page (UUID expected, validated client-side)
else if (!filePath && /^\/bounty\/[^/]+\/?$/.test(path))
filePath = resolve(root, 'pages/bounty.html');
+ // /signals/<slug> → signal feed detail page (hydrates from /api/signals/feed)
+ else if (!filePath && /^\/signals\/[^/.]+\/?$/.test(path))
+ filePath = resolve(root, 'pages/signal-detail.html');
// `[^/.]+` (no dot) mirrors vercel.json's `/agents/([^/.]+)` so
// static assets like /agents/boot.js fall through to public/
// instead of being served the agent-detail HTML shell.
diff --git a/workers/agent-orders/Dockerfile b/workers/agent-orders/Dockerfile
new file mode 100644
index 000000000..1ec7b6a45
--- /dev/null
+++ b/workers/agent-orders/Dockerfile
@@ -0,0 +1,35 @@
+# agent-orders — long-lived Node worker (programmable orders engine).
+#
+# Build from the REPO ROOT (it imports api/_lib/* and the @three-ws/agent-payments
+# workspace, so it needs the full install):
+#
+# docker build -f workers/agent-orders/Dockerfile -t agent-orders .
+# docker run --env-file .env agent-orders
+#
+# Deploy target is Cloud Run (no HTTP port — it's a background worker; deploy
+# with --no-cpu-throttling so the sweep timer keeps running between requests).
+
+FROM node:24-slim
+
+WORKDIR /app
+
+# Install deps first for layer caching. See agent-sniper/Dockerfile for why
+# .npmrc (legacy-peer-deps) and devDeps (the agent-payments SDK build) are needed.
+COPY .npmrc package.json package-lock.json* ./
+COPY agent-payments-sdk/package.json ./agent-payments-sdk/
+RUN npm ci --ignore-scripts || npm install --ignore-scripts
+
+# Source needed at runtime, then build the SDK's dist/ explicitly.
+COPY agent-payments-sdk ./agent-payments-sdk
+COPY api ./api
+COPY src ./src
+COPY workers/agent-orders ./workers/agent-orders
+COPY workers/agent-sniper/amm-exit.js ./workers/agent-sniper/amm-exit.js
+RUN npm run build --prefix agent-payments-sdk
+
+RUN npm prune --omit=dev --ignore-scripts || true
+
+ENV NODE_ENV=production \
+ ORDERS_MODE=simulate
+
+CMD ["node", "workers/agent-orders/index.js"]
diff --git a/workers/agent-orders/README.md b/workers/agent-orders/README.md
new file mode 100644
index 000000000..23659198e
--- /dev/null
+++ b/workers/agent-orders/README.md
@@ -0,0 +1,82 @@
+# agent-orders — Programmable Orders Engine worker
+
+Set-and-forget institutional order tooling for memecoins. Pump.fun has no native
+order types; this worker gives every agent wallet a real programmable order layer:
+**limit**, **stop**, **trailing stop**, **DCA**, **TWAP**, and validated
+**conditional triggers** ("buy when smart-money score > 60 and mcap < $40k", "sell
+if the dev dumps", "buy on graduation").
+
+## What it does
+
+Every `ORDERS_POLL_MS` it sweeps all `active`/`partial` orders, re-quotes each
+mint off **live on-chain state** (bonding curve → AMM after graduation), evaluates
+the trigger/schedule, and on a match fires the order through
+`executeAgentTrade` (`api/agents/agent-trade.js`) — the **same** pipeline the
+owner-driven trade endpoint uses:
+
+```
+quote → rug/honeypot firewall → spend guards (kill switch, per-trade cap,
+daily budget, USD ceiling) → custody claim → MEV-aware sign+confirm → audit
+```
+
+The orders worker adds **no new way to move funds** — it only decides *when* to
+call that one audited path. Every fill is firewall-gated, capped by the agent's
+spend policy, and written to `agent_custody_events` (the canonical spend ledger),
+with an `order_fills` receipt linking back to it.
+
+## Order lifecycle
+
+`active → firing → filled` (price/conditional, single fill) ·
+`active → partial → … → filled` (DCA/TWAP, one slice per interval) ·
+`→ cancelled` (instant, owner) · `→ expired` (deadline) · `→ error` (a terminal
+block such as a firewall rug verdict).
+
+- **Idempotent.** Each fire claims its order atomically (`active|partial → firing`)
+ so exactly one sweep fires it; across processes the custody `idempotency_key`
+ (`order:<id>:slice:<n>`) is the double-spend backstop.
+- **Per-agent serialized.** An agent's orders run under a per-agent lock so two
+ orders can't both pass the daily-budget check on the same stale total.
+- **Honest on data gaps.** No live quote → the order holds (never fires on a
+ missing/zero price). A conditional with a missing signal does not fire.
+- **Self-healing.** Stale `firing` claims (a crash mid-fire) are recovered each
+ sweep; expired deadlines are swept to `expired`.
+
+## Triggers
+
+| Type | Fires when |
+|------|------------|
+| `limit` buy / sell | metric ≤ target (dip) / ≥ target (rise) |
+| `stop` sell / buy | metric ≤ stop (stop-loss) / ≥ stop (breakout) |
+| `trailing` sell / buy | metric ≤ peak·(1−trail%) / ≥ trough·(1+trail%) |
+| `dca` | `next_fire_at ≤ now`, one slice per interval, N slices |
+| `twap` | same scheduling; slices ONE total order to cut impact |
+| `conditional` | a validated `{ all\|any: [{ signal, op, value }] }` is true |
+
+`trigger_metric` ∈ `price_sol | mcap_sol | mcap_usd`. Conditional signals:
+`price_sol`, `mcap_sol`, `mcap_usd`, `price_change_pct`, `smart_money_score`,
+`dev_dump`, `graduated` — all real, code-free (see `api/_lib/orders.js`).
+
+## Run
+
+```bash
+npm run worker:orders # ORDERS_MODE=simulate (real quotes, no broadcast)
+npm run worker:orders:live # ORDERS_MODE=live (real fills)
+```
+
+### Env
+
+| Var | Default | Notes |
+|-----|---------|-------|
+| `DATABASE_URL`, `JWT_SECRET` | — | required |
+| `ORDERS_NETWORK` | `mainnet` | `mainnet`\|`devnet` |
+| `ORDERS_MODE` | `simulate` | `live` requires `SOLANA_RPC_URL` or `HELIUS_API_KEY` |
+| `ORDERS_POLL_MS` | `10000` | sweep cadence (min 3000) |
+| `ORDERS_CONCURRENCY` | `4` | agents evaluated in parallel per sweep |
+| `ORDERS_STALE_FIRING_MS` | `180000` | recover crash-orphaned `firing` claims older than this |
+| `ORDERS_GLOBAL_KILL` | `0` | halt all fires (orders untouched; cancel still works via the API) |
+| `ORDERS_HEARTBEAT_MS` | `30000` | `bot_heartbeat` liveness write (0 disables) |
+
+Deploy like `agent-sniper` (Cloud Run, `--no-cpu-throttling`). The migration is
+`api/_lib/migrations/20260623160000_programmable_orders.sql` (`npm run db:migrate`).
+The owner-facing surface is the **Orders** tab in the agent wallet hub
+(`src/agent-wallet-hub/tabs/orders.js`), backed by `/api/agents/:id/orders`.
diff --git a/workers/agent-orders/config.js b/workers/agent-orders/config.js
new file mode 100644
index 000000000..2b869c83d
--- /dev/null
+++ b/workers/agent-orders/config.js
@@ -0,0 +1,53 @@
+// agent-orders — environment + runtime configuration. Validated once at boot so
+// a misconfigured worker fails loudly instead of trading with half a config.
+
+function req(name) {
+ const v = process.env[name];
+ if (!v || !String(v).trim()) throw new Error(`[agent-orders] missing required env var: ${name}`);
+ return v;
+}
+function num(name, def) {
+ const raw = process.env[name];
+ if (raw == null || raw === '') return def;
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : def;
+}
+function bool(name, def = false) {
+ const raw = process.env[name];
+ if (raw == null || raw === '') return def;
+ return /^(1|true|yes|on)$/i.test(String(raw).trim());
+}
+
+export function loadConfig() {
+ req('DATABASE_URL');
+ req('JWT_SECRET');
+
+ const network = (process.env.ORDERS_NETWORK || 'mainnet').trim();
+ if (network !== 'mainnet' && network !== 'devnet') {
+ throw new Error(`[agent-orders] ORDERS_NETWORK must be mainnet|devnet, got "${network}"`);
+ }
+ const mode = (process.env.ORDERS_MODE || 'simulate').trim();
+ if (mode !== 'live' && mode !== 'simulate') {
+ throw new Error(`[agent-orders] ORDERS_MODE must be live|simulate, got "${mode}"`);
+ }
+ // A live worker on a public RPC will rate-limit under re-quote load — refuse to
+ // start live without a real endpoint rather than silently dropping fills.
+ if (mode === 'live' && !process.env.SOLANA_RPC_URL && !process.env.HELIUS_API_KEY) {
+ throw new Error('[agent-orders] live mode requires SOLANA_RPC_URL or HELIUS_API_KEY');
+ }
+
+ return {
+ network,
+ mode,
+ // Emergency stop — halt all fires while leaving orders intact (cancel still works via the API).
+ globalKill: bool('ORDERS_GLOBAL_KILL', false),
+ // Evaluation cadence.
+ pollMs: Math.max(3_000, num('ORDERS_POLL_MS', 10_000)),
+ // Agents evaluated in parallel per sweep (each agent's orders run serially).
+ concurrency: Math.max(1, Math.min(16, num('ORDERS_CONCURRENCY', 4))),
+ // A 'firing' claim older than this is considered crash-orphaned and recovered.
+ staleFiringMs: Math.max(60_000, num('ORDERS_STALE_FIRING_MS', 180_000)),
+ // Liveness heartbeat into bot_heartbeat (shared ops visibility). 0 disables.
+ heartbeatMs: Math.max(0, num('ORDERS_HEARTBEAT_MS', 30_000)),
+ };
+}
diff --git a/workers/agent-orders/index.js b/workers/agent-orders/index.js
new file mode 100644
index 000000000..b9a4ee67d
--- /dev/null
+++ b/workers/agent-orders/index.js
@@ -0,0 +1,82 @@
+// agent-orders — programmable order execution worker (entrypoint).
+//
+// Long-lived process (NOT a Vercel cron). Every cfg.pollMs it sweeps all active
+// orders, re-quotes each mint off live on-chain state, evaluates the
+// trigger/schedule, and fires matched orders through executeAgentTrade — the
+// same firewall + spend-guard + custody-audited path every agent trade uses.
+//
+// ORDERS_MODE=simulate — real quotes, no broadcast (default, safe)
+// ORDERS_MODE=live — real fills from agent wallets
+// ORDERS_GLOBAL_KILL=1 — halt all fires (orders untouched; cancel still works)
+//
+// Run: node workers/agent-orders (npm run worker:orders / worker:orders:live)
+
+import { sql } from '../../api/_lib/db.js';
+import { loadConfig } from './config.js';
+import { runOrderSweep } from './sweep.js';
+import { log } from './log.js';
+
+const BOOT_AT = new Date().toISOString();
+const WORKER = 'agent-orders';
+
+async function heartbeat(cfg, extra) {
+ try {
+ await sql`
+ INSERT INTO bot_heartbeat (worker, mode, last_beat_at, meta)
+ VALUES (${WORKER}, ${cfg.mode}, now(), ${JSON.stringify({ network: cfg.network, globalKill: cfg.globalKill, bootAt: BOOT_AT, ...extra })}::jsonb)
+ ON CONFLICT (worker) DO UPDATE
+ SET mode = excluded.mode, last_beat_at = excluded.last_beat_at, meta = excluded.meta
+ `;
+ } catch (err) {
+ log.warn('heartbeat write failed', { err: err?.message });
+ }
+}
+
+async function main() {
+ const cfg = loadConfig();
+ log.info('boot', { network: cfg.network, mode: cfg.mode, pollMs: cfg.pollMs, globalKill: cfg.globalKill });
+
+ let draining = false;
+ let sweeping = false;
+ let sweeps = 0;
+
+ const tick = async () => {
+ if (draining || sweeping || cfg.globalKill) return;
+ sweeping = true;
+ const started = Date.now();
+ try {
+ await runOrderSweep(cfg);
+ sweeps++;
+ } catch (err) {
+ log.error('sweep failed', { err: err?.message });
+ } finally {
+ sweeping = false;
+ if (cfg.heartbeatMs) heartbeat(cfg, { sweeps, lastSweepMs: Date.now() - started });
+ }
+ };
+
+ if (cfg.heartbeatMs) await heartbeat(cfg, { sweeps: 0 });
+ const timer = setInterval(tick, cfg.pollMs);
+ tick();
+
+ const shutdown = (signal) => {
+ if (draining) return;
+ draining = true;
+ log.info('shutdown', { signal });
+ clearInterval(timer);
+ // Neon HTTP is stateless — nothing else to close. Give an in-flight sweep a
+ // brief grace period, then exit.
+ const deadline = Date.now() + 8_000;
+ const wait = setInterval(() => {
+ if (!sweeping || Date.now() > deadline) { clearInterval(wait); log.info('bye', {}); process.exit(0); }
+ }, 200);
+ };
+ process.on('SIGINT', () => shutdown('SIGINT'));
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
+ process.on('unhandledRejection', (err) => log.error('unhandledRejection', { err: err?.message }));
+}
+
+main().catch((err) => {
+ log.error('fatal', { err: err?.message, stack: err?.stack });
+ process.exit(1);
+});
diff --git a/workers/agent-orders/log.js b/workers/agent-orders/log.js
new file mode 100644
index 000000000..64d4464d9
--- /dev/null
+++ b/workers/agent-orders/log.js
@@ -0,0 +1,16 @@
+// agent-orders — structured, single-line JSON logging. Keypairs/secrets never
+// reach here; callers pass only ids, mints, amounts, and reasons.
+
+function emit(level, msg, meta) {
+ const rec = { t: new Date().toISOString(), level, msg, ...(meta || {}) };
+ const line = JSON.stringify(rec);
+ if (level === 'error' || level === 'warn') console.error(line);
+ else console.log(line);
+}
+
+export const log = {
+ info: (msg, meta) => emit('info', msg, meta),
+ warn: (msg, meta) => emit('warn', msg, meta),
+ error: (msg, meta) => emit('error', msg, meta),
+ trade: (msg, meta) => emit('trade', msg, meta),
+};
diff --git a/workers/agent-orders/market.js b/workers/agent-orders/market.js
new file mode 100644
index 000000000..f5532a2d8
--- /dev/null
+++ b/workers/agent-orders/market.js
@@ -0,0 +1,155 @@
+// agent-orders — live market signals for order evaluation.
+//
+// Every value here is REAL on-chain or derived-from-on-chain data: prices come
+// from a live bonding-curve / AMM quote, market cap from the curve, smart-money
+// from the reputation graph, dev-dump + graduation from the coin-intel table.
+// Nothing is simulated. A source that can't be read returns null and the caller
+// stays honest (it never fires an order on absent data).
+
+import { getPumpTradeClient, getAmmPoolState } from '../../api/_lib/pump.js';
+import { solUsdPrice } from '../../api/_lib/avatar-wallet.js';
+import { getSmartMoneyForMint } from '../../api/_lib/smart-money.js';
+import { sql } from '../../api/_lib/db.js';
+import { PublicKey } from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync, getMint,
+ TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+// pump.fun mints: fixed 1,000,000,000 supply, 6 decimals.
+const TOTAL_SUPPLY_TOKENS = 1_000_000_000;
+const TOKEN_DECIMALS = 6;
+// A tiny reference buy → near-spot marginal price with negligible impact.
+const REF_LAMPORTS = 1_000_000n; // 0.001 SOL
+
+/**
+ * Live price + market cap for a mint. price_sol is SOL per whole token; mcap_sol
+ * is that price × the fixed supply. Routes off the bonding curve, falling back to
+ * the canonical AMM pool once the coin has graduated. Returns null on any quote
+ * failure so the caller treats it as "skip this sweep", never as a price of 0.
+ *
+ * @returns {Promise<{ price_sol:number, mcap_sol:number, graduated:boolean } | null>}
+ */
+export async function quoteMarket({ network, mint }) {
+ let ctx;
+ try { ctx = await getPumpTradeClient({ network }); } catch { return null; }
+ const mintPk = new ctx.web3.PublicKey(mint);
+ try {
+ const q = await ctx.client.quoteForBuy({ mint: mintPk, quoteAmount: new ctx.BN(REF_LAMPORTS.toString()), slippagePct: 0 });
+ const baseOut = Number(q.expectedBaseTokens.toString());
+ if (!(baseOut > 0)) return null;
+ const tokensOut = baseOut / 10 ** TOKEN_DECIMALS;
+ const price_sol = (Number(REF_LAMPORTS) / 1e9) / tokensOut;
+ return { price_sol, mcap_sol: price_sol * TOTAL_SUPPLY_TOKENS, graduated: false };
+ } catch (err) {
+ if (err?.name === 'CoinGraduatedError' || err?.code === 'CoinGraduated') {
+ return quoteMarketAmm({ network, mint });
+ }
+ return null;
+ }
+}
+
+// Price off the live AMM pool reserves (post-graduation). price = quote/base.
+async function quoteMarketAmm({ network, mint }) {
+ try {
+ const state = await getAmmPoolState({ network, mint });
+ const base = Number(state.baseReserve.toString()) / 10 ** TOKEN_DECIMALS;
+ const quote = Number(state.quoteReserve.toString()) / 1e9;
+ if (!(base > 0) || !(quote > 0)) return null;
+ const price_sol = quote / base;
+ return { price_sol, mcap_sol: price_sol * TOTAL_SUPPLY_TOKENS, graduated: true };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Compute the live signal map an order's trigger needs. `need` is the set of
+ * signal keys to resolve (price/mcap are always resolved since every price
+ * trigger and most conditions use them). Each lookup degrades to null on failure.
+ *
+ * @param {object} o
+ * @param {string} o.network
+ * @param {string} o.mint
+ * @param {string[]} [o.need] extra signals (smart_money_score, dev_dump, …)
+ * @param {number|null} [o.referencePrice] baseline metric for price_change_pct
+ * @param {string} [o.metric] which metric price_change_pct is measured in
+ * @returns {Promise<{ market: object|null, signals: object }>}
+ */
+export async function getSignals({ network, mint, need = [], referencePrice = null, metric = 'mcap_usd' }) {
+ const market = await quoteMarket({ network, mint });
+ const signals = {
+ price_sol: market?.price_sol ?? null,
+ mcap_sol: market?.mcap_sol ?? null,
+ mcap_usd: null,
+ graduated: market?.graduated ?? null,
+ smart_money_score: null,
+ dev_dump: null,
+ price_change_pct: null,
+ };
+
+ const wants = new Set(need);
+ // mcap_usd is needed whenever the metric is USD or a condition references it.
+ if (market && (metric === 'mcap_usd' || wants.has('mcap_usd'))) {
+ try { signals.mcap_usd = market.mcap_sol * (await solUsdPrice()); } catch { signals.mcap_usd = null; }
+ }
+
+ if (wants.has('smart_money_score')) {
+ try {
+ const sm = await getSmartMoneyForMint(mint, network);
+ signals.smart_money_score = sm?.computed ? Number(sm.smart_money_score) : null;
+ } catch { signals.smart_money_score = null; }
+ }
+
+ if (wants.has('dev_dump')) {
+ try {
+ const [row] = await sql`SELECT dev_sold, risk_flags FROM pump_coin_intel WHERE mint = ${mint}`;
+ if (row) signals.dev_dump = row.dev_sold === true || (Array.isArray(row.risk_flags) && row.risk_flags.includes('dev_dumped'));
+ } catch { signals.dev_dump = null; }
+ }
+
+ // price_change_pct vs the metric value captured when the order was created.
+ if ((wants.has('price_change_pct') || true) && referencePrice != null && market) {
+ const cur = metricValue(market, signals, metric);
+ if (cur != null && referencePrice > 0) signals.price_change_pct = ((cur - referencePrice) / referencePrice) * 100;
+ }
+
+ return { market, signals };
+}
+
+/** Pull the metric value (price_sol | mcap_sol | mcap_usd) out of a signal set. */
+export function metricValue(market, signals, metric) {
+ if (!market) return null;
+ if (metric === 'price_sol') return market.price_sol;
+ if (metric === 'mcap_sol') return market.mcap_sol;
+ if (metric === 'mcap_usd') return signals.mcap_usd;
+ return null;
+}
+
+/**
+ * Live token holding for an owner. Used to size percentage sells (sell N% of the
+ * bag). Returns whole-token + raw base-unit balance + decimals, or null if the
+ * owner holds none / the mint can't be read. Mirrors the resolveHolding logic the
+ * trade endpoint uses so a percentage sell is priced against the same balance.
+ */
+export async function getHolding({ network, mint, owner }) {
+ if (!owner) return null;
+ let ctx;
+ try { ctx = await getPumpTradeClient({ network }); } catch { return null; }
+ const conn = ctx.connection;
+ const mintPk = new PublicKey(mint);
+ const ownerPk = new PublicKey(owner);
+ let mintAcc;
+ try { mintAcc = await conn.getAccountInfo(mintPk); } catch { return null; }
+ if (!mintAcc) return null;
+ const tokenProgramId = mintAcc.owner.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;
+ let decimals;
+ try { decimals = (await getMint(conn, mintPk, 'confirmed', tokenProgramId)).decimals; } catch { return null; }
+ const ata = getAssociatedTokenAddressSync(mintPk, ownerPk, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);
+ let raw = 0n;
+ try { raw = BigInt((await conn.getTokenAccountBalance(ata)).value.amount); } catch { raw = 0n; }
+ const whole = Number(raw) / 10 ** decimals;
+ return { whole, raw, decimals };
+}
+
+export { TOTAL_SUPPLY_TOKENS, TOKEN_DECIMALS };
diff --git a/workers/agent-orders/package.json b/workers/agent-orders/package.json
new file mode 100644
index 000000000..cc64e26ba
--- /dev/null
+++ b/workers/agent-orders/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "@three-ws/agent-orders",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "description": "Programmable order execution worker — limit/stop/trailing/DCA/TWAP/conditional orders fired from agent wallets through the firewall + spend guards.",
+ "main": "index.js",
+ "scripts": {
+ "start": "node index.js",
+ "simulate": "ORDERS_MODE=simulate node index.js",
+ "live": "ORDERS_MODE=live node index.js"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+}
diff --git a/workers/agent-orders/store.js b/workers/agent-orders/store.js
new file mode 100644
index 000000000..24d8b4a13
--- /dev/null
+++ b/workers/agent-orders/store.js
@@ -0,0 +1,144 @@
+// agent-orders — order reads + state transitions for the evaluation worker.
+//
+// Single-worker assumption (documented, mirrors agent-sniper): per-order state
+// moves through an atomic claim (active|partial → firing) so a fire is owned by
+// exactly one sweep. Across processes, the custody idempotency_key on each fill
+// (order:<id>:slice:<n>) is the real double-spend backstop.
+
+import { sql } from '../../api/_lib/db.js';
+
+/** Active/partial orders on this network — the sweep's work set. */
+export async function getActiveOrders(network, limit = 500) {
+ return sql`
+ SELECT * FROM orders
+ WHERE network = ${network}
+ AND status IN ('active', 'partial')
+ ORDER BY next_fire_at ASC NULLS LAST, created_at ASC
+ LIMIT ${limit}
+ `;
+}
+
+/** Expire orders past their deadline (active/partial only). Returns count. */
+export async function expireOrders(network) {
+ const rows = await sql`
+ UPDATE orders SET status = 'expired', updated_at = now()
+ WHERE network = ${network}
+ AND status IN ('active', 'partial')
+ AND expires_at IS NOT NULL AND expires_at < now()
+ RETURNING id
+ `;
+ return rows.length;
+}
+
+/** Reset orders stuck in 'firing' (a crash mid-fire) back to their prior state. */
+export async function recoverStaleFiring(network, staleMs = 180_000) {
+ const rows = await sql`
+ UPDATE orders
+ SET status = CASE WHEN fill_count > 0 THEN 'partial' ELSE 'active' END, updated_at = now()
+ WHERE network = ${network} AND status = 'firing'
+ AND updated_at < now() - (${Math.round(staleMs / 1000)} || ' seconds')::interval
+ RETURNING id
+ `;
+ return rows.length;
+}
+
+/**
+ * Atomically claim an order for firing. Returns true iff this caller flipped it
+ * active|partial → firing (so exactly one sweep fires it).
+ */
+export async function claimFire(orderId) {
+ const rows = await sql`
+ UPDATE orders SET status = 'firing', updated_at = now()
+ WHERE id = ${orderId} AND status IN ('active', 'partial')
+ RETURNING id
+ `;
+ return rows.length > 0;
+}
+
+/** Release a claimed order back to a non-firing state (e.g. fire aborted). */
+export async function releaseFire(orderId, status, error = null) {
+ await sql`
+ UPDATE orders SET status = ${status}, last_error = ${error}, updated_at = now()
+ WHERE id = ${orderId} AND status = 'firing'
+ `;
+}
+
+/** Persist the per-sweep observation (last metric value + trailing high/low-water). */
+export async function markEvaluated(orderId, { lastPrice = null, peak = null } = {}) {
+ await sql`
+ UPDATE orders
+ SET last_eval_at = now(),
+ last_price = COALESCE(${lastPrice}, last_price),
+ peak_price = COALESCE(${peak}, peak_price)
+ WHERE id = ${orderId}
+ `;
+}
+
+/** Seed reference_price (first observation) so price_change_pct has a baseline. */
+export async function seedReference(orderId, value) {
+ await sql`UPDATE orders SET reference_price = ${value}, peak_price = COALESCE(peak_price, ${value}) WHERE id = ${orderId} AND reference_price IS NULL`;
+}
+
+/**
+ * Record a fill and advance the order's lifecycle in one place.
+ *
+ * @param {object} o
+ * @param {object} o.order the order row
+ * @param {object} o.fill { sliceIndex, triggerReason, triggerPrice, solAmount, tokenAmount, priceImpactPct, venue, signature, custodyEventId, status, detail, meta }
+ * @param {boolean} o.terminal true → order is fully filled (price/conditional, or last slice)
+ * @param {string|null} o.nextFireAt ISO for the next scheduled slice (dca/twap), or null
+ */
+export async function recordFillAndAdvance({ order, fill, terminal, nextFireAt = null }) {
+ const confirmedSol = fill.status === 'failed' ? 0 : Number(fill.solAmount || 0);
+ const confirmedTok = fill.status === 'failed' ? 0 : Number(fill.tokenAmount || 0);
+
+ await sql`
+ INSERT INTO order_fills
+ (order_id, agent_id, network, slice_index, side, trigger_reason, trigger_price,
+ sol_amount, token_amount, price_impact_pct, venue, signature, custody_event_id, status, detail, meta)
+ VALUES (
+ ${order.id}, ${order.agent_id}, ${order.network}, ${fill.sliceIndex ?? null}, ${order.side},
+ ${fill.triggerReason || null}, ${fill.triggerPrice ?? null}, ${fill.solAmount ?? null},
+ ${fill.tokenAmount ?? null}, ${fill.priceImpactPct ?? null}, ${fill.venue || null},
+ ${fill.signature || null}, ${fill.custodyEventId ?? null}, ${fill.status || 'pending'},
+ ${fill.detail || null}, ${fill.meta ? JSON.stringify(fill.meta) : null}::jsonb)
+ `;
+
+ // A failed fill does not advance fills/budget and must not consume a slice —
+ // it returns the order to its prior state to retry next sweep.
+ if (fill.status === 'failed') {
+ await sql`
+ UPDATE orders SET status = ${order.fill_count > 0 ? 'partial' : 'active'},
+ last_error = ${(fill.detail || 'fill_failed').slice(0, 280)}, updated_at = now()
+ WHERE id = ${order.id} AND status = 'firing'
+ `;
+ return;
+ }
+
+ // Advance the schedule counter for dca/twap.
+ let schedule = order.schedule || null;
+ if (schedule && (order.type === 'dca' || order.type === 'twap')) {
+ schedule = { ...schedule, filled_slices: (schedule.filled_slices || 0) + 1 };
+ }
+ const status = terminal ? 'filled' : 'partial';
+
+ await sql`
+ UPDATE orders SET
+ status = ${status},
+ filled_sol = filled_sol + ${confirmedSol},
+ filled_tokens = filled_tokens + ${confirmedTok},
+ fill_count = fill_count + 1,
+ schedule = ${schedule ? JSON.stringify(schedule) : null}::jsonb,
+ next_fire_at = ${terminal ? null : nextFireAt},
+ last_error = NULL,
+ updated_at = now()
+ WHERE id = ${order.id} AND status = 'firing'
+ `;
+}
+
+/** Load (and lightly cache) an agent's meta + user for the execution path. */
+export async function loadAgent(agentId) {
+ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!row) return null;
+ return { id: row.id, userId: row.user_id, meta: { ...(row.meta || {}) } };
+}
diff --git a/workers/agent-orders/sweep.js b/workers/agent-orders/sweep.js
new file mode 100644
index 000000000..42a51afda
--- /dev/null
+++ b/workers/agent-orders/sweep.js
@@ -0,0 +1,248 @@
+// agent-orders — one evaluation sweep over all active orders.
+//
+// For each order: re-quote its mint off live on-chain state, evaluate the
+// trigger/schedule, and on fire execute through executeAgentTrade — the SAME
+// quote → firewall → spend-guard → custody-claim → sign → confirm pipeline the
+// owner-driven trade endpoint uses. The orders worker adds NO new way to move
+// funds: it only decides WHEN to call that one audited path. Every fill is
+// firewall-gated, capped by the agent's spend policy + daily budget, and written
+// to agent_custody_events (with an order_fills receipt linking back).
+
+import { executeAgentTrade, parseTradeInput } from '../../api/agents/agent-trade.js';
+import { getTradeLimits } from '../../api/_lib/agent-trade-guards.js';
+import {
+ shouldFirePrice, evaluateCondition, conditionSignals,
+} from '../../api/_lib/orders.js';
+import { getSignals, metricValue, getHolding } from './market.js';
+import {
+ getActiveOrders, expireOrders, recoverStaleFiring,
+ claimFire, releaseFire, markEvaluated, seedReference,
+ recordFillAndAdvance, loadAgent,
+} from './store.js';
+import { log } from './log.js';
+
+// ── per-agent serialization ───────────────────────────────────────────────────
+// One agent wallet, one budget: serialize an agent's fills inside a sweep so two
+// orders can't both pass the daily-budget check on the same stale total. Across
+// processes the custody idempotency_key is the real backstop.
+const _locks = new Map();
+async function withAgentLock(agentId, fn) {
+ const prev = _locks.get(agentId) || Promise.resolve();
+ let release;
+ const next = new Promise((r) => (release = r));
+ _locks.set(agentId, prev.then(() => next));
+ await prev;
+ try { return await fn(); }
+ finally { release(); if (_locks.get(agentId) === next) _locks.delete(agentId); }
+}
+
+function errCode(err) {
+ return err?.code || err?.name || 'error';
+}
+
+// Blocks that won't clear by retrying — stop the order (status 'error') instead
+// of re-quoting it every sweep forever.
+const TERMINAL_CODES = new Set(['firewall_block', 'graduated', 'zero_out', 'invalid_mint', 'quote_not_sol']);
+
+/**
+ * Decide whether (and how) an order fires this sweep. Returns a fire descriptor
+ * or null to hold. Persists the per-sweep observation (last metric + trailing
+ * high/low-water mark) as a side effect — that part runs every sweep, fired or not.
+ */
+async function evaluate(order, now) {
+ // ── scheduled (DCA / TWAP) ────────────────────────────────────────────────
+ if (order.type === 'dca' || order.type === 'twap') {
+ if (!order.next_fire_at || new Date(order.next_fire_at).getTime() > now) return null;
+ const slices = Number(order.schedule?.slices ?? 1);
+ const sliceIndex = Number(order.schedule?.filled_slices ?? 0);
+ if (sliceIndex >= slices) return null;
+ const terminal = sliceIndex + 1 >= slices;
+ const intervalMs = Number(order.schedule?.interval_seconds ?? 0) * 1000;
+ const nextFireAt = terminal ? null : new Date(now + intervalMs).toISOString();
+ // Best-effort price for the receipt (never blocks a scheduled fill).
+ let triggerPrice = null;
+ try {
+ const { market, signals } = await getSignals({ network: order.network, mint: order.mint, metric: order.trigger_metric });
+ triggerPrice = metricValue(market, signals, order.trigger_metric);
+ } catch { /* receipt-only */ }
+ return { reason: `${order.type}_slice`, triggerPrice, sliceIndex, terminal, nextFireAt };
+ }
+
+ // ── price-driven + conditional ────────────────────────────────────────────
+ const need = order.type === 'conditional' ? conditionSignals(order.condition) : [];
+ const { market, signals } = await getSignals({
+ network: order.network, mint: order.mint, need,
+ referencePrice: order.reference_price, metric: order.trigger_metric,
+ });
+ if (!market) { await markEvaluated(order.id, {}); return null; } // honest: no live price → hold
+
+ const metricVal = metricValue(market, signals, order.trigger_metric);
+ if (order.reference_price == null && metricVal != null) await seedReference(order.id, metricVal);
+
+ // Track the trailing high/low-water mark every sweep, fired or not.
+ let peak = order.peak_price;
+ if (order.type === 'trailing' && metricVal != null) {
+ const base = order.peak_price ?? metricVal;
+ peak = order.side === 'sell' ? Math.max(base, metricVal) : Math.min(base, metricVal);
+ }
+ await markEvaluated(order.id, { lastPrice: metricVal, peak });
+
+ if (order.type === 'conditional') {
+ const { fired } = evaluateCondition(order.condition, signals);
+ if (!fired) return null;
+ return { reason: 'condition', triggerPrice: metricVal, sliceIndex: 0, terminal: true, nextFireAt: null };
+ }
+
+ if (!shouldFirePrice(order, metricVal, peak)) return null;
+ const reason = order.type === 'trailing'
+ ? (order.side === 'sell' ? 'trailing_stop' : 'trailing_entry')
+ : order.type;
+ return { reason, triggerPrice: metricVal, sliceIndex: 0, terminal: true, nextFireAt: null };
+}
+
+/** Build the executeAgentTrade `body` for a fire, or null if it can't be sized. */
+async function buildBody(order, agent) {
+ const base = { mint: order.mint, slippageBps: order.slippage_bps, network: order.network, side: order.side };
+ if (order.side === 'buy') {
+ if (!(Number(order.size_sol) > 0)) return null;
+ return { ...base, amount: Number(order.size_sol) };
+ }
+ // sell
+ if (order.sell_pct != null) {
+ if (order.sell_pct >= 100) return { ...base, amount: 'max' };
+ const holding = await getHolding({ network: order.network, mint: order.mint, owner: agent.meta.solana_address });
+ if (!holding || holding.whole <= 0) return null;
+ const amt = holding.whole * (order.sell_pct / 100);
+ return amt > 0 ? { ...base, amount: amt } : null;
+ }
+ if (Number(order.size_tokens) > 0) return { ...base, amount: Number(order.size_tokens) };
+ return null;
+}
+
+/** Map an executeAgentTrade result onto an order_fills record + advance the order. */
+async function settle(order, fire, result, mode) {
+ const priorPartial = order.fill_count > 0;
+ if (!result.ok) {
+ const code = result.code || 'error';
+ if (TERMINAL_CODES.has(code)) {
+ await recordFillAndAdvance({
+ order, terminal: false,
+ fill: { sliceIndex: fire.sliceIndex, triggerReason: fire.reason, triggerPrice: fire.triggerPrice, status: 'failed', detail: `${code}: ${result.message || ''}`.slice(0, 280) },
+ });
+ await releaseFire(order.id, 'error', `${code}: ${result.message || ''}`.slice(0, 280));
+ log.warn('order halted', { order: order.id, type: order.type, code });
+ return;
+ }
+ // Transient/clearable block (budget, kill switch, frozen, rpc) — hold + retry.
+ await releaseFire(order.id, priorPartial ? 'partial' : 'active', `${code}: ${result.message || ''}`.slice(0, 280));
+ log.info('order fire blocked (will retry)', { order: order.id, code });
+ return;
+ }
+
+ const d = result.data || {};
+ const simulated = d.simulated === true || mode !== 'live';
+ const status = simulated ? 'simulated' : (d.signature ? 'confirmed' : 'unconfirmed');
+ const solAmount = order.side === 'buy' ? (d.sol_spent ?? null) : (d.sol_received ?? null);
+ const tokenAmount = order.side === 'buy' ? (d.tokens_received ?? d.expected_out_raw ?? null) : (d.tokens_sold ?? null);
+
+ await recordFillAndAdvance({
+ order, terminal: fire.terminal, nextFireAt: fire.nextFireAt,
+ fill: {
+ sliceIndex: fire.sliceIndex, triggerReason: fire.reason, triggerPrice: fire.triggerPrice,
+ solAmount: simulated ? 0 : solAmount, tokenAmount: simulated ? 0 : tokenAmount,
+ priceImpactPct: d.price_impact_pct ?? null, venue: d.venue || null,
+ signature: d.signature && d.signature !== 'SIMULATED' ? d.signature : null,
+ custodyEventId: d.custody_event_id ?? null,
+ status, detail: simulated ? 'paper fill (simulate mode)' : null,
+ meta: { mode, slice: fire.sliceIndex },
+ },
+ });
+ log.trade('fill', {
+ order: order.id, type: order.type, side: order.side, mode, status,
+ reason: fire.reason, slice: fire.sliceIndex, terminal: fire.terminal,
+ sig: d.signature || null, impact: d.price_impact_pct ?? null,
+ });
+}
+
+/** Fire one order (claim → size → execute → settle). Per-agent serialized. */
+async function fireOne(order, agent, fire, cfg) {
+ if (!(await claimFire(order.id))) return; // another sweep owns it
+ try {
+ const body = await buildBody(order, agent);
+ if (!body) { await releaseFire(order.id, order.fill_count > 0 ? 'partial' : 'active', 'no_balance_or_size'); return; }
+
+ const tradeLimits = getTradeLimits(agent.meta);
+ let input;
+ try { input = parseTradeInput(body, tradeLimits); }
+ catch (e) { await releaseFire(order.id, 'error', `invalid_order: ${e?.message || e?.code || ''}`.slice(0, 280)); return; }
+
+ input.idempotencyKey = `order:${order.id}:slice:${fire.sliceIndex ?? 0}`;
+ if (cfg.mode !== 'live') input.simulate = true;
+
+ const result = await executeAgentTrade({
+ id: order.agent_id, userId: agent.userId, meta: agent.meta, input,
+ source: `order:${order.type}`, sourceMeta: { order_id: order.id, slice: fire.sliceIndex },
+ });
+ await settle(order, fire, result, cfg.mode);
+ } catch (err) {
+ await releaseFire(order.id, order.fill_count > 0 ? 'partial' : 'active', errCode(err)).catch(() => {});
+ log.error('order fire crashed', { order: order.id, err: err?.message });
+ }
+}
+
+/**
+ * Run one full sweep. Self-healing first (expire deadlines, recover stale firing
+ * claims), then evaluate every active order, firing those whose trigger/schedule
+ * is met. Orders are grouped by agent and agents processed with bounded
+ * concurrency; an agent's own orders run serially under a per-agent lock.
+ */
+export async function runOrderSweep(cfg) {
+ const now = Date.now();
+ try {
+ const expired = await expireOrders(cfg.network);
+ const recovered = await recoverStaleFiring(cfg.network, cfg.staleFiringMs);
+ if (expired || recovered) log.info('housekeeping', { expired, recovered });
+ } catch (err) {
+ log.warn('housekeeping failed', { err: err?.message });
+ }
+
+ let orders;
+ try { orders = await getActiveOrders(cfg.network); }
+ catch (err) { log.error('active-order query failed', { err: err?.message }); return; }
+ if (!orders.length) return;
+
+ // Group by agent so each agent's wallet is touched serially.
+ const byAgent = new Map();
+ for (const o of orders) {
+ if (!byAgent.has(o.agent_id)) byAgent.set(o.agent_id, []);
+ byAgent.get(o.agent_id).push(o);
+ }
+
+ const agentIds = [...byAgent.keys()];
+ const agentCache = new Map();
+ let cursor = 0;
+ const worker = async () => {
+ while (cursor < agentIds.length) {
+ const agentId = agentIds[cursor++];
+ await withAgentLock(agentId, async () => {
+ let agent = agentCache.get(agentId);
+ if (!agent) { agent = await loadAgent(agentId); agentCache.set(agentId, agent); }
+ if (!agent || !agent.meta?.encrypted_solana_secret) {
+ // No provisioned wallet — can't trade; leave orders untouched (the
+ // owner sees them sit until the wallet exists). Don't spam errors.
+ return;
+ }
+ for (const order of byAgent.get(agentId)) {
+ try {
+ const fire = await evaluate(order, now);
+ if (fire) await fireOne(order, agent, fire, cfg);
+ } catch (err) {
+ log.error('order eval failed', { order: order.id, err: err?.message });
+ }
+ }
+ });
+ }
+ };
+ const pool = Math.max(1, Math.min(cfg.concurrency, agentIds.length));
+ await Promise.all(Array.from({ length: pool }, worker));
+}
diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.js
index 8935bf690..8d8dd814e 100644
--- a/workers/agent-sniper/index.js
+++ b/workers/agent-sniper/index.js
@@ -17,7 +17,9 @@ import { scoreMint, scoreIntel } from './scorer.js';
import { executeBuy } from './executor.js';
import { oracleGate } from './oracle-gate.js';
import { runPositionSweep } from './positions.js';
+import { runSwarmConsensus, runSwarmSettlement } from './swarm.js';
import { startFirstClaimWatch } from './first-claim-watch.js';
+import { startPrelaunchRadar } from './prelaunch-radar.js';
import { startIntelWatcher } from './intel/watcher.js';
import { getLearnedWeights } from './intel/store.js';
import { getSmartMoneyForMint } from '../../api/_lib/smart-money.js';
@@ -180,6 +182,18 @@ async function main() {
cfg, queue, throttle, isHalted: () => draining || cfg.globalKill,
});
+ // Pre-launch creator-wallet radar: watches proven creator + smart-money wallets
+ // on-chain, detects launch precursors (funding a fresh deploy wallet / a pump
+ // create) at block-0, and pre-arms a snipe through the SAME executor as the feed
+ // path. Honestly reports paused when no RPC endpoint is available. Shares the
+ // buy queue + throttle and halts new buys on drain/kill.
+ let radar = { stop() {}, getState: () => ({ active: false, paused: true, reason: 'disabled' }) };
+ if (cfg.radar) {
+ radar = startPrelaunchRadar({
+ cfg, queue, throttle, isHalted: () => draining || cfg.globalKill,
+ });
+ }
+
// Strategy cache refresh.
const strategyTimer = setInterval(() => {
refreshStrategies(cfg.network, cfg.strategyRefreshMs)
@@ -203,6 +217,25 @@ async function main() {
}
}, cfg.pollMs);
+ // Trading-swarm consensus + settlement — overlap-guarded so a slow pass can't
+ // stack. Consensus pools members' live positions into a reputation-weighted vote
+ // and fires firewall-gated treasury buys; settlement distributes realized profit
+ // pro-rata. Both reuse the same guards/execution as solo snipes.
+ let swarmBusy = false;
+ const swarmTimer = setInterval(async () => {
+ if (swarmBusy || draining || cfg.globalKill) return;
+ swarmBusy = true;
+ try {
+ await runSwarmConsensus(cfg, { throttle });
+ await runSwarmSettlement(cfg);
+ } catch (err) {
+ log.error('swarm loop failed', { err: err?.message });
+ noteError('swarm', err?.message);
+ } finally {
+ swarmBusy = false;
+ }
+ }, Math.max(cfg.pollMs, 8000));
+
// Feed watchdog: connectPumpFunFeed stops after 5 drops; if the feed goes
// quiet past the threshold, tear down and re-subscribe so the brain never
// silently goes deaf.
@@ -240,6 +273,7 @@ async function main() {
lastError: errors.lastError,
intel: cfg.intel,
inFlightBuys: queue.inFlight,
+ radar: cfg.radar ? radar.getState() : { active: false, paused: true, reason: 'disabled' },
bootAt: BOOT_AT,
}),
});
@@ -251,9 +285,11 @@ async function main() {
if (cfg.announceLifecycle) alertShutdown({ signal, inFlight: queue.inFlight });
clearInterval(strategyTimer);
clearInterval(positionTimer);
+ clearInterval(swarmTimer);
clearInterval(watchdogTimer);
try { stopHeartbeat?.(); } catch {}
try { stopClaimWatch?.(); } catch {}
+ try { radar?.stop?.(); } catch {}
try { stopFeed?.(); } catch {}
try { stopIntel?.(); } catch {}
abort.abort();
diff --git a/workers/agent-sniper/prelaunch-radar.js b/workers/agent-sniper/prelaunch-radar.js
new file mode 100644
index 000000000..1f1e15185
--- /dev/null
+++ b/workers/agent-sniper/prelaunch-radar.js
@@ -0,0 +1,340 @@
+// agent-sniper — the pre-launch creator-wallet radar (block-zero pre-cog).
+//
+// A fourth source of snipes, parallel to the new-mint feed, first-claim poll, and
+// intel watcher. Instead of reacting to a launch AFTER it hits the PumpPortal feed
+// (where thousands of bots already see it), the radar watches the wallets of
+// proven creators + smart-money (the auto-curated radar_watchlist) and detects the
+// on-chain PRECURSOR to a launch:
+//
+// • a watched wallet submits a pump.fun create instruction → 'create'
+// • a watched wallet funds a brand-new deploy wallet … → 'funding'
+// … which then submits the create instruction → 'correlated_mint'
+//
+// The instant a mint is known, the precursor is scored against every armed
+// prelaunch_radar strategy and — if it passes the radar gates — routed through the
+// SAME executor as any other snipe (firewall, MEV engine, spend guards, custody
+// audit all unchanged). We act on PUBLIC on-chain precursors (funding, deploys),
+// never on intercepting another user's pending mempool transaction.
+//
+// Real chain reads only (Helius RPC when keyed, else the platform Solana RPC). No
+// RPC available → the radar reports itself PAUSED and the feed-based snipe carries
+// on; it never fabricates a precursor.
+//
+// Dedupe is two-layered like first-claim-watch: an in-process `seen` set skips a
+// signature handled this run, and radar_events' unique (network, signature, kind)
+// is the durable guarantee a precursor pre-arms once. The executor's
+// (agent, mint, network) lock is the final idempotency backstop on the buy.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+import { cachedStrategies } from './strategy-store.js';
+import { executeBuy } from './executor.js';
+import { oracleGate } from './oracle-gate.js';
+import { getWalletReputation } from '../../api/_lib/smart-money.js';
+import { scoreRadarEvent } from './radar-scorer.js';
+import {
+ radarEndpoint, fetchNewSignatures, fetchTransaction,
+ classifyTransaction, walletHistoryCount,
+} from './radar-detect.js';
+import {
+ recomputeWatchlist, loadWatchlist, markWatchlistHit,
+} from './radar-watchlist.js';
+
+const MAX_SEEN = 8000;
+
+function radarStrategies(network) {
+ return cachedStrategies().filter(
+ (s) => s.trigger === 'prelaunch_radar' && (s.network || 'mainnet') === network,
+ );
+}
+
+/**
+ * Start the radar. Returns a stop() that clears every timer, and a getState() the
+ * heartbeat reads so the operator can see whether the radar is live or paused.
+ *
+ * @param {object} o
+ * @param {object} o.cfg
+ * @param {{push:Function}} o.queue bounded buy queue (shared with other triggers)
+ * @param {{tryConsume:Function}} o.throttle
+ * @param {() => boolean} o.isHalted
+ */
+export function startPrelaunchRadar({ cfg, queue, throttle, isHalted }) {
+ const endpoint = radarEndpoint(cfg.network);
+ const paused = !endpoint;
+ const source = process.env.HELIUS_API_KEY ? 'helius' : 'rpc';
+
+ const seen = new Set(); // signatures handled this run
+ const cursors = new Map(); // watched address → newest sig already scanned
+ const deployWatch = new Map(); // fresh wallet → { funder, addedAt }
+ let watchlist = new Map(); // address → row
+ let rotateIdx = 0;
+ let scanning = false;
+ let backoffUntil = 0;
+ let consecutiveErrors = 0;
+ const state = {
+ active: !paused, paused, source, reason: paused ? 'no_rpc' : null,
+ watched: 0, deployWatch: 0, lastTickAt: null, lastEventAt: null,
+ events: 0, prearmed: 0, errors: 0,
+ };
+
+ if (paused) {
+ log.warn('prelaunch radar paused — no RPC endpoint (set HELIUS_API_KEY or SOLANA_RPC_URL)', {});
+ }
+
+ // ── watchlist refresh ────────────────────────────────────────────────────
+ const refreshWatchlist = async () => {
+ try {
+ const r = await recomputeWatchlist({ network: cfg.network, cfg });
+ watchlist = await loadWatchlist(cfg.network, cfg.radarMaxWatch);
+ state.watched = watchlist.size;
+ log.info('radar watchlist refreshed', {
+ watched: watchlist.size, creators: r.creators, smartMoney: r.smartMoney, evicted: r.evicted,
+ });
+ } catch (err) {
+ log.warn('radar watchlist refresh failed', { err: err?.message });
+ // Keep whatever we already had loaded — never blank the radar on a hiccup.
+ if (!watchlist.size) {
+ try { watchlist = await loadWatchlist(cfg.network, cfg.radarMaxWatch); state.watched = watchlist.size; } catch {}
+ }
+ }
+ };
+
+ // ── pre-arm a precursor that now has a mint ──────────────────────────────
+ const prearm = async (ev) => {
+ const strategies = radarStrategies(cfg.network);
+ if (!strategies.length) return;
+
+ // One reputation read per precursor shared across strategies — the trigger
+ // wallet (or, for a correlated mint, the funder) is what require_smart_money
+ // _funder judges. Degrades to a zero-data result; never blocks the snipe.
+ let funderRep = null;
+ try { funderRep = await getWalletReputation(ev.trigger_wallet, cfg.network); } catch { funderRep = null; }
+
+ for (const strat of strategies) {
+ const scored = scoreRadarEvent({ ...ev, funder_reputation: funderRep }, strat, cfg);
+ if (!scored.pass) {
+ log.info('radar skip', { agent: strat.agent_id, mint: ev.mint, reason: scored.reasons[0] });
+ continue;
+ }
+ log.info('radar candidate', {
+ agent: strat.agent_id, mint: ev.mint, kind: ev.kind,
+ trigger: ev.trigger_wallet, confidence: scored.confidence, reasons: scored.reasons,
+ });
+ state.prearmed++;
+ const candidate = {
+ mint: ev.mint, symbol: null, name: null,
+ entry_trigger: 'prelaunch_radar', trigger_ref: ev.signature,
+ };
+ queue.push(async () => {
+ if (isHalted()) return;
+ const og = await oracleGate(ev.mint, cfg.network, strat);
+ if (!og.pass) { log.info('oracle gate skip', { agent: strat.agent_id, mint: ev.mint, reason: og.reason }); return; }
+ await executeBuy({ cfg, strat, mint: candidate, throttle });
+ });
+ }
+ };
+
+ // Persist a precursor (deduped). Returns true if it was NEW (pre-arm once).
+ const recordEvent = async (ev) => {
+ try {
+ const watch = ev.watch || {};
+ const [row] = await sql`
+ insert into radar_events
+ (network, kind, trigger_wallet, new_wallet, mint, signature, confidence,
+ watch_reason, watch_score, detail, observed_ts)
+ values
+ (${cfg.network}, ${ev.kind}, ${ev.trigger_wallet}, ${ev.new_wallet || null},
+ ${ev.mint || null}, ${ev.signature}, ${ev.base_confidence ?? 0},
+ ${watch.reason || null}, ${watch.score ?? null},
+ ${JSON.stringify(ev.detail || {})}::jsonb,
+ ${ev.observed_ms ? new Date(ev.observed_ms).toISOString() : null})
+ on conflict (network, signature, kind) do nothing
+ returning id
+ `;
+ return !!row;
+ } catch (err) {
+ log.warn('radar event persist failed', { err: err?.message });
+ return false;
+ }
+ };
+
+ const emit = async (ev) => {
+ const fresh = await recordEvent(ev);
+ if (!fresh) return;
+ state.events++;
+ state.lastEventAt = Date.now();
+ markWatchlistHit(ev.trigger_wallet, cfg.network).catch(() => {});
+ if (ev.mint) await prearm(ev);
+ };
+
+ // ── scan one watched wallet's new activity ───────────────────────────────
+ const scanWallet = async (address, watch) => {
+ const until = cursors.get(address) || null;
+ // A throw here bubbles to tick() for backoff accounting — intentional.
+ const sigs = await fetchNewSignatures(address, { endpoint, untilSig: until, limit: 25 });
+ if (!sigs.length) return;
+
+ // First time we see this wallet: anchor the cursor at its newest signature
+ // WITHOUT acting on history. The radar only fires on launches that happen
+ // after we start watching — never backfills a stale, already-floored launch.
+ if (!until) { cursors.set(address, sigs[0].signature); return; }
+
+ cursors.set(address, sigs[0].signature);
+ // Process oldest→newest so a funding that precedes its create is seen first.
+ for (const s of [...sigs].reverse()) {
+ if (s.err || seen.has(s.signature)) continue;
+ seen.add(s.signature);
+ const tx = await fetchTransaction(s.signature, { endpoint }).catch(() => null);
+ if (!tx) continue;
+ const observedMs = s.blockTime ? s.blockTime * 1000 : (tx.blockTime ? tx.blockTime * 1000 : null);
+ const { create, fundings } = classifyTransaction(tx, address);
+
+ if (create) {
+ await emit({
+ kind: 'create', trigger_wallet: address, mint: create.mint, signature: s.signature,
+ base_confidence: 0.9, observed_ms: observedMs, watch,
+ detail: { variant: create.variant },
+ });
+ }
+
+ for (const f of fundings) {
+ if (f.lamports < cfg.radarMinFundingLamports) continue;
+ let hist;
+ try { hist = await walletHistoryCount(f.destination, { endpoint }); } catch { hist = null; }
+ if (!hist || !hist.fresh) continue; // only fresh wallets are deploy-wallet candidates
+ await emit({
+ kind: 'funding', trigger_wallet: address, new_wallet: f.destination, signature: s.signature,
+ base_confidence: 0.5, observed_ms: observedMs, watch,
+ detail: { funded_sol: f.lamports / 1e9, fresh_tx_count: hist.total },
+ });
+ // Put the fresh wallet under correlation watch for its create.
+ if (deployWatch.size < 2000) {
+ deployWatch.set(f.destination, { funder: address, watch, addedAt: Date.now(), cursor: null });
+ }
+ }
+ }
+ };
+
+ // ── scan a freshly-funded wallet for the create it was funded to make ────
+ const scanDeployWallet = async (address, entry) => {
+ // A throw here bubbles to tick() for backoff accounting — intentional.
+ const sigs = await fetchNewSignatures(address, { endpoint, untilSig: entry.cursor, limit: 15 });
+ if (!sigs.length) return;
+ entry.cursor = sigs[0].signature;
+ for (const s of [...sigs].reverse()) {
+ if (s.err || seen.has(s.signature)) continue;
+ seen.add(s.signature);
+ const tx = await fetchTransaction(s.signature, { endpoint }).catch(() => null);
+ if (!tx) continue;
+ const create = classifyTransaction(tx, address).create;
+ if (!create) continue;
+ const observedMs = s.blockTime ? s.blockTime * 1000 : null;
+ await emit({
+ kind: 'correlated_mint', trigger_wallet: entry.funder, new_wallet: address, mint: create.mint,
+ signature: s.signature, base_confidence: 0.85, observed_ms: observedMs, watch: entry.watch,
+ detail: { variant: create.variant, via_funding: true },
+ });
+ deployWatch.delete(address); // correlated — stop watching it
+ return;
+ }
+ };
+
+ // ── poll tick ────────────────────────────────────────────────────────────
+ const tick = async () => {
+ if (paused || scanning || isHalted()) return;
+ if (Date.now() < backoffUntil) return;
+ if (!radarStrategies(cfg.network).length) return; // nothing armed → don't burn RPC
+ if (!watchlist.size) return;
+ scanning = true;
+ let hadError = false;
+ try {
+ // Expire stale deploy-watch entries.
+ const ttl = cfg.radarDeployWatchTtlMs;
+ for (const [addr, entry] of deployWatch) {
+ if (Date.now() - entry.addedAt > ttl) deployWatch.delete(addr);
+ }
+
+ // Round-robin a bounded batch of watched wallets so the whole set is
+ // covered across ticks without flooding the RPC in one tick.
+ const addresses = [...watchlist.keys()];
+ const batchSize = Math.min(cfg.radarWalletsPerTick, addresses.length);
+ for (let i = 0; i < batchSize; i++) {
+ const address = addresses[(rotateIdx + i) % addresses.length];
+ try {
+ await scanWallet(address, watchlist.get(address));
+ } catch (err) {
+ hadError = true;
+ log.warn('radar wallet scan failed', { address, err: err?.message });
+ }
+ }
+ rotateIdx = (rotateIdx + batchSize) % addresses.length;
+
+ // Always sweep the (small) deploy-watch set every tick — these are the
+ // hottest precursors, a create can land seconds after the funding.
+ for (const [addr, entry] of [...deployWatch]) {
+ try {
+ await scanDeployWallet(addr, entry);
+ } catch (err) {
+ hadError = true;
+ log.warn('radar deploy-wallet scan failed', { addr, err: err?.message });
+ }
+ }
+
+ pruneSeen(seen);
+ state.lastTickAt = Date.now();
+ state.deployWatch = deployWatch.size;
+ } finally {
+ scanning = false;
+ if (hadError) {
+ state.errors++;
+ consecutiveErrors++;
+ // Exponential backoff on sustained RPC failure (rate limits / outage),
+ // capped — the radar degrades, the feed snipe keeps running.
+ if (consecutiveErrors >= 3) {
+ const backoff = Math.min(120_000, cfg.radarPollMs * 2 ** Math.min(5, consecutiveErrors - 2));
+ backoffUntil = Date.now() + backoff;
+ state.reason = 'rpc_backoff';
+ log.warn('radar backing off', { ms: backoff, consecutiveErrors });
+ }
+ } else {
+ consecutiveErrors = 0;
+ if (state.reason === 'rpc_backoff') state.reason = null;
+ }
+ }
+ };
+
+ // ── boot ──────────────────────────────────────────────────────────────────
+ let pollTimer = null;
+ let refreshTimer = null;
+ if (!paused) {
+ refreshWatchlist().finally(() => {
+ pollTimer = setInterval(() => { tick().catch((err) => log.error('radar tick crashed', { err: err?.message })); }, cfg.radarPollMs);
+ if (pollTimer.unref) pollTimer.unref();
+ });
+ refreshTimer = setInterval(() => { refreshWatchlist().catch(() => {}); }, cfg.radarWatchlistRefreshMs);
+ if (refreshTimer.unref) refreshTimer.unref();
+ log.info('prelaunch radar armed', {
+ pollMs: cfg.radarPollMs, refreshMs: cfg.radarWatchlistRefreshMs, walletsPerTick: cfg.radarWalletsPerTick, source,
+ });
+ }
+
+ return {
+ stop() {
+ if (pollTimer) clearInterval(pollTimer);
+ if (refreshTimer) clearInterval(refreshTimer);
+ },
+ getState() {
+ return { ...state, watched: watchlist.size, deployWatch: deployWatch.size };
+ },
+ };
+}
+
+function pruneSeen(seen) {
+ if (seen.size <= MAX_SEEN) return;
+ const drop = seen.size - Math.floor(MAX_SEEN / 2);
+ let i = 0;
+ for (const sig of seen) {
+ seen.delete(sig);
+ if (++i >= drop) break;
+ }
+}
diff --git a/workers/agent-sniper/swarm.js b/workers/agent-sniper/swarm.js
new file mode 100644
index 000000000..e6760bb1a
--- /dev/null
+++ b/workers/agent-sniper/swarm.js
@@ -0,0 +1,192 @@
+// agent-sniper — trading-swarm consensus + settlement loops.
+//
+// A swarm pools multiple agents' capital into one custodial treasury and trades it
+// on REPUTATION-WEIGHTED CONSENSUS: the treasury buys a mint only when enough of
+// the swarm's combined, verified track record is already long that mint (each
+// member's own open position is a real, on-chain "yes" vote). Sizing scales with
+// the combined conviction, bounded by swarm policy + the trade firewall (reused
+// via executeBuy). Realized profit on close distributes pro-rata to members.
+//
+// This is a long-lived loop in the sniper worker. It reuses executeBuy unchanged,
+// so every swarm buy passes the same spend guards, firewall, and MEV execution as
+// a solo snipe — consensus only decides WHICH mints, never bypasses a treasury cap.
+
+import { sql } from '../../api/_lib/db.js';
+import { getSmartMoneyForMint } from '../../api/_lib/smart-money.js';
+import {
+ computeConsensus,
+ normalizeSwarmPolicy,
+ refreshMemberReputations,
+ settleSwarm,
+} from '../../api/_lib/swarms.js';
+import { executeBuy } from './executor.js';
+import { log } from './log.js';
+
+const REPUTATION_TTL_MS = 5 * 60_000;
+const VOTE_COOLDOWN_MS = 90_000; // don't re-evaluate the same swarm+mint more often
+const CANDIDATE_LOOKBACK = '2 hours';
+
+const _repAt = new Map(); // swarmId → last reputation refresh ts
+const _voteAt = new Map(); // `${swarmId}:${mint}` → last vote ts
+
+function cooled(key, ttl) {
+ const last = _voteAt.get(key) || 0;
+ if (Date.now() - last < ttl) return false;
+ _voteAt.set(key, Date.now());
+ return true;
+}
+
+/**
+ * One consensus pass across every active swarm on this network. For each swarm:
+ * 1. refresh cached member reputations (throttled to once per TTL),
+ * 2. gather candidate mints = mints any member currently holds (their real votes),
+ * 3. tally reputation-weighted agreement, gate on smart-money + policy,
+ * 4. fire a firewall-gated treasury buy sized by conviction when consensus clears,
+ * 5. log the full vote breakdown to swarm_votes either way.
+ */
+export async function runSwarmConsensus(cfg, { throttle } = {}) {
+ if (cfg.globalKill) return;
+ const swarms = await sql`
+ select * from swarms where network = ${cfg.network} and status = 'active'
+ `;
+ for (const swarm of swarms) {
+ try {
+ await evaluateSwarm(cfg, swarm, throttle);
+ } catch (err) {
+ log.error('swarm consensus failed', { swarm: swarm.id, err: err?.message });
+ }
+ }
+}
+
+async function evaluateSwarm(cfg, swarm, throttle) {
+ const pol = normalizeSwarmPolicy(swarm.policy);
+
+ // 1. member set + reputations (vote weights).
+ if (Date.now() - (_repAt.get(swarm.id) || 0) > REPUTATION_TTL_MS) {
+ await refreshMemberReputations(swarm.id, cfg.network).catch(() => {});
+ _repAt.set(swarm.id, Date.now());
+ }
+ const members = await sql`
+ select sm.agent_id, sm.reputation, ai.name
+ from swarm_members sm join agent_identities ai on ai.id = sm.agent_id
+ where sm.swarm_id = ${swarm.id} and sm.status = 'active'
+ `;
+ if (members.length < 2) return; // a swarm needs ≥2 members to form consensus
+ const memberAgentIds = members.map((m) => m.agent_id);
+
+ // 2. candidate mints: what members are actually long right now (their real,
+ // on-chain "yes" votes). A member who recently opened a position in a mint is
+ // expressing live conviction we can pool.
+ const candidates = await sql`
+ select p.mint,
+ coalesce(max(p.symbol),'') as symbol, coalesce(max(p.name),'') as name,
+ array_agg(distinct p.agent_id) as agents
+ from agent_sniper_positions p
+ where p.agent_id = any(${memberAgentIds}::uuid[]) and p.network = ${cfg.network}
+ and p.status in ('open','opening')
+ and p.opened_at > now() - ${CANDIDATE_LOOKBACK}::interval
+ group by p.mint
+ `;
+
+ // Treasury already-held mints (skip — executeBuy would no-op anyway).
+ const held = new Set(
+ (await sql`
+ select mint from agent_sniper_positions
+ where agent_id = ${swarm.treasury_agent_id} and network = ${cfg.network} and status in ('opening','open','closing')
+ `).map((r) => r.mint),
+ );
+
+ for (const cand of candidates) {
+ if (held.has(cand.mint)) continue;
+ if (!cooled(`${swarm.id}:${cand.mint}`, VOTE_COOLDOWN_MS)) continue;
+
+ // 3. smart-money confirmation (real graph read; degrades to zero-data).
+ const sm = await getSmartMoneyForMint(cand.mint, cfg.network).catch(() => null);
+ const smScore = sm?.computed ? Number(sm.smart_money_score) || 0 : 0;
+
+ const longAgentIds = new Set(cand.agents || []);
+ const tally = computeConsensus({ members, longAgentIds, smartMoneyScore: smScore, policy: pol });
+
+ // Policy gates → skip (still logged for the audit trail).
+ let skipReason = null;
+ if (pol.require_smart_money && (!sm?.computed || (sm.count ?? 0) < 1)) skipReason = 'no_smart_money';
+ else if (pol.min_smart_money_score > 0 && smScore < pol.min_smart_money_score) skipReason = 'smart_money_below_min';
+ else if (tally.consensus < pol.min_consensus) skipReason = 'below_consensus';
+
+ if (skipReason) {
+ await logVote(swarm, cand, tally, smScore, pol, 'skip', null, skipReason);
+ continue;
+ }
+
+ // 4. size by conviction, bounded by policy max-per-trade.
+ const maxPer = BigInt(pol.max_per_trade_lamports);
+ const floor = maxPer / 4n;
+ let size = BigInt(Math.round(Number(maxPer) * tally.conviction));
+ if (size < floor) size = floor;
+ if (size > maxPer) size = maxPer;
+
+ const strat = await loadTreasuryStrategy(swarm, size);
+ if (!strat) { await logVote(swarm, cand, tally, smScore, pol, 'skip', null, 'no_strategy'); continue; }
+
+ log.info('swarm consensus fire', {
+ swarm: swarm.id, mint: cand.mint, consensus: tally.consensus.toFixed(3),
+ conviction: tally.conviction.toFixed(3), members_long: tally.members_long, members_total: tally.members_total, smScore,
+ });
+
+ const result = await executeBuy({
+ cfg, strat, throttle: throttle || { tryConsume: () => true },
+ mint: { mint: cand.mint, symbol: cand.symbol || null, name: cand.name || null, entry_trigger: 'swarm_consensus', trigger_ref: swarm.id },
+ });
+
+ // Resolve the position id we just opened (if any) for the vote log.
+ let positionId = null;
+ if (result?.status === 'open') {
+ const [p] = await sql`
+ select id from agent_sniper_positions
+ where agent_id = ${swarm.treasury_agent_id} and mint = ${cand.mint} and network = ${cfg.network}
+ order by opened_at desc limit 1`;
+ positionId = p?.id || null;
+ }
+ await logVote(swarm, cand, tally, smScore, pol, result?.status === 'open' ? 'fire' : 'skip', positionId, result?.status === 'open' ? 'consensus_met' : (result?.reason || result?.status || 'not_opened'), size);
+ }
+}
+
+async function loadTreasuryStrategy(swarm, perTradeOverride) {
+ const [strat] = await sql`select * from agent_sniper_strategies where id = ${swarm.strategy_id} limit 1`;
+ if (!strat) return null;
+ // Clone + size this fire by conviction. Everything else (budget, exits, firewall)
+ // stays exactly as the swarm policy configured it; executeBuy enforces all of it.
+ return { ...strat, per_trade_lamports: perTradeOverride.toString(), agent_name: `Swarm · ${swarm.name}` };
+}
+
+async function logVote(swarm, cand, tally, smScore, pol, decision, positionId, reason, sizeLamports = null) {
+ await sql`
+ insert into swarm_votes
+ (swarm_id, mint, network, decision, consensus, min_consensus, conviction, size_lamports,
+ members_long, members_total, smart_money_score, breakdown, position_id, reason)
+ values
+ (${swarm.id}, ${cand.mint}, ${swarm.network}, ${decision}, ${tally.consensus}, ${pol.min_consensus},
+ ${tally.conviction}, ${sizeLamports != null ? sizeLamports.toString() : null},
+ ${tally.members_long}, ${tally.members_total}, ${smScore}, ${JSON.stringify(tally.breakdown)}::jsonb,
+ ${positionId}, ${reason})
+ `.catch((err) => log.error('swarm vote log failed', { swarm: swarm.id, err: err?.message }));
+}
+
+/**
+ * Settlement pass: distribute realized profit on newly-closed treasury positions
+ * to members pro-rata via real SOL transfers. Runs for active AND killed swarms (a
+ * killed swarm still needs its final closes distributed). Idempotent.
+ */
+export async function runSwarmSettlement(cfg) {
+ const swarms = await sql`
+ select id, name from swarms where network = ${cfg.network} and status in ('active','paused','killed')
+ `;
+ for (const swarm of swarms) {
+ try {
+ const r = await settleSwarm(swarm.id);
+ if (r.settled > 0) log.info('swarm settled', { swarm: swarm.id, positions: r.settled, distributed_lamports: r.distributed });
+ } catch (err) {
+ log.error('swarm settle failed', { swarm: swarm.id, err: err?.message });
+ }
+ }
+}