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.

feat(trader): show why an agent took each trade, with the evidence it had at entry

overstepping0176eedef29b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77174144d..4d0772d8a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-09-24
+- **Docs · Trade receipts** (`/docs/trade-receipts`): Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.
- **Paying the Club cover in USDC works in wallets that refused to show the request**: Some visitors paying the Club cover in USDC saw their wallet refuse to open the approval window, and the payment stopped with "Your wallet could not display this payment request". The payment itself was well formed; the problem was in how the page handed it to the wallet. The payment window now passes the transaction to your wallet through the Wallet Standard interface that Phantom, Solflare and Backpack all support, exactly as our server built it, and only falls back to the older wallet connection for wallets that do not offer it. Nothing was ever charged on a refused attempt. (`/club`) `[fix]`
+- **See why an AI trader bought, with the evidence it had**: Every closed trade on an agent's track record now has a why link. It opens the trade's receipt: what triggered the entry, the Oracle score and the base-rate reasons behind it, the trade firewall's on-chain buy and sell simulation, the LLM judge's thesis when one ran, the Risk Officer's review, and paid market and rug-pull reads with the payment transaction that bought them. Every entry and exit leg links to its transaction. Each piece of evidence shows when it was recorded relative to the entry. Anything logged after the exit is left out, because it could not have caused the trade. The same receipt appears on every shareable trade page, a link with ?trade= opens it directly, and agents can read it through the new trade_receipt MCP tool. (`/docs/trade-receipts`) `[feature]`
- **The x402 payment rail stops starting payments it cannot afford to finish**: The platform's own agents pay each other for services over x402, and a daily budget caps how much SOL the shared fee wallet spends on network fees. When that budget was nearly used up, our agents kept starting payments anyway: they looked up accounts, signed transfers and ran a simulated check, only to be turned away at the last step. About 1,700 payments an hour ended that way beside roughly 230 that settled. Each agent now reserves its share of the remaining budget before it starts, so a payment only begins when the fee wallet can fund it. The economy lab also now counts every refused payment instead of about one in a hundred, and the treasury report tells a wallet holding a little spare SOL apart from one that is empty. Payments from customer wallets are never held back by this budget. (`/economy-lab`) `[fix, infra]`
## 2026-09-22
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 0f72b8e20..970a19dfd 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -247,6 +247,7 @@ bottom.
| Airdrop Checker (any-address eligibility) | scanner [api/_lib/wallet-activity.js](api/_lib/wallet-activity.js), evaluator [api/_lib/airdrop-eligibility.js](api/_lib/airdrop-eligibility.js) (pure, tested in [tests/airdrop-eligibility.test.js](tests/airdrop-eligibility.test.js)), registry [data/airdrops.json](data/airdrops.json), endpoint [api/crypto/airdrops.js](api/crypto/airdrops.js) `→ /api/crypto/airdrops`, page [pages/airdrops.html](pages/airdrops.html) + [src/airdrops.js](src/airdrops.js) + [src/airdrops.css](src/airdrops.css) `→ /airdrops` | Live | Scores any wallet's REAL on-chain activity against tracked airdrop criteria: Solana keyless (signature scan over the rotating RPC chain + balance-layer token diversity), EVM via Etherscan V2 behind ETHERSCAN_API_KEY. Unmeasurable fields report as unknown and never count as met; protocol-specific steps are unscored manual to-dos; capped scans flag totals as minimums. Cross-links with /portfolio and shares its recent-wallet list. Docs: [docs/airdrops.md](docs/airdrops.md). Wiring test: [tests/airdrops-page.test.js](tests/airdrops-page.test.js) |
| Exit Lab (counterfactual exit replay) | kernel [api/_lib/exit-replay.js](api/_lib/exit-replay.js), corpus [api/sniper/exit-lab.js](api/sniper/exit-lab.js) `→ /api/sniper/exit-lab`, page [pages/exit-lab.html](pages/exit-lab.html) + [src/exit-lab.js](src/exit-lab.js) `→ /exit-lab` | Live | Replays every REAL closed sniper position through the live `decideLadderedExit` with the exit rules changed, so the fleet can ask "were our exits right?" about SOL it already spent. The kernel is pure and is imported by BOTH the handler and the browser, so a slider move is instant and server and client can never disagree. Two-phase walk over the recorded path (entry to peak to final quote) mirroring the live partial-sell bookkeeping leg for leg. States its own limits on the page: earlier exits are exact, longer holds are a lower bound, laddered positions are excluded with a stated reason. Grid search is an exact enumeration, flagged as in-sample. Tests: [tests/exit-replay.test.js](tests/exit-replay.test.js), [tests/exit-lab-page.test.js](tests/exit-lab-page.test.js). Docs: [docs/exit-lab.md](docs/exit-lab.md), tutorial [docs/tutorials/find-a-better-exit-policy.md](docs/tutorials/find-a-better-exit-policy.md) |
| Shareable trade card (per closed trade) | model [api/_lib/trade-card.js](api/_lib/trade-card.js), loader [api/_lib/trade-card-store.js](api/_lib/trade-card-store.js), image [api/trade-og.js](api/trade-og.js) `→ /api/trade-og?id=`, page [api/trade-share.js](api/trade-share.js) `→ /trade/<position id>`, share link on every closed row in [src/trader.js](src/trader.js) | Live | The trader-level card answers "is this trader any good?"; this one answers "what just happened?" and is the artifact worth posting the minute a position closes. One closed `agent_sniper_positions` row becomes an SVG 1200x630 card (coin, result with its return multiple, SOL in/out, hold time, exit reason) plus an SSR page carrying per-trade Open Graph / Twitter / Farcaster meta, both legs linked to Solscan, and a one-tap post. Image and page render from ONE pure model, so the picture that unfurls and the page it lands on can never disagree about a number. Honest by construction: a loss renders exactly like a win, a simulate-mode fill is stamped PAPER and never counted as live, and a moon-bag exit says the position was not fully sold. Unknown, still-open or deleted trades fall back rather than break an unfurl. Tests: [tests/trade-card.test.js](tests/trade-card.test.js) |
+| Trade receipts ("why it traded") | model + loader [api/_lib/trade-receipt.js](api/_lib/trade-receipt.js), endpoint [api/sniper/receipt.js](api/sniper/receipt.js) `→ /api/sniper/receipt?id=`, shared renderer [src/shared/trade-receipt-view.js](src/shared/trade-receipt-view.js), drawer on [src/trader.js](src/trader.js) `→ /trader/:id?trade=<id>`, section on [api/trade-share.js](api/trade-share.js) `→ /trade/:id`, MCP tool `trade_receipt` in [api/_mcp/tools/trader.js](api/_mcp/tools/trader.js), tests [tests/trade-receipt.test.js](tests/trade-receipt.test.js) | Live (read-only) | Why an agent took one trade, from the rows its gates actually wrote: entry trigger, Oracle score and pillars at entry with the base-rate reasons behind it, the trade firewall verdict and checks (the simulated buy/sell round-trip included), the LLM judge thesis, the Risk Officer review, paid x402 sentiment and rug-pull reads with their payment tx, launch intel, and every journal leg with its signature. Each block is timed against the entry; evidence logged after the exit is dropped and evidence seen while holding is labeled as such, so a receipt never passes hindsight off as a reason. Same visibility gate as `/api/sniper/trader`. Doc: [docs/trade-receipts.md](docs/trade-receipts.md). |
| Never sell 100% of a winner (moon-bag policy) | rule [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`moonbagExitFraction`, `moonbagAlways`), retained-bag booking [workers/agent-sniper/executor.js](workers/agent-sniper/executor.js), position fields [api/_lib/migrations/20260725100000_sniper_moonbag_always.sql](api/_lib/migrations/20260725100000_sniper_moonbag_always.sql), board [api/sniper/experiments.js](api/sniper/experiments.js) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments` | Live | Fleet-wide owner rule: a terminal exit that is IN PROFIT sells down to the moon-bag floor (default 15%) instead of to zero, and the retained tokens ride indefinitely. Once the cost basis is back the remainder is free, so a bag that goes to zero costs nothing and a bag that runs is the whole upside; selling the last slice for a rounding error gives that up. Applies with or without the proactive 2x ladder. A loss exit with the stake still at risk is still a FULL exit and the hard stop-loss is never overridden. The position still books `closed`, so realized P&L and the `max_concurrent_positions` slot are unaffected and a held bag can never stop an arm trading; only the tokens stay behind (`moonbag_base_amount`). Per-strategy opt-out `moonbag_always = false`. Tests: [tests/sniper-laddered-exit.test.js](tests/sniper-laddered-exit.test.js), [tests/trading-experiment-e2e.test.js](tests/trading-experiment-e2e.test.js). See [docs/trading-experiment.md](docs/trading-experiment.md) |
| Autonomous Trading hub (front door) | [pages/trading.html](pages/trading.html) `→ /trading` + [src/trading-hub.js](src/trading-hub.js), pure formatters [src/trading-hub-format.js](src/trading-hub-format.js), surface + doc directory [src/trading-hub-data.js](src/trading-hub-data.js), styles [src/trading-hub.css](src/trading-hub.css) | Live | One entry point for a trading system that had grown to ~20 pages with no front door. Live fleet vitals from `GET /api/sniper/status` (mode, armed strategies, open positions, feed health, funding, uptime), the agent scoreboard from `GET /api/sniper/leaderboard` (realized P&L only, closed trades only, with cumulative sparkline), the five-gate entry-to-exit explainer, and directories of every trading surface and doc. Feed health is reported separately from process health because a beating worker with a silent feed reads as green while seeing nothing. Directory is data, so [tests/trading-hub.test.js](tests/trading-hub.test.js) asserts every link resolves against `data/pages.json` and the docs tree. Docs: [docs/trading-hub.md](docs/trading-hub.md), tutorial [docs/tutorials/read-the-trading-fleet.md](docs/tutorials/read-the-trading-fleet.md) |
| Sniper Experiments (rules vs LLM A/B fleet) | [pages/sniper-experiments.html](pages/sniper-experiments.html) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments`, aggregate [api/sniper/experiments.js](api/sniper/experiments.js), LLM judge [workers/agent-sniper/llm-judge.js](workers/agent-sniper/llm-judge.js), fleet seeding [scripts/seed-sniper-experiments.mjs](scripts/seed-sniper-experiments.mjs) | Live | The sniper fleet runs labeled rule-set variants side by side (strict shields, oracle-gated, and `decision_mode=llm` arms judged per-launch by Grok / Claude / OpenRouter auto with no shields), all behind the same safety rails. The page is the live scoreboard of which entry conditions actually make money; real on-chain fills only. |
diff --git a/api/_lib/trade-receipt.js b/api/_lib/trade-receipt.js
new file mode 100644
index 000000000..b4294b423
--- /dev/null
+++ b/api/_lib/trade-receipt.js
@@ -0,0 +1,472 @@
+/**
+ * Trade receipts: why an agent took one trade, with the evidence it had.
+ *
+ * The track record answers "did it make money". A receipt answers the question a
+ * copier asks next: "why did it buy that?" Every autonomous entry already passes
+ * through a chain of real gates that each leave a row behind, so a receipt is not
+ * an after-the-fact story. It is those rows, joined to one position and ordered
+ * against its entry time:
+ *
+ * trigger agent_sniper_positions.entry_trigger / trigger_ref
+ * oracle oracle_conviction_history (the score + pillars at entry) and
+ * oracle_conviction (the base-rate reasons behind the score)
+ * firewall firewall_decisions (the buy/sell round-trip simulation and
+ * authority / concentration / impact checks run for this buy)
+ * judge sniper_llm_verdicts (the LLM buy/skip thesis, when one ran)
+ * risk officer sniper_risk_reviews (the adversarial second opinion)
+ * sentiment sniper_coin_sentiment (paid x402 market read, with its tx)
+ * token risk token_intel_risk (paid x402 rug-pull score, with its tx)
+ * intel pump_coin_intel (observed launch structure)
+ * legs trading_journal (every entry / partial / exit leg + its tx)
+ *
+ * Honesty rules, enforced here so no renderer can break them:
+ * - Evidence recorded AFTER the exit is dropped: it cannot have caused the trade.
+ * - Evidence recorded after the entry but before the exit is kept and tagged
+ * `during_trade`, so the page can say "seen while holding", not "why it bought".
+ * - A paper fill stays labeled paper. A missing gate is simply absent, never
+ * filled with a guess.
+ *
+ * The shaping functions are pure and database-free (tests/trade-receipt.test.js);
+ * loadTradeReceipt() is the single query path the API and the /trade/:id page share.
+ */
+
+import { sql } from './db.js';
+import { isUuid } from './validate.js';
+import { exitReasonLabel, solscanTx, solscanToken, SIMULATED_SIG } from './trade-card.js';
+
+const LAMPORTS_PER_SOL = 1e9;
+
+/** How far before the entry a firewall decision may sit and still be this buy's. */
+const FIREWALL_LOOKBACK_MS = 15 * 60 * 1000;
+/** Rows are stamped by separate writers, so allow a little clock skew past the fill. */
+const ENTRY_SKEW_MS = 2 * 60 * 1000;
+/** At most this many Oracle base-rate reasons: the ones that moved the score most. */
+const MAX_ORACLE_REASONS = 5;
+
+/** Entry triggers the sniper can write, in words a spectator understands. */
+const TRIGGER_LABELS = {
+ new_mint: {
+ label: 'Fresh launch',
+ detail: 'Bought at creation, scored on the launch itself before anyone else had traded it.',
+ },
+ oracle_crossing: {
+ label: 'Oracle crossing',
+ detail: 'The Oracle conviction score for this coin crossed the strategy\'s buy threshold.',
+ },
+ intel_confirmed: {
+ label: 'Intel confirmed',
+ detail: 'The coin was watched for its first minutes and bought once its observed trading cleared the bar.',
+ },
+ llm_intel: {
+ label: 'LLM judgment',
+ detail: 'An LLM judge read the observed launch data and voted to buy.',
+ },
+ graduation_ride: {
+ label: 'Graduation ride',
+ detail: 'Bought as the coin approached graduation from the bonding curve to the AMM.',
+ },
+};
+
+export function triggerLabel(trigger) {
+ const key = trigger || 'new_mint';
+ return TRIGGER_LABELS[key] || { label: String(key).replace(/_/g, ' '), detail: null };
+}
+
+const JOURNAL_EVENT_LABELS = {
+ entry: 'Entry',
+ take_initials: 'Initials recovered',
+ exit: 'Exit',
+ exit_moonbag: 'Moon-bag exit',
+};
+
+function num(v) {
+ if (v == null || v === '') return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+function lamToSol(v) {
+ const n = num(v);
+ return n == null ? null : n / LAMPORTS_PER_SOL;
+}
+
+function ms(ts) {
+ if (!ts) return null;
+ const t = new Date(ts).getTime();
+ return Number.isFinite(t) ? t : null;
+}
+
+function iso(ts) {
+ const t = ms(ts);
+ return t == null ? null : new Date(t).toISOString();
+}
+
+/**
+ * Where a piece of evidence sits against the trade: before the entry (it could
+ * have caused the buy), during the hold, or after the exit (it could not have).
+ */
+export function evidenceTiming(at, openedAt, closedAt) {
+ const t = ms(at);
+ const open = ms(openedAt);
+ if (t == null || open == null) return null;
+ if (t <= open + ENTRY_SKEW_MS) return 'before_entry';
+ const close = ms(closedAt);
+ if (close != null && t > close) return 'after_exit';
+ return 'during_trade';
+}
+
+/**
+ * A transaction explorer link for any signature a receipt carries. Solana
+ * signatures go to Solscan; an EVM hash (an x402 payment settled on Base) goes
+ * to Basescan, so a paid-signal receipt always opens on the chain it settled on.
+ */
+export function receiptTxUrl(sig, network = 'mainnet') {
+ const s = typeof sig === 'string' ? sig.trim() : '';
+ if (!s || s === SIMULATED_SIG) return null;
+ if (/^0x[0-9a-fA-F]{64}$/.test(s)) return `https://basescan.org/tx/${s}`;
+ if (/^[1-9A-HJ-NP-Za-km-z]{64,90}$/.test(s)) return solscanTx(s, network);
+ return null;
+}
+
+function shapeOracle(history, current, position) {
+ if (!history && !current) return null;
+ const base = history || current;
+ const reasonsTiming = current ? evidenceTiming(current.scored_at, position.opened_at, position.closed_at) : null;
+ const reasons = current && reasonsTiming && reasonsTiming !== 'after_exit' && Array.isArray(current.reasons)
+ ? current.reasons
+ .filter((r) => r && typeof r.text === 'string')
+ .map((r) => ({ text: r.text, pillar: r.pillar || null, lift: num(r.lift), samples: num(r.samples) }))
+ .sort((a, b) => Math.abs((b.lift ?? 1) - 1) - Math.abs((a.lift ?? 1) - 1))
+ .slice(0, MAX_ORACLE_REASONS)
+ : [];
+ return {
+ score: num(base.score),
+ tier: base.tier || null,
+ pillars: {
+ pedigree: num(base.pedigree),
+ structure: num(base.structure),
+ narrative: num(base.narrative),
+ momentum: num(base.momentum),
+ },
+ rug_risk: num(base.rug_risk),
+ upside: num(base.upside),
+ give_back_risk: num(base.give_back_risk),
+ scored_at: iso(base.scored_at),
+ timing: evidenceTiming(base.scored_at, position.opened_at, position.closed_at),
+ reasons,
+ reasons_scored_at: reasons.length ? iso(current.scored_at) : null,
+ reasons_timing: reasons.length ? reasonsTiming : null,
+ };
+}
+
+function shapeFirewall(row, position) {
+ if (!row) return null;
+ const checks = Array.isArray(row.checks)
+ ? row.checks
+ .filter((c) => c && c.name)
+ .map((c) => ({ name: String(c.name), status: c.status || null, reason: c.reason || null }))
+ : [];
+ return {
+ verdict: row.verdict || null,
+ score: num(row.score),
+ reasons: Array.isArray(row.reasons) ? row.reasons.filter((r) => typeof r === 'string') : [],
+ checks,
+ simulated: row.simulated !== false,
+ enforced: row.enforced === true,
+ at: iso(row.created_at),
+ timing: evidenceTiming(row.created_at, position.opened_at, position.closed_at),
+ };
+}
+
+function shapeJudge(row, position) {
+ if (!row) return null;
+ const timing = evidenceTiming(row.created_at, position.opened_at, position.closed_at);
+ if (timing !== 'before_entry') return null;
+ return {
+ buy: row.buy === true,
+ confidence: num(row.confidence),
+ thesis: row.thesis || null,
+ model: row.model || null,
+ at: iso(row.created_at),
+ timing,
+ };
+}
+
+function shapeRiskReview(row, position) {
+ if (!row) return null;
+ return {
+ level: row.level || null,
+ veto: row.veto === true,
+ severity: row.severity || null,
+ reasons: Array.isArray(row.reasons) ? row.reasons.filter((r) => typeof r === 'string') : [],
+ proposed_sol: lamToSol(row.proposed_lamports),
+ adjusted_sol: lamToSol(row.adjusted_lamports),
+ enforced: row.enforced === true,
+ model: row.model || null,
+ at: iso(row.created_at),
+ timing: evidenceTiming(row.created_at, position.opened_at, position.closed_at),
+ };
+}
+
+function shapePaidSignal(row, position, fields) {
+ if (!row) return null;
+ const timing = evidenceTiming(row.checked_at, position.opened_at, position.closed_at);
+ if (!timing || timing === 'after_exit') return null;
+ const out = { at: iso(row.checked_at), timing, receipt_url: receiptTxUrl(row.tx_signature, position.network) };
+ for (const [key, kind] of Object.entries(fields)) {
+ if (kind === 'num') out[key] = num(row[key]);
+ else if (kind === 'bool') out[key] = row[key] === true;
+ else out[key] = row[key] ?? null;
+ }
+ return out;
+}
+
+function shapeIntel(row, position) {
+ if (!row) return null;
+ const observedAt = row.observation_ended_at || row.updated_at || row.first_seen_at;
+ const timing = evidenceTiming(observedAt, position.opened_at, position.closed_at);
+ if (!timing || timing === 'after_exit') return null;
+ return {
+ quality_score: num(row.quality_score),
+ category: row.category || null,
+ narrative: row.narrative || null,
+ smart_money_count: num(row.smart_money_count),
+ bundle_score: num(row.bundle_score),
+ organic_score: num(row.organic_score),
+ concentration_top10: num(row.concentration_top10),
+ unique_buyers: num(row.unique_buyers),
+ risk_flags: Array.isArray(row.risk_flags) ? row.risk_flags.filter(Boolean) : [],
+ is_news_meme: row.is_news_meme === true,
+ observed_at: iso(observedAt),
+ timing,
+ };
+}
+
+function shapeLeg(row, network) {
+ return {
+ event: row.event,
+ label: JOURNAL_EVENT_LABELS[row.event] || String(row.event || '').replace(/_/g, ' '),
+ reason: row.reason || null,
+ rationale: row.rationale || null,
+ sold_fraction: num(row.sold_fraction),
+ leg_pnl_sol: lamToSol(row.leg_pnl_lamports),
+ market_cap_usd: num(row.market_cap_usd),
+ venue: row.venue || null,
+ mode: row.mode || null,
+ at: iso(row.ts),
+ tx_url: receiptTxUrl(row.sig, network),
+ };
+}
+
+function fmtPctPlain(p) {
+ if (p == null) return null;
+ const sign = p > 0 ? '+' : p < 0 ? '-' : '';
+ return `${sign}${Math.abs(p).toFixed(Math.abs(p) >= 100 ? 0 : 1)}%`;
+}
+
+/**
+ * One plain-English line that states the drivers, built only from evidence the
+ * receipt actually carries. Never a prediction, never a superlative.
+ */
+export function summarizeReceipt(r) {
+ const p = r.position;
+ const who = p.agent_name || 'This agent';
+ const coin = p.symbol ? `$${p.symbol}` : 'this coin';
+ const e = r.evidence;
+ const drivers = [];
+ if (e.oracle && e.oracle.timing === 'before_entry' && e.oracle.score != null) {
+ drivers.push(`Oracle score ${e.oracle.score}${e.oracle.tier ? ` ${e.oracle.tier}` : ''}`);
+ }
+ if (e.firewall && e.firewall.verdict) drivers.push(`firewall ${e.firewall.verdict}`);
+ if (e.judge) {
+ const conf = e.judge.confidence != null ? ` at ${Math.round(e.judge.confidence * 100)}%` : '';
+ drivers.push(`LLM judge voted ${e.judge.buy ? 'buy' : 'skip'}${conf}`);
+ }
+ if (e.risk_review && e.risk_review.severity) drivers.push(`risk officer ${e.risk_review.severity}`);
+ let line = `${who} ${p.paper ? 'paper-bought' : 'bought'} ${coin}. Trigger: ${r.trigger.label}.`;
+ if (drivers.length) line += ` ${drivers.join(', ').replace(/^./, (c) => c.toUpperCase())}.`;
+ if (p.status === 'closed') {
+ const pct = fmtPctPlain(p.pnl_pct);
+ line += ` Exited on ${p.exit_label.toLowerCase()}${pct ? ` at ${pct}` : ''}.`;
+ } else {
+ line += ' Still open.';
+ }
+ return line;
+}
+
+/**
+ * Shape the raw rows into the receipt model. PURE.
+ *
+ * @param {object} parts
+ * position agent_sniper_positions row joined with agent_name / agent_image / is_public
+ * journal trading_journal rows for the position (any order)
+ * oracleHistory, oracleCurrent, firewall, judge, riskReview, sentiment, tokenRisk, intel
+ * @returns {object} the receipt the API returns and both renderers read
+ */
+export function shapeTradeReceipt(parts) {
+ const row = parts.position;
+ const network = row.network === 'devnet' ? 'devnet' : 'mainnet';
+ const paper = !row.buy_sig || row.buy_sig === SIMULATED_SIG;
+ const trigger = triggerLabel(row.entry_trigger);
+ const position = {
+ id: row.id,
+ agent_id: row.agent_id,
+ agent_name: row.agent_name || null,
+ agent_image: row.agent_image || null,
+ network,
+ mint: row.mint,
+ symbol: row.symbol || null,
+ name: row.name || null,
+ status: row.status,
+ paper,
+ entry_trigger: row.entry_trigger || 'new_mint',
+ trigger_ref: row.trigger_ref || null,
+ opened_at: iso(row.opened_at),
+ closed_at: iso(row.closed_at),
+ entry_sol: lamToSol(row.entry_quote_lamports),
+ exit_sol: lamToSol(row.exit_quote_lamports),
+ pnl_sol: lamToSol(row.realized_pnl_lamports),
+ pnl_pct: num(row.realized_pnl_pct),
+ entry_price_impact_pct: num(row.entry_price_impact_pct),
+ exit_reason: row.exit_reason || null,
+ exit_label: exitReasonLabel(row.exit_reason),
+ buy_url: solscanTx(row.buy_sig, network),
+ sell_url: solscanTx(row.sell_sig, network),
+ token_url: solscanToken(row.mint, network),
+ trader_url: `/trader/${row.agent_id}`,
+ share_url: row.status === 'closed' ? `/trade/${row.id}` : null,
+ };
+ const legs = (parts.journal || [])
+ .slice()
+ .sort((a, b) => (ms(a.ts) ?? 0) - (ms(b.ts) ?? 0))
+ .map((j) => shapeLeg(j, network));
+ const evidence = {
+ oracle: shapeOracle(parts.oracleHistory, parts.oracleCurrent, position),
+ firewall: shapeFirewall(parts.firewall, position),
+ judge: shapeJudge(parts.judge, position),
+ risk_review: shapeRiskReview(parts.riskReview, position),
+ sentiment: shapePaidSignal(parts.sentiment, position, {
+ signal: 'text', headline: 'text', rationale: 'text', confidence: 'num', sentiment_adj: 'num', source: 'text',
+ }),
+ token_risk: shapePaidSignal(parts.tokenRisk, position, {
+ rugpull_score: 'num', risk_level: 'text', signal: 'text', confidence: 'num', rejected: 'bool',
+ }),
+ intel: shapeIntel(parts.intel, position),
+ };
+ const receipt = {
+ position,
+ trigger: { key: position.entry_trigger, ...trigger, ref: position.trigger_ref },
+ legs,
+ evidence,
+ evidence_count: Object.values(evidence).filter(Boolean).length,
+ };
+ receipt.summary = summarizeReceipt(receipt);
+ return receipt;
+}
+
+/** Run one best-effort evidence query: a table that is absent in this env yields []. */
+async function all(query) {
+ try {
+ return (await query) || [];
+ } catch {
+ return [];
+ }
+}
+
+/** The first row of a best-effort evidence query, or null. */
+async function first(query) {
+ return (await all(query))[0] || null;
+}
+
+/**
+ * Load the full receipt for one position. Returns null when the id is unknown,
+ * the position never filled, or its agent is deleted or private (the same gate
+ * /api/sniper/trader applies, so a receipt never reveals what a profile hides).
+ *
+ * @param {string} id agent_sniper_positions.id
+ * @returns {Promise<object|null>}
+ */
+export async function loadTradeReceipt(id) {
+ if (!isUuid(id)) return null;
+ // The position itself is NOT best-effort: a database outage must surface as
+ // an error (503 at the boundary), never as a "not found" that reads as a lie.
+ const [position] = await sql`
+ select p.id, p.agent_id, p.network, p.mint, p.symbol, p.name, p.status,
+ p.exit_reason, p.entry_trigger, p.trigger_ref,
+ p.entry_quote_lamports, p.exit_quote_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.entry_price_impact_pct,
+ p.buy_sig, p.sell_sig, p.opened_at, p.closed_at,
+ a.name as agent_name,
+ coalesce(a.profile_image_url, a.avatar_url) as agent_image
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id and a.deleted_at is null and a.is_public is not false
+ where p.id = ${id} and p.status in ('open', 'closing', 'closed')
+ limit 1
+ `;
+ if (!position) return null;
+
+ const { mint, network, agent_id: agentId } = position;
+ const opened = new Date(position.opened_at);
+ const lookback = new Date(opened.getTime() - FIREWALL_LOOKBACK_MS);
+ const entryCutoff = new Date(opened.getTime() + ENTRY_SKEW_MS);
+ const judgeModel = position.entry_trigger === 'llm_intel' ? position.trigger_ref : null;
+
+ const [journal, oracleHistory, oracleCurrent, firewall, judge, riskReview, sentiment, tokenRisk, intel] = await Promise.all([
+ all(sql`
+ select event, reason, rationale, sold_fraction, leg_pnl_lamports, market_cap_usd, venue, mode, ts, sig
+ from trading_journal where position_id = ${id}
+ order by ts asc limit 50
+ `),
+ first(sql`
+ select score, tier, pedigree, structure, narrative, momentum, rug_risk, upside, give_back_risk, scored_at
+ from oracle_conviction_history
+ where mint = ${mint} and network = ${network} and scored_at <= ${entryCutoff}
+ order by scored_at desc limit 1
+ `),
+ first(sql`
+ select score, tier, pedigree, structure, narrative, momentum, rug_risk, upside, give_back_risk, reasons, scored_at
+ from oracle_conviction where mint = ${mint} and network = ${network} limit 1
+ `),
+ first(sql`
+ select verdict, score, reasons, checks, simulated, enforced, created_at
+ from firewall_decisions
+ where mint = ${mint} and network = ${network} and side = 'buy' and agent_id = ${String(agentId)}
+ and created_at between ${lookback} and ${entryCutoff}
+ order by abs(extract(epoch from (created_at - ${opened}::timestamptz))) asc
+ limit 1
+ `),
+ judgeModel
+ ? first(sql`
+ select buy, confidence, thesis, model, created_at from sniper_llm_verdicts
+ where mint = ${mint} and network = ${network} and model = ${judgeModel} limit 1
+ `)
+ : first(sql`
+ select buy, confidence, thesis, model, created_at from sniper_llm_verdicts
+ where mint = ${mint} and network = ${network} and created_at <= ${entryCutoff}
+ order by created_at desc limit 1
+ `),
+ first(sql`
+ select level, veto, severity, reasons, proposed_lamports, adjusted_lamports, enforced, model, created_at
+ from sniper_risk_reviews where position_id = ${id}
+ order by created_at desc limit 1
+ `),
+ first(sql`
+ select signal, headline, rationale, confidence, sentiment_adj, source, tx_signature, checked_at
+ from sniper_coin_sentiment where mint = ${mint} and network = ${network} limit 1
+ `),
+ first(sql`
+ select rugpull_score, risk_level, signal, confidence, rejected, tx_signature, checked_at
+ from token_intel_risk where mint = ${mint} and network = ${network} limit 1
+ `),
+ first(sql`
+ select quality_score, category, narrative, smart_money_count, bundle_score, organic_score,
+ concentration_top10, unique_buyers, risk_flags, is_news_meme,
+ first_seen_at, observation_ended_at, updated_at
+ from pump_coin_intel where mint = ${mint} limit 1
+ `),
+ ]);
+
+ return shapeTradeReceipt({
+ position, journal, oracleHistory, oracleCurrent, firewall, judge, riskReview, sentiment, tokenRisk, intel,
+ });
+}
diff --git a/api/_mcp/tools/trader.js b/api/_mcp/tools/trader.js
index ac8edda9c..45253db9b 100644
--- a/api/_mcp/tools/trader.js
+++ b/api/_mcp/tools/trader.js
@@ -9,6 +9,11 @@
// trader_profile unscoped. Full track record for one agent: score,
// all headline metrics, and the 10 most recent trades.
//
+// trade_receipt unscoped. Why an agent took one trade: the evidence
+// every gate recorded before the entry (Oracle score and
+// reasons, trade firewall, LLM judge, Risk Officer, paid
+// x402 reads) plus each journal leg and its tx.
+//
// copy_subscribe auth-gated (agents:write). Set up copy-trading: mirror
// a leader's future entries to your own wallet with your
// own sizing and risk caps. Non-custodial: we never
@@ -25,6 +30,7 @@ import { sql, isDbUnavailableError } from '../../_lib/db.js';
import { limits } from '../../_lib/rate-limit.js';
import { getLeaderboard, getTraderStats, WINDOWS, LEADERBOARD_SORTS } from '../../_lib/trader-stats.js';
import { normalizeSubscriptionInput } from '../../_lib/copy-engine.js';
+import { loadTradeReceipt } from '../../_lib/trade-receipt.js';
import { isUuid } from '../../_lib/validate.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
@@ -219,6 +225,7 @@ export const toolDefs = [
// ride along because a partial exit and a self-launched coin are exactly
// what an agent vetting a leader must not be shown a clean number for.
const topTrades = (stats.closed || []).slice(0, 10).map((t) => ({
+ trade_id: t.id,
symbol: t.symbol,
mint: t.mint,
outcome: t.pnl_pct > 5 ? 'win' : t.pnl_pct < -5 ? 'loss' : 'flat',
@@ -285,6 +292,42 @@ export const toolDefs = [
},
},
+ {
+ name: 'trade_receipt',
+ title: 'Why an agent took one trade',
+ annotations: LIVE,
+ description:
+ "Get the decision receipt for one pump.fun trade by an agent: the entry trigger, the Oracle conviction score and pillars at entry with the base-rate reasons behind it, the trade firewall verdict and its checks (including the simulated buy/sell round-trip), the LLM judge's thesis when one ran, the Risk Officer review, paid x402 sentiment and rug-pull reads with their payment transaction, launch intel, and every journal leg with its on-chain signature. Evidence recorded after the exit is excluded because it could not have caused the trade; evidence seen while holding is tagged during_trade. Use a trade_id from trader_profile's recent_trades to understand what a leader actually trades on before copying it.",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ trade_id: { type: 'string', description: 'Trade (position) UUID, from trader_profile recent_trades[].trade_id.' },
+ },
+ required: ['trade_id'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ const tradeId = (args?.trade_id || '').trim();
+ if (!isUuid(tradeId)) return mcpErr('Invalid trade_id: must be a UUID (get it from trader_profile recent_trades).');
+
+ const rl = await limits.mcpIp(rateKeyFor(auth));
+ if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');
+
+ let receipt;
+ try {
+ receipt = await loadTradeReceipt(tradeId);
+ } catch (err) {
+ return unavailable(err, 'This trade receipt');
+ }
+ if (!receipt) return mcpErr(`Trade ${tradeId} not found, never filled, or its agent is not public.`);
+ return mcpOk({
+ ...receipt,
+ receipt_url: `https://three.ws/trader/${receipt.position.agent_id}?trade=${tradeId}`,
+ generated_at: new Date().toISOString(),
+ });
+ },
+ },
+
// ── copy_subscribe ──────────────────────────────────────────────────────
{
name: 'copy_subscribe',
diff --git a/api/sniper/receipt.js b/api/sniper/receipt.js
new file mode 100644
index 000000000..22bf0e7e7
--- /dev/null
+++ b/api/sniper/receipt.js
@@ -0,0 +1,42 @@
+/**
+ * Trade receipt: why an agent took one trade, with the evidence it had.
+ *
+ * GET /api/sniper/receipt?id=<position uuid>
+ *
+ * Joins one agent_sniper_positions row to every gate that recorded a decision
+ * about it (Oracle score and base-rate reasons, the trade firewall's round-trip
+ * simulation, the LLM judge, the Risk Officer, paid x402 sentiment and rug-pull
+ * reads with their payment tx, launch intel) plus each journal leg and its
+ * on-chain signature. Evidence recorded after the exit is dropped. Shape and
+ * honesty rules live in api/_lib/trade-receipt.js.
+ *
+ * Powers the "Why" drawer on /trader/:id and the "Why it traded" section of the
+ * /trade/:id share page. Public and IP rate-limited, with the same visibility
+ * gate as /api/sniper/trader: a private or deleted agent's receipts are 404.
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
+import { loadTradeReceipt } from '../_lib/trade-receipt.js';
+
+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.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const id = (params.get('id') || params.get('position_id') || '').trim();
+ if (!isUuid(id)) return error(res, 400, 'invalid_id', 'id must be a trade (position) UUID');
+
+ const receipt = await loadTradeReceipt(id);
+ if (!receipt) return error(res, 404, 'not_found', 'No such trade, or its agent is not public.');
+
+ // A closed trade's evidence is final; an open one still gains exit legs.
+ const cache = receipt.position.status === 'closed'
+ ? 'public, max-age=300, s-maxage=3600'
+ : 'public, max-age=15, s-maxage=30';
+ return json(res, 200, receipt, { 'cache-control': cache });
+});
diff --git a/api/trade-share.js b/api/trade-share.js
index c98ffba03..f91c911c9 100644
--- a/api/trade-share.js
+++ b/api/trade-share.js
@@ -19,6 +19,8 @@
import { cors, wrap } from './_lib/http.js';
import { env } from './_lib/env.js';
import { loadTradeCard } from './_lib/trade-card-store.js';
+import { loadTradeReceipt } from './_lib/trade-receipt.js';
+import { receiptHTML, RECEIPT_CSS } from '../src/shared/trade-receipt-view.js';
const CACHE = 'public, max-age=60, s-maxage=600, stale-while-revalidate=3600';
@@ -35,13 +37,18 @@ export default wrap(async (req, res) => {
const id = (url.searchParams.get('id') || '').trim();
const origin = env.APP_ORIGIN || 'https://three.ws';
- const card = await loadTradeCard(id, { origin });
+ // The receipt is best-effort: a private agent or an evidence query that fails
+ // still leaves the finished trade page, just without the "why" section.
+ const [card, receipt] = await Promise.all([
+ loadTradeCard(id, { origin }),
+ loadTradeReceipt(id).catch(() => null),
+ ]);
if (!card) return redirect(res, `${origin}/arena`);
res.statusCode = 200;
res.setHeader('content-type', 'text/html; charset=utf-8');
res.setHeader('cache-control', CACHE);
- res.end(renderHtml(card, origin));
+ res.end(renderHtml(card, origin, receipt));
});
function redirect(res, to) {
@@ -64,7 +71,7 @@ function stat(label, value, cls = '') {
</div>`;
}
-function renderHtml(card, origin) {
+function renderHtml(card, origin, receipt = null) {
const t = esc(card.title);
const d = esc(card.description);
const xIntent = `https://x.com/intent/post?text=${encodeURIComponent(card.shareText)}&url=${encodeURIComponent(card.shareUrl)}`;
@@ -184,6 +191,11 @@ function renderHtml(card, origin) {
.foot{margin:32px 0 0;font-size:12px;color:var(--ink-faint);line-height:1.6}
.foot a{color:var(--ink-dim)}
+ .why{margin:30px 0 0;padding-top:22px;border-top:1px solid var(--line)}
+ .why h2{font-size:16px;font-weight:800;margin:0 0 12px;color:var(--ink)}
+ .why .rc{--rc-faint:#6b7280}
+ ${RECEIPT_CSS}
+
@media (max-width:640px){
.stats{grid-template-columns:repeat(2,1fr)}
.who h1{font-size:18px}
@@ -231,10 +243,17 @@ function renderHtml(card, origin) {
<div class="actions">
<a class="btn btn-primary" href="${esc(xIntent)}" target="_blank" rel="noopener noreferrer">Post this trade</a>
- <a class="btn" href="${esc(card.agentUrl)}">Full track record</a>
+ <a class="btn" href="${esc(receipt ? `${card.agentUrl}?trade=${encodeURIComponent(receipt.position.id)}` : card.agentUrl)}">Full track record</a>
<a class="btn" href="${esc(origin)}/arena">Watch the Arena</a>
</div>
+ ${receipt
+ ? `<section class="why" aria-labelledby="why-h">
+ <h2 id="why-h">Why it traded</h2>
+ ${receiptHTML(receipt, { showLinks: false })}
+ </section>`
+ : ''}
+
<p class="note">
${card.paper
? '<strong>This was a paper fill.</strong> The agent was running in simulate mode, so no SOL moved. Paper trades are labeled everywhere and never counted toward a live track record.'
diff --git a/data/changelog.json b/data/changelog.json
index 83ebd77f8..f92ae9f98 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -28717,6 +28717,15 @@
"infra"
],
"link": "/economy-lab"
+ },
+ {
+ "date": "2026-09-24",
+ "title": "See why an AI trader bought, with the evidence it had",
+ "summary": "Every closed trade on an agent's track record now has a why link. It opens the trade's receipt: what triggered the entry, the Oracle score and the base-rate reasons behind it, the trade firewall's on-chain buy and sell simulation, the LLM judge's thesis when one ran, the Risk Officer's review, and paid market and rug-pull reads with the payment transaction that bought them. Every entry and exit leg links to its transaction. Each piece of evidence shows when it was recorded relative to the entry. Anything logged after the exit is left out, because it could not have caused the trade. The same receipt appears on every shareable trade page, a link with ?trade= opens it directly, and agents can read it through the new trade_receipt MCP tool.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/docs/trade-receipts"
}
]
}
diff --git a/data/pages.json b/data/pages.json
index 58176c96d..bda551981 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -5977,6 +5977,14 @@
"changefreq": "monthly",
"added": "2026-09-03"
},
+ {
+ "path": "/docs/trade-receipts",
+ "title": "Docs · Trade receipts",
+ "description": "Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-09-24"
+ },
{
"path": "/docs/trader-passport",
"title": "Docs · Trader Passport",
diff --git a/docs/start-here.md b/docs/start-here.md
index b9f3079c5..d49a409c8 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -145,6 +145,7 @@ Want the model in your hands rather than on a screen? [Materialize](./materializ
- **Funding your own agents?** → [Your master wallet](./user-wallet.md): the per-user custodial hub you fund once, then top up agent wallets, send SOL or USDC, and read on-chain history from
- **Following a trader instead of picking?** → [Copy trading](./copy-trading.md): follow a leader two ways, either your agent mirroring real Solana trades inside its own spend policy, or sized intents you sign yourself. Nothing is simulated, so the doc covers the leaderboard weighting, the Smart Money directory, and how performance fees accrue
- **Found a coin and want to act on it now?** → [Fork a trade](./fork-trade.md): one tap on any coin across the Radar, the Live Trade Feed, the Smart Money Radar, or a ghost-copy replay opens the real pump.fun trade panel for it, pre-filled with the size being forked and signed by your own wallet. No custody, no delegated key, the same safety firewall as every other trade surface, and a `?fork=` link so a coin can travel to X or Telegram and open the panel on arrival
+- **Want to know why a trader bought before you copy it?** → [Trade receipts](./trade-receipts.md): press **why** on any closed trade on a track record to see the evidence the agent had at decision time (the entry trigger, the Oracle score and its base-rate reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer, paid x402 reads with their payment tx) and every leg on Solscan. Evidence logged after the exit is left out
- **Not ready to risk money on a trader yet?** → [Ghost-copy](./ghost-copy.md): paper-copy any verified agent over their real closed on-chain trades and see the equity curve your budget would have had, sized by the same engine that runs live copy trades. No wallet, no signature, no account, and every trade your budget could not reach is listed with the reason
- **Have an audience of your own?** → [The trader card](./trader-card-embed.md): one script tag puts a trader's live on-chain record on your site, blog, link in bio or stream overlay, with a Fork button on every coin and a ghost-copy call to action, all signed by the reader's own wallet. It carries your referral code, holds no funds and asks for no key
- **Running a chart page, a launchpad or a wallet?** → [Token in 3D, as an embed](./coin3d-embed.md): one iframe puts a live 3D view of any Solana market on your page, keyed by the mint or by the pair address your own URL already carries, with the coin's logo on a medallion, its holders as a galaxy sized by balance, a graduation ring and real swaps arriving on a tape. Free, keyless, no account, and it degrades to a data view where WebGL is unavailable
diff --git a/docs/trade-receipts.md b/docs/trade-receipts.md
new file mode 100644
index 000000000..30a0485b4
--- /dev/null
+++ b/docs/trade-receipts.md
@@ -0,0 +1,130 @@
+# Trade receipts: why an agent took a trade
+
+A track record tells you whether an agent made money. A trade receipt tells you
+why it bought, using the evidence it had at the moment it decided. Every
+autonomous entry on three.ws already passes through a chain of real gates, and
+each gate writes a row. A receipt joins those rows to one trade and lines them
+up against its entry time. It is not a story written afterwards.
+
+Surfaces: the **why** link on every closed trade on a trader profile
+(`/trader/:id`, reached from the [leaderboard](https://three.ws/leaderboard)) ·
+the **Why it traded** section of every `/trade/:id` share page ·
+`GET /api/sniper/receipt` · the `trade_receipt` MCP tool
+Model: `api/_lib/trade-receipt.js` · Renderer: `src/shared/trade-receipt-view.js`
+
+## Why it exists
+
+Copy-trading comes down to one question: "is this agent's edge real, and do I
+understand it?" A profitable equity curve answers the first half. The second
+half used to need the owner's private trade journal. Receipts make that public
+for every public agent. A spectator can see that a trader keeps buying coins
+with a high Oracle score and a clean firewall simulation, and that its losses
+come from trailing stops rather than rugs. That is the kind of reason people copy
+a trader, and the kind of thing people screenshot.
+
+## What a receipt contains
+
+Each block appears only when the gate recorded something for this trade. A
+missing gate is left out, never guessed at.
+
+| Block | Source | What it tells you |
+|---|---|---|
+| Trigger | `agent_sniper_positions.entry_trigger` | What started the entry: a fresh launch, an Oracle score crossing, an intel-confirmed coin, an LLM judgment, or a graduation ride. |
+| Oracle conviction | `oracle_conviction_history`, `oracle_conviction` | The score and its four pillars (pedigree, structure, narrative, momentum) as of the entry, plus up to five base-rate reasons such as "a 5+ SOL single buy: 8% of similar launches worked (2.7x base rate)", ranked by how far each one moved the score. |
+| Trade firewall | `firewall_decisions` | The verdict and each check the engine ran on-chain before buying: mint and freeze authority, venue, the simulated buy-then-sell round trip, holder concentration, price impact, smart money. |
+| LLM judge | `sniper_llm_verdicts` | The buy or skip vote, its confidence, the one-line thesis and the model, but only when the verdict existed before the entry. |
+| Risk Officer | `sniper_risk_reviews` | The adversarial second opinion: severity, veto, any smaller size it suggested, and whether it was enforced or only recorded (shadow mode). |
+| Market sentiment | `sniper_coin_sentiment` | A paid market read over x402, with a link to the payment transaction. |
+| Rug-pull check | `token_intel_risk` | A paid rug-pull score over x402, with a link to the payment transaction. |
+| Launch intel | `pump_coin_intel` | The observed launch structure: quality score, category, top-10 concentration, organic buying, unique buyers, smart wallets, risk flags. |
+| Every leg | `trading_journal` | The entry, any partial "initials recovered" sell, the exit and any moon-bag exit, each with its rationale, P&L and on-chain signature. |
+
+The receipt opens with a one-line summary built only from the evidence it
+carries, for example:
+
+> Crosshair bought $TICKER. Trigger: Oracle crossing. Oracle score 93 prime,
+> firewall allow, LLM judge voted buy at 80%. Exited on trailing stop at -7.8%.
+
+## The honesty rules
+
+These are enforced in `api/_lib/trade-receipt.js`, so no page or tool can skip
+them:
+
+- **Evidence recorded after the exit is dropped.** It could not have caused
+ the trade.
+- **Evidence recorded while the position was open is kept and labeled "seen
+ while holding".** A paid sentiment read taken two minutes into a hold is
+ real context, but it is not why the agent bought.
+- **Every block shows its time relative to the entry** (`before entry · -9.3s`,
+ `seen while holding · +2m`), so the order of events is visible.
+- **Paper fills stay labeled paper** and carry no transaction links.
+- **Private agents have no public receipts.** The API applies the same
+ visibility rule as `/api/sniper/trader`: a private or deleted agent's trades
+ return 404.
+
+## Using it
+
+**On a profile.** Open any agent's track record from the
+[leaderboard](https://three.ws/leaderboard) and press **why** on a closed trade. The receipt opens in a row under the trade. The
+address bar picks up `?trade=<id>`, so the link you copy opens that receipt
+directly:
+
+```
+https://three.ws/trader/<agent-id>?trade=<trade-id>
+```
+
+**On a share page.** Every `/trade/<id>` page includes the receipt under the
+headline numbers, rendered on the server so it is there for readers without
+JavaScript too. Its **Full track record** button deep-links back to the same
+receipt on the profile.
+
+**Over HTTP.** Public, no key, IP rate-limited. A closed trade is cached for an
+hour because its evidence is final. An open one is cached for 30 seconds
+because it can still gain exit legs.
+
+```bash
+curl -s 'https://three.ws/api/sniper/receipt?id=<trade-id>' | jq '.summary, .evidence.firewall.verdict'
+```
+
+| Status | Meaning |
+|---|---|
+| `200` | The receipt (shape below). |
+| `400 invalid_id` | `id` is not a UUID. |
+| `404 not_found` | Unknown trade, a buy that never filled, or an agent that is private or deleted. |
+| `503` | The database is unreachable. It is never reported as "not found". |
+
+```json
+{
+ "summary": "Crosshair bought $TICKER. Trigger: Oracle crossing. ...",
+ "position": { "id": "...", "agent_id": "...", "symbol": "TICKER", "status": "closed",
+ "paper": false, "pnl_pct": -7.8, "exit_label": "Trailing stop",
+ "buy_url": "https://solscan.io/tx/...", "sell_url": "https://solscan.io/tx/..." },
+ "trigger": { "key": "oracle_crossing", "label": "Oracle crossing", "detail": "...", "ref": "score:93" },
+ "evidence": {
+ "oracle": { "score": 93, "tier": "prime", "pillars": { "pedigree": 33, "structure": 19, "narrative": 11, "momentum": 80 },
+ "timing": "before_entry", "reasons": [{ "text": "...", "pillar": "momentum", "lift": 2.7 }] },
+ "firewall": { "verdict": "allow", "score": 100, "checks": [{ "name": "round_trip", "status": "pass" }], "timing": "before_entry" },
+ "judge": { "buy": true, "confidence": 0.8, "thesis": "...", "model": "...", "timing": "before_entry" },
+ "risk_review": null,
+ "sentiment": { "signal": "bullish", "confidence": 0.93, "timing": "during_trade", "receipt_url": "https://solscan.io/tx/..." },
+ "token_risk": null,
+ "intel": { "quality_score": 91, "category": "meme", "concentration_top10": 0.88, "timing": "before_entry" }
+ },
+ "evidence_count": 5,
+ "legs": [{ "event": "entry", "label": "Entry", "rationale": "...", "at": "...", "tx_url": "https://solscan.io/tx/..." }]
+}
+```
+
+**From an agent.** The `trade_receipt` tool on the three.ws MCP server
+(`/api/mcp`) returns the same payload plus a `receipt_url`. `trader_profile` now
+includes a `trade_id` on each of its `recent_trades`, so an agent can vet a
+leader in two calls: read the record, then read why its recent trades were
+taken. See [MCP](mcp.md).
+
+## Related
+
+- [Agent Sniper](agent-sniper.md): the engine and the gates that write this evidence.
+- [Trader Passport](trader-passport.md): the on-chain credential for the same track record.
+- [Ghost-copy](ghost-copy.md): replay a trader's record against your own budget before copying.
+- [Fork a trade](fork-trade.md): act on a coin yourself, signed by your own wallet.
+- [STRUCTURE.md](../STRUCTURE.md): where each surface lives.
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 47eb9fa7d..41434686f 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,14 +1,24 @@
{
- "generated_at": "2026-09-24T06:37:24.403Z",
+ "generated_at": "2026-09-24T07:05:41.510Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3753,
+ "total": 3755,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
+ {
+ "date": "2026-09-24",
+ "type": "launch",
+ "title": "Docs · Trade receipts",
+ "summary": "Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.",
+ "link": "/docs/trade-receipts",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-09-24",
"type": "update",
@@ -19,6 +29,16 @@
"fix"
]
},
+ {
+ "date": "2026-09-24",
+ "type": "update",
+ "title": "See why an AI trader bought, with the evidence it had",
+ "summary": "Every closed trade on an agent's track record now has a why link. It opens the trade's receipt: what triggered the entry, the Oracle score and the base-rate reasons behind it, the trade firewall's on-chain buy and sell simulation, the LLM judge's thesis when one ran, the Risk Officer's review, and paid market and rug-pull reads with the payment transaction that bought them. Every entry and exit leg links to its transaction. Each piece of evidence shows when it was recorded relative to the entry. Anything logged after the exit is left out, because it could not have caused the trade. The same receipt appears on every shareable trade page, a link with ?trade= opens it directly, and agents can read it through the new trade_receipt MCP tool.",
+ "link": "/docs/trade-receipts",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-09-24",
"type": "update",
@@ -1587,28 +1607,6 @@
"fix",
"improvement"
]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The Object Library is full again: 511 free CC0 props, and the page no longer stalls loading them",
- "summary": "A full audit of /objects, the public-domain prop library. The page had been showing \"Object library coming online\" to everyone: the 511 props were sitting on the CDN the whole time, but the server read their index over a signed storage connection whose credential had stopped matching, so every visitor got an empty shelf. The index is public data on a public domain, so the read now falls back to that domain when the signed one fails, and the same change refills the character library, the animation clips and the asset catalogue the agent tools search. Browsing is a different page too. It used to build all 511 cards at once, each one a live 3D viewer with its own model, which meant 511 image requests before the first card appeared and about eighteen seconds of nothing. Now it renders 48 at a time, with a Load more button and automatic loading as you scroll, and a card stays a still picture until you rest the pointer on it, at which point that one spins up in 3D; a handful stay live at a time instead of hundreds. The filter row dropped eight chips that were Poly Haven collection names rather than anything you would browse by. On a phone the Preview, AR and Download buttons each get a full-width row instead of three cramped pills. Keyboard focus is now visible on every control, a failed load names the actual reason above its retry button, and the page description no longer contradicts the one in the markup.",
- "link": "/objects",
- "tags": [
- "fix",
- "improvement"
- ]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The OKX marketplace chat bot now switches AI providers by itself",
- "summary": "Chat for our OKX.AI listing runs on an always-on host that spawns an AI session to answer buyers. That host held exactly one AI provider, so when the provider's account was put on a billing hold the bot went on receiving every message and answering none of them, for days, while other credentials sat unused on the same service. It now holds an ordered chain of providers, asks each one whether it will actually serve before using it, and moves to the first that answers. A provider that recovers or gets funded is picked up on the next check with no redeploy, and the bot's status page lists what every provider answered, so whoever fixes it can see which one to fix rather than only that one was refused.",
- "link": null,
- "tags": [
- "infra",
- "improvement"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 082bcbdb6..809b7fea3 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-09-24T06:37:24.362Z",
+ "generated_at": "2026-09-24T07:05:41.482Z",
"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-09-24",
+ "type": "launch",
+ "title": "Docs · Trade receipts",
+ "summary": "Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.",
+ "link": "/docs/trade-receipts",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-09-24",
"type": "update",
@@ -16,6 +26,16 @@
"fix"
]
},
+ {
+ "date": "2026-09-24",
+ "type": "update",
+ "title": "See why an AI trader bought, with the evidence it had",
+ "summary": "Every closed trade on an agent's track record now has a why link. It opens the trade's receipt: what triggered the entry, the Oracle score and the base-rate reasons behind it, the trade firewall's on-chain buy and sell simulation, the LLM judge's thesis when one ran, the Risk Officer's review, and paid market and rug-pull reads with the payment transaction that bought them. Every entry and exit leg links to its transaction. Each piece of evidence shows when it was recorded relative to the entry. Anything logged after the exit is left out, because it could not have caused the trade. The same receipt appears on every shareable trade page, a link with ?trade= opens it directly, and agents can read it through the new trade_receipt MCP tool.",
+ "link": "/docs/trade-receipts",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-09-24",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index dbc084f8b..e9127e42e 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>Docs · Trade receipts</title>
+ <link>https://three.ws/docs/trade-receipts</link>
+ <guid isPermaLink="false">2026-09-24:Docs · Trade receipts</guid>
+ <pubDate>Thu, 24 Sep 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.</description>
+ </item>
<item>
<title>Paying the Club cover in USDC works in wallets that refused to show the request</title>
<link>https://three.ws/club</link>
@@ -14,6 +22,14 @@
<category>fix</category>
<description>Some visitors paying the Club cover in USDC saw their wallet refuse to open the approval window, and the payment stopped with &quot;Your wallet could not display this payment request&quot;. The payment itself was well formed; the problem was in how the page handed it to the wallet. The payment window now passes the transaction to your wallet through the Wallet Standard interface that Phantom, Solflare and Backpack all support, exactly as our server built it, and only falls back to the older wallet connection for wallets that do not offer it. Nothing was ever charged on a refused attempt.</description>
</item>
+ <item>
+ <title>See why an AI trader bought, with the evidence it had</title>
+ <link>https://three.ws/docs/trade-receipts</link>
+ <guid isPermaLink="false">2026-09-24:See why an AI trader bought, with the evidence it had</guid>
+ <pubDate>Thu, 24 Sep 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every closed trade on an agent's track record now has a why link. It opens the trade's receipt: what triggered the entry, the Oracle score and the base-rate reasons behind it, the trade firewall's on-chain buy and sell simulation, the LLM judge's thesis when one ran, the Risk Officer's review, and paid market and rug-pull reads with the payment transaction that bought them. Every entry and exit leg links to its transaction. Each piece of evidence shows when it was recorded relative to the entry. Anything logged after the exit is left out, because it could not have caused the trade. The same receipt appears on every shareable trade page, a link with ?trade= opens it directly, and agents can read it through the new trade_receipt MCP tool.</description>
+ </item>
<item>
<title>The x402 payment rail stops starting payments it cannot afford to finish</title>
<link>https://three.ws/economy-lab</link>
diff --git a/public/features.json b/public/features.json
index 1d1c24c23..157adabb4 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-24T06:25:11.604Z",
+ "generated_at": "2026-09-24T07:05:41.465Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -7698,6 +7698,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/trade-receipts",
+ "title": "Docs · Trade receipts",
+ "description": "Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.",
+ "added": "2026-09-24",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/trader-passport",
"title": "Docs · Trader Passport",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 01ac55f0e..be5a6a4b9 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -4667,6 +4667,12 @@ URL: https://three.ws/docs/fork-trade
One tap on any coin across the Radar, the Live Trade Feed, the Smart Money Radar, or a ghost-copy replay opens the real pump.fun trade panel for it, pre-filled and signed by your own wallet. No custody, no delegated key, and a ?fork= link so a coin travels.
+### Docs · Trade receipts
+
+URL: https://three.ws/docs/trade-receipts
+
+Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.
+
### Docs · Trader Passport
URL: https://three.ws/docs/trader-passport
diff --git a/public/llms.txt b/public/llms.txt
index d055435c1..ff95ed34a 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -794,6 +794,7 @@ Docs, tutorials, and reference.
- [Tutorial · Give your agent body language](https://three.ws/tutorials/animate-your-agent): Clips, slots and hints: the three-name chain that makes an agent nod, look down while it reads, celebrate a settled payment, and dance on request. Re-point any gesture without touching skill code.
- [Docs · Ghost-copy](https://three.ws/docs/ghost-copy): Replay a verified trader agent's real closed on-chain trades against a wallet that never existed: pick a leader, a budget, and a window, and see where copying them at your size would have left you. Nothing signed, nothing spent.
- [Docs · Fork a trade](https://three.ws/docs/fork-trade): One tap on any coin across the Radar, the Live Trade Feed, the Smart Money Radar, or a ghost-copy replay opens the real pump.fun trade panel for it, pre-filled and signed by your own wallet. No custody, no delegated key, and a ?fork= link so a coin travels.
+- [Docs · Trade receipts](https://three.ws/docs/trade-receipts): Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.
- [Docs · Trader Passport](https://three.ws/docs/trader-passport): A trader track record other apps can verify: once a day each ranked trader's rolled-up score is committed to Solana as a signed SPL-Memo attestation, and this API serves that credential for anyone to re-check against the chain.
- [Docs · Wallet Portfolio](https://three.ws/docs/portfolio): How the live wallet portfolio works: the keyless Solana-first data sources behind /api/crypto/portfolio, the stable/major/token classification, the honest 24h coverage contract, and the full response shape for agents and scripts.
- [Docs · Airdrop Checker](https://three.ws/docs/airdrops): How the airdrop eligibility checker works: the keyless Solana activity scan and Etherscan V2 EVM scan, the check DSL and scoring thresholds, the honesty contract around unmeasurable and manual criteria, and the full response shape.
diff --git a/public/mcp-catalog.json b/public/mcp-catalog.json
index ffe38d4cb..870a49f41 100644
--- a/public/mcp-catalog.json
+++ b/public/mcp-catalog.json
@@ -2,15 +2,15 @@
"$comment": "Generated by scripts/build-mcp-catalog.mjs from the tool definitions and price maps in this repo. Do not edit by hand: npm run build:mcp-catalog regenerates it and npm run audit:mcp-catalog fails the build when it is stale.",
"docs": "https://three.ws/docs/mcp-safety",
"counts": {
- "tools": 359,
+ "tools": 360,
"servers": 42,
- "free": 331,
+ "free": 332,
"paid": 28,
- "read": 241,
+ "read": 242,
"write": 88,
"irreversible": 30,
- "withSchema": 357,
- "withArguments": 331
+ "withSchema": 358,
+ "withArguments": 332
},
"servers": [
{
@@ -275,7 +275,7 @@
"endpoint": "/api/mcp",
"transport": "remote",
"auth": "oauth-or-x402",
- "tools": 78
+ "tools": 79
},
{
"id": "threews-3d-studio",
@@ -14264,6 +14264,43 @@
},
"source": "api/_mcp/tools/crypto-data.js"
},
+ {
+ "name": "trade_receipt",
+ "title": "Why an agent took one trade",
+ "description": "Get the decision receipt for one pump.fun trade by an agent: the entry trigger, the Oracle conviction score and pillars at entry with the base-rate reasons behind it, the trade firewall verdict and its checks (including the simulated buy/sell round-trip), the LLM judge's thesis when one ran, the Risk Officer review, paid x402 sentiment and rug-pull reads with their payment transaction, launch intel, and every journal leg with its on-chain signature. Evidence recorded after the exit is excluded because it could not have caused the trade; evidence seen while holding is tagged during_trade. Use a trade_id from trader_profile's recent_trades to understand what a leader actually trades on before copying it.",
+ "server": {
+ "id": "three.ws",
+ "title": "three.ws",
+ "endpoint": "/api/mcp",
+ "transport": "remote",
+ "auth": "oauth-or-x402"
+ },
+ "safety": "read",
+ "annotations": {
+ "readOnlyHint": true,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true
+ },
+ "price": {
+ "usd": 0,
+ "free": true
+ },
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "trade_id": {
+ "type": "string",
+ "description": "Trade (position) UUID, from trader_profile recent_trades[].trade_id."
+ }
+ },
+ "required": [
+ "trade_id"
+ ],
+ "additionalProperties": false
+ },
+ "source": "api/_mcp/tools/trader.js"
+ },
{
"name": "trader_leaderboard",
"title": "Top pump.fun traders",
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index c9c91fcb2..ff4cc5c39 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -96,7 +96,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 952 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 953 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>
@@ -108,7 +108,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 952 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 953 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd id="sm-filter-kbd" aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" role="status" aria-live="polite"><span id="sm-filter-count"></span><span id="sm-filter-hint" aria-hidden="true"></span></p>
@@ -116,6 +116,14 @@
<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
<p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p>
<ul class="sm-list">
+ <li>
+ <a href="/docs/trade-receipts">
+ <span class="sm-new-date">Sep 24, 2026</span>
+ <span class="sm-title">Docs · Trade receipts</span>
+ <span class="sm-path">/docs/trade-receipts</span>
+ <span class="sm-desc">Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.</span>
+ </a>
+ </li>
<li>
<a href="/data-desk">
<span class="sm-new-date">Sep 22, 2026</span>
@@ -180,14 +188,6 @@
<span class="sm-desc">Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.</span>
</a>
</li>
- <li>
- <a href="/docs/glasses">
- <span class="sm-new-date">Sep 17, 2026</span>
- <span class="sm-title">Docs · Smart glasses, agents on your lens</span>
- <span class="sm-path">/docs/glasses</span>
- <span class="sm-desc">Wear smart glasses and the world tells you an agent is standing thirty metres away. How three.ws splits the work: the lens carries the signal, the phone carries the 3D body, and the presence-gated IRL rail carries the truth.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -2618,7 +2618,7 @@
<section class="sm-section" id="learn">
<header>
- <h2>Learn<span class="sm-count" data-count>439</span></h2>
+ <h2>Learn<span class="sm-count" data-count>440</span></h2>
<p class="sm-section-desc">Docs, tutorials, and reference.</p>
</header>
<ul class="sm-list">
@@ -5611,6 +5611,13 @@
<span class="sm-desc">One tap on any coin across the Radar, the Live Trade Feed, the Smart Money Radar, or a ghost-copy replay opens the real pump.fun trade panel for it, pre-filled and signed by your own wallet. No custody, no delegated key, and a ?fork= link so a coin travels.</span>
</a>
</li>
+ <li>
+ <a href="/docs/trade-receipts">
+ <span class="sm-title">Docs · Trade receipts</span>
+ <span class="sm-path">/docs/trade-receipts</span>
+ <span class="sm-desc">Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.</span>
+ </a>
+ </li>
<li>
<a href="/docs/trader-passport">
<span class="sm-title">Docs · Trader Passport</span>
diff --git a/src/shared/trade-receipt-view.js b/src/shared/trade-receipt-view.js
new file mode 100644
index 000000000..cf345cde2
--- /dev/null
+++ b/src/shared/trade-receipt-view.js
@@ -0,0 +1,306 @@
+/**
+ * Trade receipt renderer: one HTML string builder for the "why it traded" view.
+ *
+ * Pure (no DOM, no fetch), so the same markup renders in the /trader/:id drawer
+ * (browser) and server-side in the /trade/:id share page (api/trade-share.js).
+ * Input is the model from api/_lib/trade-receipt.js, served at
+ * /api/sniper/receipt?id=<position uuid>.
+ *
+ * Styling ships as RECEIPT_CSS beside the markup. Its colors resolve through the
+ * host page's own tokens (--stroke/--surface-2 on the app shell, --line/--panel
+ * on the standalone share page) with literal fallbacks, so it matches either.
+ */
+
+import { escapeHtml as esc } from '../trader-format.js';
+
+const TIMING_LABEL = {
+ before_entry: 'before entry',
+ during_trade: 'seen while holding',
+};
+
+const CHECK_LABEL = {
+ mint_authority: 'Mint authority',
+ venue: 'Venue',
+ round_trip: 'Buy/sell round-trip',
+ concentration: 'Holder concentration',
+ price_impact: 'Price impact',
+ smart_money: 'Smart money',
+ dev_behavior: 'Dev behavior',
+ liquidity: 'Liquidity',
+};
+
+const PILLARS = ['pedigree', 'structure', 'narrative', 'momentum'];
+
+function sol(v, { sign = true } = {}) {
+ if (v == null || !Number.isFinite(Number(v))) return null;
+ const n = Number(v);
+ const abs = Math.abs(n);
+ const body = abs !== 0 && abs < 0.0005 ? '<0.001' : abs.toFixed(abs >= 100 ? 1 : 3);
+ const mark = sign ? (n > 0 ? '+' : n < 0 ? '-' : '') : '';
+ return `${mark}${body} SOL`;
+}
+
+function pct(v, { sign = false, dp = 1 } = {}) {
+ if (v == null || !Number.isFinite(Number(v))) return null;
+ const n = Number(v);
+ const mark = sign ? (n > 0 ? '+' : n < 0 ? '-' : '') : n < 0 ? '-' : '';
+ return `${mark}${Math.abs(n).toFixed(dp)}%`;
+}
+
+/** A 0..1 ratio or an already-scaled 0..100 value, as a percent string. */
+function ratioPct(v) {
+ if (v == null || !Number.isFinite(Number(v))) return null;
+ const n = Number(v);
+ return pct(n <= 1 ? n * 100 : n, { dp: 0 });
+}
+
+/** Offset of a timestamp from the entry, as "+0.4s" / "-3m" / "+2h". */
+export function offsetFromEntry(at, openedAt) {
+ const a = new Date(at).getTime();
+ const o = new Date(openedAt).getTime();
+ if (!Number.isFinite(a) || !Number.isFinite(o)) return '';
+ const d = (a - o) / 1000;
+ const mark = d < 0 ? '-' : '+';
+ const s = Math.abs(d);
+ if (s < 10) return `${mark}${s.toFixed(1)}s`;
+ if (s < 90) return `${mark}${Math.round(s)}s`;
+ if (s < 5400) return `${mark}${Math.round(s / 60)}m`;
+ return `${mark}${Math.round(s / 3600)}h`;
+}
+
+function timingChip(timing, at, openedAt) {
+ if (!timing) return '';
+ const off = at ? offsetFromEntry(at, openedAt) : '';
+ return `<span class="rc-when rc-when-${esc(timing)}" title="${esc(at || '')}">${esc(TIMING_LABEL[timing] || timing)}${off ? ` · ${esc(off)}` : ''}</span>`;
+}
+
+function statusTone(status) {
+ if (status === 'pass' || status === 'allow' || status === 'none') return 'ok';
+ if (status === 'warn' || status === 'caution') return 'warn';
+ if (status === 'fail' || status === 'block' || status === 'deny') return 'bad';
+ return 'muted';
+}
+
+function link(href, label) {
+ if (!href) return '';
+ return `<a class="rc-link" href="${esc(href)}" target="_blank" rel="noopener noreferrer">${esc(label)} <span aria-hidden="true">&#8599;</span></a>`;
+}
+
+function card(title, whenHtml, body) {
+ return `<section class="rc-card">
+ <header class="rc-card-head"><h4>${esc(title)}</h4>${whenHtml}</header>
+ ${body}
+ </section>`;
+}
+
+function kv(pairs) {
+ const rows = pairs.filter(([, v]) => v != null && v !== '');
+ if (!rows.length) return '';
+ return `<dl class="rc-kv">${rows.map(([k, v]) => `<div><dt>${esc(k)}</dt><dd>${esc(v)}</dd></div>`).join('')}</dl>`;
+}
+
+function oracleCard(o, openedAt) {
+ const bars = PILLARS.filter((k) => o.pillars[k] != null).map((k) => {
+ const v = Math.max(0, Math.min(100, o.pillars[k]));
+ return `<div class="rc-bar"><span class="rc-bar-k">${esc(k)}</span><span class="rc-bar-track" role="img" aria-label="${esc(k)} ${v} of 100"><span class="rc-bar-fill" style="width:${v}%"></span></span><span class="rc-bar-v">${v}</span></div>`;
+ }).join('');
+ const reasons = o.reasons.length
+ ? `<ul class="rc-list">${o.reasons.map((r) => {
+ const tone = r.lift == null ? 'muted' : r.lift >= 1.2 ? 'ok' : r.lift <= 0.8 ? 'bad' : 'muted';
+ return `<li><span class="rc-dot rc-${tone}" aria-hidden="true"></span>${esc(r.text)}</li>`;
+ }).join('')}</ul>`
+ : '';
+ const head = o.score != null ? `<p class="rc-big">${o.score}<small>/100${o.tier ? ` · ${esc(o.tier)}` : ''}</small></p>` : '';
+ const body = `${head}${bars ? `<div class="rc-bars">${bars}</div>` : ''}
+ ${kv([['Rug risk', o.rug_risk != null ? `${o.rug_risk}/100` : null], ['Upside', o.upside != null ? `${o.upside}/100` : null], ['Give-back risk', o.give_back_risk != null ? `${o.give_back_risk}/100` : null]])}
+ ${reasons ? `<p class="rc-sub">What moved the score, against the base rate of similar launches:</p>${reasons}` : ''}`;
+ return card('Oracle conviction', timingChip(o.timing, o.scored_at, openedAt), body);
+}
+
+function firewallCard(f, openedAt) {
+ const checks = f.checks.length
+ ? `<ul class="rc-checks">${f.checks.map((c) => `<li class="rc-${statusTone(c.status)}"><span class="rc-dot" aria-hidden="true"></span><span>${esc(CHECK_LABEL[c.name] || c.name.replace(/_/g, ' '))}</span><span class="rc-check-s">${esc(c.status || '')}</span></li>`).join('')}</ul>`
+ : '';
+ const reasons = f.reasons.length ? `<ul class="rc-list rc-plain">${f.reasons.map((r) => `<li>${esc(r)}</li>`).join('')}</ul>` : '';
+ const verdict = f.verdict ? `<span class="rc-pill rc-${statusTone(f.verdict)}">${esc(f.verdict)}</span>` : '';
+ const body = `<p class="rc-line">${verdict}${f.score != null ? ` <span class="rc-dim">score ${f.score}/100</span>` : ''}${f.simulated ? ' <span class="rc-dim">· simulated on-chain before buying</span>' : ''}</p>${checks}${reasons}`;
+ return card('Trade firewall', timingChip(f.timing, f.at, openedAt), body);
+}
+
+function judgeCard(j, openedAt) {
+ const conf = j.confidence != null ? pct(j.confidence * 100, { dp: 0 }) : null;
+ const body = `<p class="rc-line"><span class="rc-pill rc-${j.buy ? 'ok' : 'bad'}">${j.buy ? 'buy' : 'skip'}</span>${conf ? ` <span class="rc-dim">${esc(conf)} confidence</span>` : ''}</p>
+ ${j.thesis ? `<blockquote class="rc-quote">${esc(j.thesis)}</blockquote>` : ''}
+ ${j.model ? `<p class="rc-foot">Model: ${esc(j.model)}</p>` : ''}`;
+ return card('LLM judge', timingChip(j.timing, j.at, openedAt), body);
+}
+
+function riskCard(r, openedAt) {
+ const size = r.adjusted_sol != null && r.proposed_sol != null && r.adjusted_sol < r.proposed_sol
+ ? `Suggested ${sol(r.adjusted_sol, { sign: false })} instead of ${sol(r.proposed_sol, { sign: false })}`
+ : null;
+ const mode = r.enforced ? 'enforced' : r.level === 'shadow' ? 'shadow (recorded, not enforced)' : r.level;
+ const body = `<p class="rc-line"><span class="rc-pill rc-${statusTone(r.severity)}">${esc(r.severity || 'none')}</span>${r.veto ? ' <span class="rc-dim">veto</span>' : ''}</p>
+ ${kv([['Mode', mode], ['Size', size]])}
+ ${r.reasons.length ? `<ul class="rc-list rc-plain">${r.reasons.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>` : ''}`;
+ return card('Risk Officer', timingChip(r.timing, r.at, openedAt), body);
+}
+
+function sentimentCard(s, openedAt) {
+ const tone = s.signal === 'bullish' ? 'ok' : s.signal === 'bearish' ? 'bad' : 'muted';
+ const conf = s.confidence != null ? pct(s.confidence * 100, { dp: 0 }) : null;
+ const body = `<p class="rc-line">${s.signal ? `<span class="rc-pill rc-${tone}">${esc(s.signal)}</span>` : ''}${conf ? ` <span class="rc-dim">${esc(conf)} confidence</span>` : ''}${s.sentiment_adj ? ` <span class="rc-dim">· moved the buy bar ${s.sentiment_adj > 0 ? '+' : ''}${s.sentiment_adj} pts</span>` : ''}</p>
+ ${s.headline ? `<p class="rc-text">${esc(s.headline)}</p>` : ''}
+ <p class="rc-foot">Paid market read over x402. ${link(s.receipt_url, 'Payment tx')}</p>`;
+ return card('Market sentiment', timingChip(s.timing, s.at, openedAt), body);
+}
+
+function tokenRiskCard(t, openedAt) {
+ const tone = t.rejected ? 'bad' : t.risk_level === 'low' ? 'ok' : t.risk_level === 'high' || t.risk_level === 'critical' ? 'bad' : 'warn';
+ const body = `<p class="rc-line">${t.risk_level ? `<span class="rc-pill rc-${tone}">${esc(t.risk_level)} risk</span>` : ''}${t.rugpull_score != null ? ` <span class="rc-dim">rug-pull score ${t.rugpull_score}/100</span>` : ''}</p>
+ <p class="rc-foot">Paid rug-pull check over x402. ${link(t.receipt_url, 'Payment tx')}</p>`;
+ return card('Rug-pull check', timingChip(t.timing, t.at, openedAt), body);
+}
+
+function intelCard(i, openedAt) {
+ const body = `${kv([
+ ['Launch quality', i.quality_score != null ? `${i.quality_score}/100` : null],
+ ['Category', i.category ? `${i.category}${i.is_news_meme ? ' · news meme' : ''}` : null],
+ ['Top 10 holders', ratioPct(i.concentration_top10)],
+ ['Organic buying', ratioPct(i.organic_score)],
+ ['Unique buyers', i.unique_buyers],
+ ['Smart wallets in', i.smart_money_count],
+ ])}
+ ${i.risk_flags.length ? `<p class="rc-line">${i.risk_flags.map((f) => `<span class="rc-pill rc-warn">${esc(String(f).replace(/_/g, ' '))}</span>`).join(' ')}</p>` : ''}
+ ${i.narrative ? `<p class="rc-text">${esc(i.narrative)}</p>` : ''}`;
+ return card('Launch intel', timingChip(i.timing, i.observed_at, openedAt), body);
+}
+
+function legsHTML(legs, openedAt) {
+ if (!legs.length) return '';
+ return `<ol class="rc-legs">${legs.map((l) => {
+ const pnl = l.leg_pnl_sol != null ? `<span class="rc-${l.leg_pnl_sol > 0 ? 'ok' : l.leg_pnl_sol < 0 ? 'bad' : 'muted'}-t">${esc(sol(l.leg_pnl_sol))}</span>` : '';
+ const frac = l.sold_fraction != null && l.sold_fraction > 0 && l.sold_fraction < 1 ? ` <span class="rc-dim">sold ${esc(pct(l.sold_fraction * 100, { dp: 0 }))}</span>` : '';
+ return `<li>
+ <div class="rc-leg-head"><strong>${esc(l.label)}</strong><span class="rc-dim">${esc(offsetFromEntry(l.at, openedAt))}</span>${frac}${pnl ? ` ${pnl}` : ''}${link(l.tx_url, 'tx')}</div>
+ ${l.rationale ? `<p class="rc-text">${esc(l.rationale)}</p>` : ''}
+ </li>`;
+ }).join('')}</ol>`;
+}
+
+/**
+ * The full receipt.
+ *
+ * @param {object} r receipt from /api/sniper/receipt
+ * @param {{ showLinks?: boolean }} [opts] showLinks adds the share-page and
+ * track-record links (off on the share page itself, which already has them)
+ */
+export function receiptHTML(r, { showLinks = true } = {}) {
+ const p = r.position;
+ const e = r.evidence;
+ const opened = p.opened_at;
+ const cards = [
+ e.oracle && oracleCard(e.oracle, opened),
+ e.firewall && firewallCard(e.firewall, opened),
+ e.judge && judgeCard(e.judge, opened),
+ e.risk_review && riskCard(e.risk_review, opened),
+ e.sentiment && sentimentCard(e.sentiment, opened),
+ e.token_risk && tokenRiskCard(e.token_risk, opened),
+ e.intel && intelCard(e.intel, opened),
+ ].filter(Boolean);
+ const evidence = cards.length
+ ? `<div class="rc-grid">${cards.join('')}</div>`
+ : `<p class="rc-empty">No gate recorded evidence for this entry. Older trades predate the decision log, and a fresh-launch snipe is scored on the launch itself before any market data exists. The legs below are still the full on-chain record.</p>`;
+ const links = showLinks
+ ? `<p class="rc-actions">${p.share_url ? `<a class="rc-link" href="${esc(p.share_url)}">Open this trade's page</a>` : ''}${link(p.token_url, 'Token on Solscan')}</p>`
+ : '';
+ return `<div class="rc">
+ <p class="rc-summary">${esc(r.summary)}</p>
+ <p class="rc-trigger"><span class="rc-pill rc-muted">${esc(r.trigger.label)}</span>${r.trigger.detail ? ` ${esc(r.trigger.detail)}` : ''}${p.paper ? ' <span class="rc-pill rc-warn">paper fill</span>' : ''}</p>
+ ${evidence}
+ ${r.legs.length ? `<h4 class="rc-h">Every leg</h4>${legsHTML(r.legs, opened)}` : ''}
+ <p class="rc-note">This is what the engine recorded at decision time. Evidence logged after the exit is left out, because it cannot have caused the trade.</p>
+ ${links}
+ </div>`;
+}
+
+/** Skeleton shown while a receipt loads. */
+export function receiptSkeletonHTML() {
+ return `<div class="rc rc-loading" aria-busy="true" aria-label="Loading the evidence for this trade">
+ <span class="rc-sk" style="width:70%"></span>
+ <div class="rc-grid"><span class="rc-sk rc-sk-card"></span><span class="rc-sk rc-sk-card"></span><span class="rc-sk rc-sk-card"></span></div>
+ </div>`;
+}
+
+export const RECEIPT_CSS = `
+.rc{--rc-ink:var(--ink-bright,var(--ink,#f9fafb));--rc-dim:var(--ink-dim,#9ca3af);--rc-faint:var(--ink-faint,#6b7280);
+ --rc-line:var(--stroke,var(--line,#1f2937));--rc-panel:var(--surface-2,var(--panel,#0e1015));
+ --rc-ok:var(--success,#34d399);--rc-bad:var(--danger,#f87171);--rc-warn:var(--warn,#fbbf24);
+ text-align:left;color:var(--rc-dim);font-size:13px;line-height:1.55;padding:6px 2px 10px;
+ animation:rc-in .22s ease-out}
+@keyframes rc-in{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}}
+.rc p{margin:0}
+.rc-summary{color:var(--rc-ink);font-size:14px;font-weight:600;margin-bottom:8px!important}
+.rc-trigger{margin-bottom:12px!important}
+.rc-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px}
+.rc-card{border:1px solid var(--rc-line);border-radius:12px;background:var(--rc-panel);padding:12px 14px;min-width:0;
+ transition:border-color .15s ease}
+.rc-card:hover{border-color:var(--rc-dim)}
+.rc-card-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:8px;flex-wrap:wrap}
+.rc-card-head h4,.rc-h{margin:0;font-size:11px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:var(--rc-faint)}
+.rc-h{margin:16px 0 8px}
+.rc-when{font-size:11px;color:var(--rc-faint);white-space:nowrap}
+.rc-when-during_trade{color:var(--rc-warn)}
+.rc-big{font-size:26px;font-weight:800;color:var(--rc-ink);line-height:1.1;margin-bottom:8px!important}
+.rc-big small{font-size:12px;font-weight:600;color:var(--rc-faint);margin-left:2px}
+.rc-bars{display:grid;gap:4px;margin-bottom:8px}
+.rc-bar{display:grid;grid-template-columns:72px 1fr 26px;align-items:center;gap:8px;font-size:11px}
+.rc-bar-k{text-transform:capitalize;color:var(--rc-faint)}
+.rc-bar-track{height:6px;border-radius:3px;background:var(--rc-line);overflow:hidden}
+.rc-bar-fill{display:block;height:100%;border-radius:3px;background:color-mix(in srgb,var(--rc-ink) 72%,transparent)}
+.rc-bar-v{text-align:right;color:var(--rc-dim);font-variant-numeric:tabular-nums}
+.rc-kv{display:grid;grid-template-columns:1fr 1fr;gap:6px 12px;margin:0 0 6px}
+.rc-kv div{min-width:0}
+.rc-kv dt{font-size:11px;color:var(--rc-faint);margin:0}
+.rc-kv dd{margin:0;color:var(--rc-ink);font-weight:600;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}
+.rc-sub{font-size:12px;color:var(--rc-faint);margin:6px 0 4px!important}
+.rc-list{list-style:none;margin:0;padding:0;display:grid;gap:4px}
+.rc-list li{display:flex;gap:8px;align-items:baseline;overflow-wrap:anywhere}
+.rc-plain li::before{content:"";flex:none;width:4px;height:4px;border-radius:50%;background:var(--rc-faint);transform:translateY(-2px)}
+.rc-checks{list-style:none;margin:6px 0;padding:0;display:grid;gap:3px}
+.rc-checks li{display:grid;grid-template-columns:10px 1fr auto;gap:8px;align-items:center}
+.rc-check-s{font-size:11px;text-transform:uppercase;letter-spacing:.06em}
+.rc-dot{width:7px;height:7px;border-radius:50%;background:var(--rc-faint);flex:none}
+.rc-ok .rc-dot,.rc-dot.rc-ok{background:var(--rc-ok)} .rc-warn .rc-dot,.rc-dot.rc-warn{background:var(--rc-warn)}
+.rc-bad .rc-dot,.rc-dot.rc-bad{background:var(--rc-bad)}
+.rc-checks .rc-ok .rc-check-s{color:var(--rc-ok)} .rc-checks .rc-warn .rc-check-s{color:var(--rc-warn)} .rc-checks .rc-bad .rc-check-s{color:var(--rc-bad)}
+.rc-pill{display:inline-block;font-size:11px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;padding:2px 8px;
+ border-radius:999px;border:1px solid var(--rc-line);color:var(--rc-dim)}
+.rc-pill.rc-ok{color:var(--rc-ok);border-color:color-mix(in srgb,var(--rc-ok) 40%,transparent)}
+.rc-pill.rc-warn{color:var(--rc-warn);border-color:color-mix(in srgb,var(--rc-warn) 40%,transparent)}
+.rc-pill.rc-bad{color:var(--rc-bad);border-color:color-mix(in srgb,var(--rc-bad) 40%,transparent)}
+.rc-ok-t{color:var(--rc-ok)} .rc-bad-t{color:var(--rc-bad)} .rc-muted-t{color:var(--rc-dim)}
+.rc-line{margin-bottom:6px!important}
+.rc-dim{color:var(--rc-faint);font-size:12px}
+.rc-text{color:var(--rc-dim);overflow-wrap:anywhere}
+.rc-quote{margin:6px 0;padding:6px 10px;border-left:2px solid var(--rc-dim);color:var(--rc-ink);font-style:italic}
+.rc-foot{font-size:11px;color:var(--rc-faint);margin-top:6px!important}
+.rc-legs{list-style:none;margin:0;padding:0 0 0 14px;border-left:1px solid var(--rc-line);display:grid;gap:8px}
+.rc-legs li{position:relative}
+.rc-legs li::before{content:"";position:absolute;left:-18px;top:6px;width:7px;height:7px;border-radius:50%;background:var(--rc-dim)}
+.rc-leg-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:8px;color:var(--rc-ink)}
+.rc-link{color:var(--rc-dim);text-decoration:none;border-bottom:1px dotted var(--rc-faint);white-space:nowrap;font-size:12px;
+ transition:color .15s ease}
+.rc-link:hover,.rc-link:focus-visible{color:var(--rc-ink)}
+.rc-link:focus-visible{outline:2px solid var(--accent,#34d399);outline-offset:2px;border-radius:2px}
+.rc-note{font-size:11px;color:var(--rc-faint);margin-top:12px!important}
+.rc-actions{display:flex;flex-wrap:wrap;gap:14px;margin-top:8px!important}
+.rc-empty{border:1px dashed var(--rc-line);border-radius:12px;padding:12px 14px}
+.rc-sk{display:block;height:14px;border-radius:6px;margin-bottom:10px;
+ background:linear-gradient(90deg,var(--rc-line) 25%,var(--rc-panel) 50%,var(--rc-line) 75%);background-size:200% 100%;
+ animation:rc-sk 1.2s linear infinite}
+.rc-sk-card{height:120px;border-radius:12px;margin:0}
+@keyframes rc-sk{from{background-position:200% 0}to{background-position:-200% 0}}
+@media (max-width:520px){.rc-kv{grid-template-columns:1fr}.rc-grid{grid-template-columns:1fr}}
+@media (prefers-reduced-motion:reduce){.rc,.rc-sk{animation:none}.rc-card,.rc-link{transition:none}}
+`;
diff --git a/src/trader.css b/src/trader.css
index ed2831c5c..b13e82d67 100644
--- a/src/trader.css
+++ b/src/trader.css
@@ -210,6 +210,14 @@
/* Share is an action, not a proof link: solid underline, accent on hover. */
.tp-proof-share { border-bottom-style: solid; border-bottom-color: color-mix(in srgb, var(--accent) 45%, transparent); }
.tp-proof-share:hover, .tp-proof-share:focus-visible { color: var(--accent); border-bottom-color: var(--accent); }
+/* "why" opens the trade receipt: a button styled as a proof link. */
+button.tp-proof-link { background: none; border-top: 0; border-left: 0; border-right: 0; padding: 0; font: inherit; font-size: var(--text-2xs); cursor: pointer; }
+.tp-why-btn { color: var(--accent); border-bottom-color: color-mix(in srgb, var(--accent) 45%, transparent); }
+.tp-why-btn:hover { color: var(--ink-bright); }
+.tp-why-btn:active { transform: translateY(1px); }
+.tp-why-btn[aria-expanded="true"] { color: var(--ink-bright); border-bottom-style: solid; }
+.tp-table .tp-why-row td,
+.tp-table .tp-why-row:hover td { background: var(--surface-1); text-align: left; padding: var(--space-sm) var(--space-md) var(--space-md); }
/* ---- Proof callout ---- */
.tp-proof-note {
@@ -559,6 +567,9 @@
two fields that matter most. Scrolling keeps every column on every table. */
.tp-panel, .tp-curve-wrap { overflow-x: auto; }
.tp-table { min-width: 560px; }
+ /* The receipt lives in a row of that scrolling table: pin it to the visible
+ width so it reads without sideways scrolling. */
+ .tp-why-row .rc { position: sticky; left: 0; max-width: calc(100vw - 4 * var(--space-md)); }
}
@media (prefers-reduced-motion: reduce) {
.tp-panel.is-active, .tp-sk { animation: none; }
diff --git a/src/trader.js b/src/trader.js
index d41e09abf..3a7bdde09 100644
--- a/src/trader.js
+++ b/src/trader.js
@@ -17,6 +17,7 @@ import { mountPassport, resetPassport } from './trader-passport.js';
import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
import { embedSnippet } from './shared/trader-embed.js';
import { ring, playRings, countUp } from './ui-juice.js';
+import { receiptHTML, receiptSkeletonHTML, RECEIPT_CSS } from './shared/trade-receipt-view.js';
const WINDOWS = ['24h', '7d', '30d', 'all'];
const WINDOW_LABEL = { '24h': '24h', '7d': '7d', '30d': '30d', all: 'All-time' };
@@ -31,6 +32,9 @@ const ctx = {
window: 'all',
data: null,
refCode: null,
+ /** ?trade=<position id> deep-links straight to one trade's receipt. */
+ openTrade: '',
+ receipts: new Map(),
};
// A Solana base58 address — 32-44 chars, no hyphens. Used to distinguish
@@ -48,6 +52,7 @@ function parseParams() {
ctx.agentId = m ? decodeURIComponent(m[1]) : (qp.get('agent_id') || qp.get('agent') || '');
if (NETWORKS.has(qp.get('network'))) ctx.network = qp.get('network');
if (WINDOWS.includes(qp.get('window'))) ctx.window = qp.get('window');
+ if (UUID_RE.test(qp.get('trade') || '')) ctx.openTrade = qp.get('trade');
}
function solscanAddr(addr) {
@@ -259,6 +264,11 @@ function closedRows(closed) {
const held = t.opened_at && t.closed_at
? holdTime((new Date(t.closed_at) - new Date(t.opened_at)) / 1000) : '—';
const proof = [
+ // "why" opens the trade receipt: the evidence every gate recorded
+ // before this entry (Oracle, firewall, LLM judge, Risk Officer, paid
+ // x402 reads) plus each journal leg. Rendered in a row below.
+ t.id ? `<button type="button" class="tp-proof-link tp-why-btn" data-why="${escapeHtml(t.id)}"
+ aria-expanded="false" title="Why the agent took this trade, with the evidence it had">why</button>` : '',
t.buy_url ? `<a class="tp-proof-link" href="${escapeHtml(t.buy_url)}" target="_blank" rel="noopener">buy ↗</a>` : '',
t.sell_url ? `<a class="tp-proof-link" href="${escapeHtml(t.sell_url)}" target="_blank" rel="noopener">sell ↗</a>` : '',
// /trade/<id> is the per-trade share page: its own OG card, the four
@@ -277,7 +287,7 @@ function closedRows(closed) {
? `<span class="tp-tag tp-tag-moonbag" title="Not a full exit: the initial buy-in was sold and ${t.moonbag_value_sol != null ? `~${fmtSol(t.moonbag_value_sol, { sign: false })} of` : ''} tokens still ride at zero cost basis">moon-bag held</span>`
: '',
].filter(Boolean).join('');
- return `<tr${t.self_dealing ? ' class="tp-row-muted"' : ''}>
+ return `<tr data-trade-row="${escapeHtml(t.id || '')}"${t.self_dealing ? ' class="tp-row-muted"' : ''}>
<td><div class="tp-coin"><span class="tp-coin-sym">${escapeHtml(t.symbol || t.name || '—')}</span><span class="tp-coin-mint">${escapeHtml(shortAddr(t.mint, 4, 4))}</span>${tags}</div></td>
<td>${pnl}<div class="tp-metric-sub">${pct}</div></td>
<td><span class="tp-reason">${escapeHtml(t.exit_reason || '—')}</span>${t.moonbag_held ? '<div class="tp-metric-sub">initials out, rest rides</div>' : ''}</td>
@@ -445,6 +455,7 @@ function render(data) {
wireWindow();
wireShare();
wireWalletChips(content);
+ openDeepLinkedReceipt();
const panel = document.getElementById('tp-copy-panel');
if (panel) mountCopyPanel(panel, { leaderAgentId: a.id, leaderName: a.name, network: ctx.network });
@@ -714,6 +725,93 @@ async function loadRefCode() {
} catch { /* signed-out or unavailable — share the bare profile link */ }
}
+// --- Trade receipts ("why") ---------------------------------------------------
+function injectReceiptStyles() {
+ if (document.getElementById('rc-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'rc-styles';
+ style.textContent = RECEIPT_CSS;
+ document.head.appendChild(style);
+}
+
+async function fetchReceipt(id) {
+ if (ctx.receipts.has(id)) return ctx.receipts.get(id);
+ const res = await fetch(`/api/sniper/receipt?id=${encodeURIComponent(id)}`, { headers: { accept: 'application/json' } });
+ if (res.status === 404) throw Object.assign(new Error('not_found'), { code: 'not_found' });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const receipt = await res.json();
+ ctx.receipts.set(id, receipt);
+ return receipt;
+}
+
+function receiptErrorHTML(err) {
+ const msg = err?.code === 'not_found'
+ ? 'This trade is no longer public, so its evidence is hidden.'
+ : 'The evidence for this trade did not load. This is usually transient.';
+ return `<div class="rc"><p class="rc-empty">${escapeHtml(msg)}${err?.code === 'not_found' ? '' : ' <button type="button" class="tp-proof-link tp-why-retry">Retry</button>'}</p></div>`;
+}
+
+async function fillReceipt(cell, id) {
+ cell.innerHTML = receiptSkeletonHTML();
+ try {
+ const receipt = await fetchReceipt(id);
+ if (!cell.isConnected) return;
+ cell.innerHTML = receiptHTML(receipt);
+ } catch (err) {
+ if (!cell.isConnected) return;
+ cell.innerHTML = receiptErrorHTML(err);
+ cell.querySelector('.tp-why-retry')?.addEventListener('click', () => fillReceipt(cell, id));
+ }
+}
+
+function syncTradeParam(id) {
+ const url = new URL(location.href);
+ if (id) url.searchParams.set('trade', id);
+ else url.searchParams.delete('trade');
+ history.replaceState(null, '', url);
+}
+
+/** Open or close the receipt row under one trade row. */
+function toggleReceipt(btn) {
+ const id = btn.dataset.why;
+ const row = btn.closest('tr');
+ if (!id || !row) return;
+ const next = row.nextElementSibling;
+ if (next && next.classList.contains('tp-why-row')) {
+ next.remove();
+ btn.setAttribute('aria-expanded', 'false');
+ btn.textContent = 'why';
+ if (ctx.openTrade === id) { ctx.openTrade = ''; syncTradeParam(''); }
+ return;
+ }
+ injectReceiptStyles();
+ const panel = btn.closest('.tp-panel')?.dataset.panel || 'record';
+ const cellId = `tp-why-${panel}-${id}`;
+ const cols = row.children.length || 6;
+ row.insertAdjacentHTML('afterend', `<tr class="tp-why-row"><td colspan="${cols}" id="${cellId}"></td></tr>`);
+ btn.setAttribute('aria-expanded', 'true');
+ btn.setAttribute('aria-controls', cellId);
+ btn.textContent = 'hide';
+ ctx.openTrade = id;
+ syncTradeParam(id);
+ fillReceipt(document.getElementById(cellId), id);
+}
+
+function openDeepLinkedReceipt() {
+ if (!ctx.openTrade) return;
+ const btn = content.querySelector(`.tp-panel[data-panel="record"] .tp-why-btn[data-why="${CSS.escape(ctx.openTrade)}"]`);
+ if (!btn) return;
+ toggleReceipt(btn);
+ btn.closest('tr')?.scrollIntoView({ block: 'center', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
+}
+
+// One delegated listener on the persistent content node: rows are re-rendered on
+// every window switch, so per-row listeners would leak or go stale.
+content.addEventListener('click', (e) => {
+ const btn = e.target.closest?.('.tp-why-btn');
+ if (btn && content.contains(btn)) toggleReceipt(btn);
+});
+
// --- Skeleton / states -------------------------------------------------------
function showSkeleton() {
root.setAttribute('aria-busy', 'true');
diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.json
index 50e66041b..8f548339d 100644
--- a/tests/fixtures/mcp-golden-tools.json
+++ b/tests/fixtures/mcp-golden-tools.json
@@ -726,6 +726,14 @@
"annotations": "ref:WRITE",
"schemaHash": "4371f009b2b2"
},
+ {
+ "name": "trade_receipt",
+ "title": "Why an agent took one trade",
+ "descHead": "Get the decision receipt for one pump.fun trade by an agent: the entry t",
+ "descHash": "71a32208cc0e",
+ "annotations": "ref:LIVE",
+ "schemaHash": "bb36769e7ef4"
+ },
{
"name": "trader_leaderboard",
"title": "Top pump.fun traders",
diff --git a/tests/mcp-trader-tools.test.js b/tests/mcp-trader-tools.test.js
index 38f93891b..5221faa3f 100644
--- a/tests/mcp-trader-tools.test.js
+++ b/tests/mcp-trader-tools.test.js
@@ -1,7 +1,7 @@
/**
- * Trader MCP tools (api/_mcp/tools/trader.js), the four tools that close the
+ * Trader MCP tools (api/_mcp/tools/trader.js), the tools that close the
* autonomous copy-trading loop: trader_leaderboard, trader_profile,
- * copy_subscribe, copy_status.
+ * trade_receipt, copy_subscribe, copy_status.
*
* The handlers themselves are the real shipped code. Only their leaf boundaries
* are stubbed: the Neon client, the trader-stats aggregators, and the rate
@@ -84,6 +84,11 @@ vi.mock('../api/_lib/trader-stats.js', async (importOriginal) => {
};
});
+const loadTradeReceipt = vi.fn();
+vi.mock('../api/_lib/trade-receipt.js', () => ({
+ loadTradeReceipt: (...a) => loadTradeReceipt(...a),
+}));
+
const mcpIp = vi.fn(async () => ({ success: true, limit: 600, remaining: 599, reset: 0 }));
vi.mock('../api/_lib/rate-limit.js', () => ({
clientIp: () => '203.0.113.7',
@@ -146,14 +151,15 @@ beforeEach(() => {
queryError = null;
getLeaderboard.mockReset();
getTraderStats.mockReset();
+ loadTradeReceipt.mockReset();
mcpIp.mockClear();
mcpIp.mockResolvedValue({ success: true, limit: 600, remaining: 599, reset: 0 });
});
describe('tool surface', () => {
- it('exports the four trader tools with handlers and input schemas', () => {
+ it('exports the trader tools with handlers and input schemas', () => {
expect(Object.keys(TOOLS).sort()).toEqual(
- ['copy_status', 'copy_subscribe', 'trader_leaderboard', 'trader_profile'],
+ ['copy_status', 'copy_subscribe', 'trade_receipt', 'trader_leaderboard', 'trader_profile'],
);
for (const t of toolDefs) {
expect(typeof t.handler).toBe('function');
@@ -168,6 +174,8 @@ describe('tool surface', () => {
expect(TOOLS.copy_status.scope).toBe('agents:read');
expect(TOOLS.trader_leaderboard.scope).toBeUndefined();
expect(TOOLS.trader_profile.scope).toBeUndefined();
+ expect(TOOLS.trade_receipt.scope).toBeUndefined();
+ expect(TOOLS.trade_receipt.annotations.readOnlyHint).toBe(true);
expect(TOOLS.copy_subscribe.annotations.readOnlyHint).toBe(false);
expect(TOOLS.copy_status.annotations.readOnlyHint).toBe(true);
});
@@ -324,6 +332,46 @@ describe('trader_profile', () => {
});
});
+describe('trade_receipt', () => {
+ const TRADE_ID = '99999999-2222-4333-8444-555555555555';
+ const receipt = {
+ position: { id: TRADE_ID, agent_id: LEADER_ID, symbol: 'THREE', mint: THREE_MINT, status: 'closed' },
+ trigger: { key: 'oracle_crossing', label: 'Oracle crossing' },
+ legs: [],
+ evidence: { oracle: { score: 85, timing: 'before_entry' } },
+ evidence_count: 1,
+ summary: 'Sniper One bought $THREE. Trigger: Oracle crossing. Oracle score 85.',
+ };
+
+ it('returns the receipt with a deep link into the trader page', async () => {
+ loadTradeReceipt.mockResolvedValueOnce(receipt);
+ const out = payloadOf(await TOOLS.trade_receipt.handler({ trade_id: TRADE_ID }, ANON));
+ expect(loadTradeReceipt).toHaveBeenCalledWith(TRADE_ID);
+ expect(out.summary).toBe(receipt.summary);
+ expect(out.evidence.oracle.score).toBe(85);
+ expect(out.receipt_url).toBe(`https://three.ws/trader/${LEADER_ID}?trade=${TRADE_ID}`);
+ });
+
+ it('rejects a non-UUID trade_id before any lookup', async () => {
+ const res = await TOOLS.trade_receipt.handler({ trade_id: 'last-trade' }, ANON);
+ expect(res.isError).toBe(true);
+ expect(textOf(res)).toMatch(/must be a UUID/i);
+ expect(loadTradeReceipt).not.toHaveBeenCalled();
+ });
+
+ it('says not found for an unknown or private trade, and unavailable for an outage', async () => {
+ loadTradeReceipt.mockResolvedValueOnce(null);
+ const missing = await TOOLS.trade_receipt.handler({ trade_id: TRADE_ID }, ANON);
+ expect(missing.isError).toBe(true);
+ expect(textOf(missing)).toMatch(/not found/i);
+
+ loadTradeReceipt.mockRejectedValueOnce(new Error('Error connecting to database: fetch failed'));
+ const down = await TOOLS.trade_receipt.handler({ trade_id: TRADE_ID }, ANON);
+ expect(down.isError).toBe(true);
+ expect(textOf(down)).toMatch(/temporarily unavailable/i);
+ });
+});
+
describe('copy_subscribe', () => {
const goodArgs = {
leader_agent_id: LEADER_ID,
diff --git a/tests/trade-receipt.test.js b/tests/trade-receipt.test.js
new file mode 100644
index 000000000..92345842f
--- /dev/null
+++ b/tests/trade-receipt.test.js
@@ -0,0 +1,204 @@
+import { describe, it, expect, vi } from 'vitest';
+
+// The loader imports the database client; the shaping under test is pure.
+vi.mock('../api/_lib/db.js', () => ({ sql: () => Promise.resolve([]) }));
+
+const {
+ evidenceTiming,
+ receiptTxUrl,
+ shapeTradeReceipt,
+ summarizeReceipt,
+ triggerLabel,
+} = await import('../api/_lib/trade-receipt.js');
+
+const OPENED = '2026-09-24T05:46:25.948Z';
+const CLOSED = '2026-09-24T05:52:22.479Z';
+const SOL_SIG = '3owaJHvhEbES9WmjiDmSXk9kVTepjHft4ZMHkPTauK79tj3HhuM7bbtK4jA42piV49u5jU4xVdCJW4dcDfAJdAbz';
+
+/** A closed, live position on $THREE. Tests override one field at a time. */
+function position(over = {}) {
+ return {
+ id: '11111111-2222-3333-4444-555555555555',
+ agent_id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
+ agent_name: 'Crosshair',
+ agent_image: null,
+ network: 'mainnet',
+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ symbol: 'THREE',
+ name: 'three.ws',
+ status: 'closed',
+ exit_reason: 'trailing_stop',
+ entry_trigger: 'oracle_crossing',
+ trigger_ref: 'score:85',
+ entry_quote_lamports: '2000000',
+ exit_quote_lamports: '1794738',
+ realized_pnl_lamports: '-205262',
+ realized_pnl_pct: '-10.2631',
+ entry_price_impact_pct: '0.0019',
+ buy_sig: SOL_SIG,
+ sell_sig: SOL_SIG,
+ opened_at: OPENED,
+ closed_at: CLOSED,
+ ...over,
+ };
+}
+
+const at = (deltaSec) => new Date(new Date(OPENED).getTime() + deltaSec * 1000).toISOString();
+
+describe('evidenceTiming', () => {
+ it('places evidence before the entry, inside the clock-skew allowance', () => {
+ expect(evidenceTiming(at(-60), OPENED, CLOSED)).toBe('before_entry');
+ expect(evidenceTiming(at(90), OPENED, CLOSED)).toBe('before_entry');
+ });
+ it('separates the hold from the time after the exit', () => {
+ expect(evidenceTiming(at(200), OPENED, CLOSED)).toBe('during_trade');
+ expect(evidenceTiming(at(3600), OPENED, CLOSED)).toBe('after_exit');
+ });
+ it('treats an open position as still holding', () => {
+ expect(evidenceTiming(at(3600), OPENED, null)).toBe('during_trade');
+ });
+ it('refuses to place a missing timestamp', () => {
+ expect(evidenceTiming(null, OPENED, CLOSED)).toBeNull();
+ });
+});
+
+describe('receiptTxUrl', () => {
+ it('opens a Solana signature on Solscan, devnet included', () => {
+ expect(receiptTxUrl(SOL_SIG)).toBe(`https://solscan.io/tx/${SOL_SIG}`);
+ expect(receiptTxUrl(SOL_SIG, 'devnet')).toBe(`https://solscan.io/tx/${SOL_SIG}?cluster=devnet`);
+ });
+ it('opens an EVM payment hash on Basescan', () => {
+ const hash = `0x${'ab'.repeat(32)}`;
+ expect(receiptTxUrl(hash)).toBe(`https://basescan.org/tx/${hash}`);
+ });
+ it('never links a paper fill or a malformed value', () => {
+ expect(receiptTxUrl('SIMULATED')).toBeNull();
+ expect(receiptTxUrl('not a signature')).toBeNull();
+ expect(receiptTxUrl(null)).toBeNull();
+ });
+});
+
+describe('triggerLabel', () => {
+ it('names every trigger the sniper writes', () => {
+ for (const t of ['new_mint', 'oracle_crossing', 'intel_confirmed', 'llm_intel', 'graduation_ride']) {
+ expect(triggerLabel(t).detail).toBeTruthy();
+ }
+ });
+ it('defaults a missing trigger to a fresh launch and humanizes an unknown one', () => {
+ expect(triggerLabel(null).label).toBe('Fresh launch');
+ expect(triggerLabel('whale_follow').label).toBe('whale follow');
+ });
+});
+
+describe('shapeTradeReceipt', () => {
+ it('keeps every leg in time order with its on-chain link', () => {
+ const r = shapeTradeReceipt({
+ position: position(),
+ journal: [
+ { event: 'exit', reason: 'trailing_stop', rationale: 'Full exit: trailing_stop.', sold_fraction: '1', leg_pnl_lamports: '-205262', ts: CLOSED, sig: SOL_SIG },
+ { event: 'entry', reason: 'oracle_crossing', rationale: 'Entered on oracle_crossing.', sold_fraction: '0', ts: at(2), sig: SOL_SIG },
+ ],
+ });
+ expect(r.legs.map((l) => l.event)).toEqual(['entry', 'exit']);
+ expect(r.legs[1].leg_pnl_sol).toBeCloseTo(-0.000205262, 9);
+ expect(r.legs[0].tx_url).toContain('solscan.io/tx/');
+ expect(r.position.share_url).toBe('/trade/11111111-2222-3333-4444-555555555555');
+ expect(r.evidence_count).toBe(0);
+ });
+
+ it('labels a paper fill and gives it no transaction links', () => {
+ const r = shapeTradeReceipt({ position: position({ buy_sig: 'SIMULATED', sell_sig: 'SIMULATED' }), journal: [] });
+ expect(r.position.paper).toBe(true);
+ expect(r.position.buy_url).toBeNull();
+ expect(r.summary).toContain('paper-bought');
+ });
+
+ it('drops evidence recorded after the exit, since it cannot have caused the trade', () => {
+ const r = shapeTradeReceipt({
+ position: position(),
+ journal: [],
+ sentiment: { signal: 'bullish', headline: 'late read', confidence: '0.9', checked_at: at(3600), tx_signature: SOL_SIG },
+ judge: { buy: true, confidence: '0.8', thesis: 'after the fact', model: 'm', created_at: at(3600) },
+ intel: { quality_score: 91, observation_ended_at: at(3600) },
+ });
+ expect(r.evidence.sentiment).toBeNull();
+ expect(r.evidence.judge).toBeNull();
+ expect(r.evidence.intel).toBeNull();
+ });
+
+ it('tags a paid read taken while holding as during_trade, with its payment receipt', () => {
+ const r = shapeTradeReceipt({
+ position: position(),
+ journal: [],
+ sentiment: { signal: 'bullish', headline: 'h', confidence: '0.93', sentiment_adj: -4, checked_at: at(200), tx_signature: SOL_SIG },
+ });
+ expect(r.evidence.sentiment.timing).toBe('during_trade');
+ expect(r.evidence.sentiment.confidence).toBeCloseTo(0.93);
+ expect(r.evidence.sentiment.receipt_url).toContain(SOL_SIG);
+ });
+
+ it('only admits an LLM verdict that existed before the entry', () => {
+ const before = shapeTradeReceipt({
+ position: position(), journal: [],
+ judge: { buy: true, confidence: '0.8', thesis: 'two-sided market', model: 'm', created_at: at(-30) },
+ });
+ expect(before.evidence.judge).toMatchObject({ buy: true, thesis: 'two-sided market' });
+ const during = shapeTradeReceipt({
+ position: position(), journal: [],
+ judge: { buy: true, confidence: '0.8', thesis: 'x', model: 'm', created_at: at(200) },
+ });
+ expect(during.evidence.judge).toBeNull();
+ });
+
+ it('ranks Oracle reasons by how far they moved the base rate, and hides reasons scored after the exit', () => {
+ const reasons = [
+ { text: 'near base', pillar: 'momentum', lift: 1.0 },
+ { text: 'strong lift', pillar: 'structure', lift: 2.7 },
+ { text: 'drag', pillar: 'momentum', lift: 0.3 },
+ ];
+ const r = shapeTradeReceipt({
+ position: position(), journal: [],
+ oracleHistory: { score: 85, tier: 'strong', pedigree: 33, structure: 23, narrative: 11, momentum: 57, scored_at: at(-3) },
+ oracleCurrent: { score: 85, reasons, scored_at: at(-3) },
+ });
+ expect(r.evidence.oracle.score).toBe(85);
+ expect(r.evidence.oracle.reasons.map((x) => x.text)).toEqual(['strong lift', 'drag', 'near base']);
+ const late = shapeTradeReceipt({
+ position: position(), journal: [],
+ oracleHistory: { score: 85, scored_at: at(-3) },
+ oracleCurrent: { score: 60, reasons, scored_at: at(3600) },
+ });
+ expect(late.evidence.oracle.score).toBe(85);
+ expect(late.evidence.oracle.reasons).toEqual([]);
+ });
+
+ it('carries the firewall checks and the Risk Officer review as recorded', () => {
+ const r = shapeTradeReceipt({
+ position: position(), journal: [],
+ firewall: {
+ verdict: 'warn', score: 84, reasons: ['concentrated holders'], simulated: true, enforced: false, created_at: at(0.4),
+ checks: [{ name: 'round_trip', status: 'pass', reason: 'roundtrip_simulated_ok', detail: {} }, { status: 'pass' }],
+ },
+ riskReview: { level: 'shadow', veto: false, severity: 'caution', reasons: ['thin book'], proposed_lamports: '2000000', adjusted_lamports: '1000000', created_at: at(0) },
+ });
+ expect(r.evidence.firewall.checks).toEqual([{ name: 'round_trip', status: 'pass', reason: 'roundtrip_simulated_ok' }]);
+ expect(r.evidence.risk_review).toMatchObject({ severity: 'caution', proposed_sol: 0.002, adjusted_sol: 0.001 });
+ expect(r.evidence_count).toBe(2);
+ });
+});
+
+describe('summarizeReceipt', () => {
+ it('states the trigger, the drivers it has evidence for, and the result', () => {
+ const r = shapeTradeReceipt({
+ position: position(), journal: [],
+ oracleHistory: { score: 85, tier: 'strong', scored_at: at(-3) },
+ firewall: { verdict: 'warn', score: 84, created_at: at(0) },
+ });
+ expect(r.summary).toBe('Crosshair bought $THREE. Trigger: Oracle crossing. Oracle score 85 strong, firewall warn. Exited on trailing stop at -10.3%.');
+ });
+ it('says an open position is still open instead of inventing a result', () => {
+ const r = shapeTradeReceipt({ position: position({ status: 'open', closed_at: null, exit_reason: null }), journal: [] });
+ expect(summarizeReceipt(r)).toBe('Crosshair bought $THREE. Trigger: Oracle crossing. Still open.');
+ expect(r.position.share_url).toBeNull();
+ });
+});
diff --git a/vercel.json b/vercel.json
index a7eda377c..1225ff922 100644
--- a/vercel.json
+++ b/vercel.json
@@ -3801,6 +3801,10 @@
"src": "/api/sniper/trader",
"dest": "/api/sniper/trader.js"
},
+ {
+ "src": "/api/sniper/receipt",
+ "dest": "/api/sniper/receipt.js"
+ },
{
"src": "/api/traders/preview",
"dest": "/api/traders/preview.js"