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.

Add Oracle conviction product + launch-detail aggregator

nirholasab317ffdc28f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 46babe66f..556cf859a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,12 @@
Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).
+## 2026-06-16
+
+- **Every launch now has its own page — the full story of a coin in one place** — Until now, clicking a coin on the launches feed sent you out to pump.fun. Now every launch opens a rich profile that stays on three.ws and answers every question a trader actually has, all from real on-chain data: live price, market cap and graduation progress; the Coin Intelligence verdict from the coin's first ~90 seconds (a quality score plus organic-vs-bundle, sniping, holder concentration, fresh-wallet and funder-clustering signals, with any risk flags called out); the labeled outcome if it graduated or rugged, with its all-time-high multiple; a live price chart and a live trade tape that ticks every buy and sell as it lands; holder count and concentration; the agent behind the mint and its verifiable TraderScore; and the buyback-and-burn economics for agent-payment coins, each burn linking to its on-chain transaction. Watch a coin, share its page, jump into its 3D world, or open it in 3D — every number traces back to a real transaction. (`/launches`) `[feature]`
+- **Oracle — one conviction score per launch, and an agent that acts on it** — Oracle is a new way to read pump.fun: instead of a wall of separate metrics, every launch gets one transparent 0–100 conviction score that fuses four reads — WHO is buying it (the proven track record of the wallets in the book), HOW it's being bought (organic vs. a bundle or a single-funder cluster), WHAT it is (a live cultural-narrative read — meme, tech, AI, a news-story meme, a culture or community coin), and HOW it's moving. A hard structural cap means a coordinated bundle or a dumping dev can never read 'strong,' no matter who's in it. Open any coin to see the full breakdown, the exact reasons, and a live 'who's in' panel that labels every early wallet by archetype — smart money, sniper, dumper, rugger — with its real win rate. A wallet leaderboard ranks the proven money, and an honest 'edge' tab shows the realized graduation rate by conviction tier — no backfilled numbers. Best of all, you can arm your 3D AI agent to act: it watches the live conviction stream and buys a small position the moment a coin clears your bar, starting in simulate so you can watch it work before any real spend. The more coins and wallets the platform watches, the sharper every score. (`/oracle`) `[feature]`
+- **The Sniper Arena is now a living 3D world** — The arena used to be a flat leaderboard. Now it's a real 3D world you walk into. Every armed AI agent stands on the trading floor as an animated avatar — the #1 agent up on a gold podium — and when they trade live, you see it happen: a cheer and a coin burst on a buy, confetti and a back-flip on a big win, a slump on a loss, each one tied to the same on-chain trade scrolling in the live tape. Pick your own avatar from a roster or the community gallery and walk the floor in third person with WASD or a touch joystick. Floating name tags track each agent with their live P&L, and a banner calls out the biggest win as it lands. Every number is real and verifiable on-chain — now it has a face. (`/play/arena`) `[feature]`
+
## 2026-06-15
- **Coin Intelligence** (`/coin-intel`) — Every pump.fun launch watched and classified in real time — organic vs bundle, the wallets behind it, a transparent quality score, and a model that learns which signals predict winners.
diff --git a/api/_lib/migrations/20260616120000_oracle.sql b/api/_lib/migrations/20260616120000_oracle.sql
new file mode 100644
index 000000000..2e74b42c7
--- /dev/null
+++ b/api/_lib/migrations/20260616120000_oracle.sql
@@ -0,0 +1,128 @@
+-- Migration: Oracle — the fused pump.fun conviction layer.
+-- Apply: npm run db:migrate (or psql "$DATABASE_URL" -f this file). Idempotent.
+--
+-- Oracle sits ON TOP of the platform's full-coverage data brain
+-- (pump_coin_intel, pump_coin_wallets, wallet_reputation, coin_smart_money,
+-- pump_coin_outcomes). It does NOT re-ingest or duplicate those — it reads them,
+-- adds the two things they don't have, and caches the result:
+--
+-- 1. oracle_narrative — the cultural read (thesis + virality) the LLM produces.
+-- 2. oracle_conviction — the fused 0–100 score + transparent pillar breakdown,
+-- materialized so the live feed is one fast indexed read
+-- and so we can backtest conviction tiers vs. outcomes.
+-- 3. oracle_agent_watch / oracle_watch_actions — the agent action loop: a user
+-- arms their 3D agent to act on conviction crossings,
+-- and every (simulated or live) action is logged for
+-- win-rate proof.
+--
+-- Standalone tables keyed by mint — no cross-system foreign keys, so this
+-- migration can apply before/after the brain's own migrations in any order.
+-- Mainnet is where pump.fun lives; `network` is carried for parity with the rest.
+
+begin;
+
+-- ── 1. Narrative classification (one row per mint) ───────────────────────────
+create table if not exists oracle_narrative (
+ mint text not null,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ category text not null default 'unknown',
+ narrative text, -- the thesis, one sentence
+ virality int not null default 0, -- 0..100
+ confidence numeric not null default 0, -- 0..1
+ tags jsonb not null default '[]'::jsonb,
+ source text not null default 'heuristic' check (source in ('llm','heuristic')),
+ classified_at timestamptz not null default now(),
+ primary key (mint, network)
+);
+create index if not exists oracle_narrative_category
+ on oracle_narrative (network, category, virality desc);
+
+-- ── 2. Fused conviction (one row per mint, recomputed on a cadence) ──────────
+create table if not exists oracle_conviction (
+ mint text not null,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ symbol text,
+ name text,
+ image_uri text,
+
+ score int not null default 0, -- 0..100 fused conviction
+ tier text not null default 'avoid', -- prime|strong|lean|watch|avoid
+
+ pedigree int not null default 0,
+ structure int not null default 0,
+ narrative int not null default 0,
+ momentum int not null default 0,
+ structure_cap int not null default 100,
+
+ badges jsonb not null default '[]'::jsonb,
+ reasons jsonb not null default '[]'::jsonb, -- [{pillar,text}]
+ components jsonb not null default '{}'::jsonb, -- raw normalized inputs (audit trail)
+
+ category text, -- denormalized for fast feed filters
+ smart_wallet_count int not null default 0,
+
+ coin_first_seen_at timestamptz,
+ scored_at timestamptz not null default now(),
+ primary key (mint, network)
+);
+-- Live-feed read: newest, highest-conviction first, filterable by tier/category.
+create index if not exists oracle_conviction_feed
+ on oracle_conviction (network, score desc, scored_at desc);
+create index if not exists oracle_conviction_tier
+ on oracle_conviction (network, tier, scored_at desc);
+create index if not exists oracle_conviction_fresh
+ on oracle_conviction (network, scored_at desc);
+
+-- ── 3. Agent action loop ─────────────────────────────────────────────────────
+-- One armed config per (agent, network). The agent auto-acts when a coin's fused
+-- conviction crosses `min_score` AND its narrative is in `categories` (empty =
+-- any). `mode` defaults to simulate — real spend is opt-in and capped.
+create table if not exists oracle_agent_watch (
+ agent_id uuid not null,
+ user_id uuid,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+
+ armed boolean not null default false,
+ mode text not null default 'simulate' check (mode in ('simulate','live')),
+ min_score int not null default 80 check (min_score between 0 and 100),
+ min_tier text not null default 'strong',
+ categories jsonb not null default '[]'::jsonb, -- [] = any narrative
+ per_trade_sol numeric not null default 0.05, -- size per action (SOL)
+ max_daily_sol numeric not null default 0.5,
+ max_open int not null default 5,
+ require_smart_money boolean not null default true, -- only act if ≥1 proven wallet in
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ primary key (agent_id, network)
+);
+
+-- Every action the loop takes (simulated or live) — the win-rate ledger.
+create table if not exists oracle_watch_actions (
+ id bigserial primary key,
+ agent_id uuid not null,
+ user_id uuid,
+ network text not null default 'mainnet',
+ mint text not null,
+ symbol text,
+ conviction int,
+ tier text,
+ mode text not null check (mode in ('simulate','live')),
+ size_sol numeric not null default 0,
+ status text not null default 'taken' check (status in ('taken','filled','skipped','failed')),
+ reason text,
+ entry_mc_usd numeric,
+ tx_signature text,
+ -- outcome, labeled after the fact by the sweeper (mirrors the brain's loop)
+ peak_multiple numeric,
+ realized_pnl_sol numeric,
+ outcome text, -- win|loss|flat|open
+ acted_at timestamptz not null default now(),
+ settled_at timestamptz
+);
+create index if not exists oracle_watch_actions_agent
+ on oracle_watch_actions (agent_id, network, acted_at desc);
+create index if not exists oracle_watch_actions_mint
+ on oracle_watch_actions (mint, network);
+
+commit;
diff --git a/api/_lib/oracle/agent-eval.js b/api/_lib/oracle/agent-eval.js
new file mode 100644
index 000000000..5a6005e4f
--- /dev/null
+++ b/api/_lib/oracle/agent-eval.js
@@ -0,0 +1,57 @@
+// Oracle — agent action decision (pure).
+//
+// Given an armed watch config and a freshly-scored coin, decide whether the
+// agent should act, and at what size. Pure and fully tested: the worker handles
+// the I/O (loading open-position counts, today's spend, then executing), but the
+// rules that gate real money live here where they can be verified in isolation.
+
+const TIER_RANK = { avoid: 0, watch: 1, lean: 2, strong: 3, prime: 4 };
+
+/**
+ * @param {object} args
+ * @param {object} args.watch oracle_agent_watch row (armed, mode, min_score, min_tier, categories, per_trade_sol, max_daily_sol, max_open, require_smart_money)
+ * @param {object} args.coin scored coin { score, tier, category, smart_wallet_count }
+ * @param {number} args.openCount agent's currently-open positions
+ * @param {number} args.spentTodaySol agent's SOL committed today
+ * @returns {{act:boolean, size:number, reason:string}}
+ */
+export function evaluateWatch({ watch, coin, openCount = 0, spentTodaySol = 0 }) {
+ if (!watch || !watch.armed) return block('agent not armed');
+ if (!coin) return block('no coin');
+
+ const score = Number(coin.score) || 0;
+ const minScore = Number(watch.min_score) || 0;
+ if (score < minScore) return block(`conviction ${score} below threshold ${minScore}`);
+
+ // Tier gate (coarser duplicate of score, but the owner set it explicitly).
+ const minTier = watch.min_tier || 'watch';
+ if ((TIER_RANK[coin.tier] ?? 0) < (TIER_RANK[minTier] ?? 0)) {
+ return block(`tier ${coin.tier} below ${minTier}`);
+ }
+
+ // Narrative filter.
+ const cats = Array.isArray(watch.categories) ? watch.categories : [];
+ if (cats.length && !cats.includes(coin.category)) {
+ return block(`narrative ${coin.category} not in watchlist`);
+ }
+
+ // Require proven money in the book.
+ if (watch.require_smart_money !== false && (Number(coin.smart_wallet_count) || 0) < 1) {
+ return block('no proven wallet in yet');
+ }
+
+ // Concurrency + budget caps.
+ if (openCount >= (Number(watch.max_open) || 5)) {
+ return block(`at max open positions (${openCount})`);
+ }
+ const size = Number(watch.per_trade_sol) || 0;
+ if (size <= 0) return block('per-trade size is zero');
+ const maxDaily = Number(watch.max_daily_sol) || 0;
+ if (maxDaily > 0 && spentTodaySol + size > maxDaily + 1e-9) {
+ return block(`daily budget reached (${spentTodaySol.toFixed(3)}/${maxDaily} SOL)`);
+ }
+
+ return { act: true, size, reason: `conviction ${score} ≥ ${minScore} (${coin.tier}); ${coin.smart_wallet_count || 0} smart in` };
+}
+
+function block(reason) { return { act: false, size: 0, reason }; }
diff --git a/api/_lib/oracle/archetype.js b/api/_lib/oracle/archetype.js
new file mode 100644
index 000000000..c38ad5d4a
--- /dev/null
+++ b/api/_lib/oracle/archetype.js
@@ -0,0 +1,108 @@
+// Oracle — wallet archetypes.
+//
+// The data brain (wallet_reputation) labels each wallet from its real track
+// record: smart_money | sniper | dumper | rugger | fresh | neutral | unproven.
+// Oracle surfaces those labels everywhere — in a coin's "who's in" panel, in the
+// reputation leaderboard, on a wallet's profile — so a richer, display-ready
+// description lives here once and is shared by the API and the UI.
+//
+// Pure module: no I/O, no DB. Safe to import in a worker, an API route, or a
+// vitest. The UI mirrors the `tone` values as CSS classes (oracle-arch--good etc).
+
+/**
+ * @typedef {'smart_money'|'sniper'|'dumper'|'rugger'|'fresh'|'neutral'|'unproven'} WalletLabel
+ */
+
+const ARCHETYPES = {
+ smart_money: {
+ label: 'smart_money',
+ title: 'Smart Money',
+ glyph: '◆',
+ tone: 'good',
+ blurb: 'Repeatedly early into coins that went on to graduate. Following them is the edge.',
+ },
+ sniper: {
+ label: 'sniper',
+ title: 'Sniper',
+ glyph: '⊚',
+ tone: 'warn',
+ blurb: 'Buys in the first seconds of a launch. Fast, but not always right — weight by win rate.',
+ },
+ dumper: {
+ label: 'dumper',
+ title: 'Dumper',
+ glyph: '▾',
+ tone: 'bad',
+ blurb: 'Sells at least half its position inside the early window. Exit liquidity for followers.',
+ },
+ rugger: {
+ label: 'rugger',
+ title: 'Rugger',
+ glyph: '☠',
+ tone: 'bad',
+ blurb: 'Created coins that died. Their presence on a launch is a red flag.',
+ },
+ fresh: {
+ label: 'fresh',
+ title: 'Fresh Wallet',
+ glyph: '○',
+ tone: 'neutral',
+ blurb: 'Brand-new wallet with no history. Often a funded burner — neither proof nor poison.',
+ },
+ neutral: {
+ label: 'neutral',
+ title: 'Neutral',
+ glyph: '◇',
+ tone: 'neutral',
+ blurb: 'Trades both ways with no decisive edge. Background liquidity.',
+ },
+ unproven: {
+ label: 'unproven',
+ title: 'Unproven',
+ glyph: '·',
+ tone: 'neutral',
+ blurb: 'Too few judged trades to earn a verdict yet. Reputation builds as outcomes land.',
+ },
+};
+
+const UNKNOWN = {
+ label: 'unproven',
+ title: 'Unproven',
+ glyph: '·',
+ tone: 'neutral',
+ blurb: 'No reputation on file.',
+};
+
+/**
+ * Resolve a wallet_reputation label to its display archetype. Tolerant of
+ * null / unknown values so callers never have to guard.
+ * @param {string|null|undefined} label
+ * @returns {{label:WalletLabel,title:string,glyph:string,tone:'good'|'bad'|'warn'|'neutral',blurb:string}}
+ */
+export function archetypeFor(label) {
+ if (!label) return UNKNOWN;
+ return ARCHETYPES[String(label).toLowerCase()] || UNKNOWN;
+}
+
+/** All archetypes, for legends / filter chips. */
+export function allArchetypes() {
+ return Object.values(ARCHETYPES);
+}
+
+/**
+ * Is this label one Oracle treats as proven-positive pedigree? Used by the
+ * conviction engine and the "smart wallets in" counters.
+ * @param {string|null|undefined} label
+ */
+export function isProven(label, score = 0) {
+ return String(label).toLowerCase() === 'smart_money' || Number(score) >= 70;
+}
+
+/**
+ * Is this label one Oracle treats as a warning flag on a launch?
+ * @param {string|null|undefined} label
+ */
+export function isFlagged(label) {
+ const l = String(label).toLowerCase();
+ return l === 'rugger' || l === 'dumper';
+}
diff --git a/api/_lib/oracle/conviction.js b/api/_lib/oracle/conviction.js
new file mode 100644
index 000000000..a1506f795
--- /dev/null
+++ b/api/_lib/oracle/conviction.js
@@ -0,0 +1,318 @@
+// Oracle — the fused conviction engine.
+//
+// Every other system on the platform scores ONE dimension of a pump.fun launch:
+// coin-intel scores the coin's quality, smart-money scores the pedigree of its
+// buyers, the sniper scores entry filters. Oracle's job is the synthesis no
+// single dimension can give: one 0–100 conviction number that fuses *who* is
+// buying, *how* they're buying, *what* the coin is, and *how it's moving* — with
+// a transparent breakdown so a human (or an agent) can see exactly why.
+//
+// The thesis: on pump.fun, edge comes from full-coverage data. We observe every
+// wallet's track record, every coin's footprint, and every outcome. Fusing those
+// in real time is the highest-signal "should I touch this" the platform can
+// produce — and it's only possible because we have the most data.
+//
+// This module is PURE: it takes a normalized CoinIntel object (assembled by
+// sources.js from the data-brain tables) and returns a verdict. No I/O, no DB,
+// no clock — deterministic and fully unit-tested. The numbers are designed so a
+// coin can never look strong on pedigree alone if its structure screams bundle,
+// and never look safe on structure alone if known ruggers are in it.
+
+import { isProven, isFlagged } from './archetype.js';
+
+// Pillar weights. Pedigree (who's in) leads because buyer track record is the
+// single most predictive signal we have; structure (is it a fair launch) is a
+// near-equal guardrail; narrative and momentum refine. Sum = 1.
+export const WEIGHTS = Object.freeze({
+ pedigree: 0.34,
+ structure: 0.30,
+ narrative: 0.18,
+ momentum: 0.18,
+});
+
+// Tier thresholds on the final 0–100 score. Names are chosen to be honest:
+// most launches are noise, so the bar for "prime" is deliberately high.
+const TIERS = [
+ { min: 86, tier: 'prime', label: 'Prime' },
+ { min: 72, tier: 'strong', label: 'Strong' },
+ { min: 56, tier: 'lean', label: 'Lean' },
+ { min: 34, tier: 'watch', label: 'Watch' },
+ { min: 0, tier: 'avoid', label: 'Avoid' },
+];
+
+const clamp = (n, lo = 0, hi = 100) => Math.max(lo, Math.min(hi, n));
+const num = (v, d = 0) => (Number.isFinite(Number(v)) ? Number(v) : d);
+
+/**
+ * Pedigree — the quality of the wallets buying. Driven by the data brain's
+ * pre-computed coin_smart_money.score when present (it is already pedigree-
+ * weighted 0–100), then nudged by the count of proven wallets and dragged down
+ * hard by any flagged (rugger/dumper) wallets in the book.
+ *
+ * @param {object} sm smartMoney slice of CoinIntel
+ * @returns {{score:number, reasons:string[]}}
+ */
+export function pedigreeScore(sm = {}) {
+ const reasons = [];
+ const notable = Array.isArray(sm.notable) ? sm.notable : [];
+ const provenWallets = notable.filter((w) => isProven(w.label, w.score));
+ const flaggedWallets = notable.filter((w) => isFlagged(w.label));
+
+ // Base: prefer the brain's composite if we have one, else derive from the
+ // notable wallets' average reputation.
+ let base = num(sm.score, NaN);
+ if (!Number.isFinite(base)) {
+ if (provenWallets.length || notable.length) {
+ const avg = notable.reduce((s, w) => s + num(w.score), 0) / Math.max(1, notable.length);
+ base = avg;
+ } else {
+ base = 0;
+ }
+ }
+
+ let score = base;
+ const provenCount = num(sm.smartWalletCount, provenWallets.length);
+ if (provenCount >= 5) { score += 14; reasons.push(`${provenCount} smart-money wallets already in`); }
+ else if (provenCount >= 3) { score += 9; reasons.push(`${provenCount} smart-money wallets in`); }
+ else if (provenCount >= 1) { score += 5; reasons.push(`${provenCount} smart-money wallet in`); }
+ else if (notable.length === 0) { reasons.push('no proven wallets identified yet'); }
+
+ // Proven money share of total buys — conviction, not just headcount.
+ const proven = num(sm.provenBuyLamports);
+ const total = num(sm.totalBuyLamports);
+ if (total > 0 && proven > 0) {
+ const share = proven / total;
+ if (share >= 0.4) { score += 8; reasons.push(`${Math.round(share * 100)}% of buy volume is proven money`); }
+ else if (share >= 0.2) { score += 4; }
+ }
+
+ // Flagged wallets are a hard drag — exit liquidity / rug history in the book.
+ if (flaggedWallets.length) {
+ score -= 12 * Math.min(3, flaggedWallets.length);
+ reasons.push(`${flaggedWallets.length} flagged wallet${flaggedWallets.length > 1 ? 's' : ''} (rugger/dumper) in the book`);
+ }
+
+ return { score: clamp(score), reasons };
+}
+
+/**
+ * Structure — is this a fair, organic launch or an engineered one? Penalizes
+ * bundle launches, high holder concentration, single-funder clusters, and a dev
+ * that is already dumping. Rewards a wide, distributed early base.
+ *
+ * @param {object} st structure slice of CoinIntel
+ * @returns {{score:number, reasons:string[], cap:number}}
+ */
+export function structureScore(st = {}) {
+ const reasons = [];
+ let cap = 100; // a hard ceiling some red flags impose on the FINAL score
+
+ // Anchor on the data brain's precomputed organic_score when we have it (it's
+ // a far better base than any single proxy); otherwise start neutral-organic.
+ const organic = num(st.organicScore, NaN); // 0..100
+ let score = Number.isFinite(organic) ? 30 + organic * 0.55 : 62;
+ if (Number.isFinite(organic)) {
+ if (organic >= 70) reasons.push(`organic-demand score ${Math.round(organic)}/100`);
+ else if (organic <= 30) reasons.push(`weak organic demand (${Math.round(organic)}/100)`);
+ }
+
+ // Precise bundle / concentration / wallet-graph signals (0..100) when present.
+ const bundleScore = num(st.bundleScore, NaN);
+ if (Number.isFinite(bundleScore)) {
+ if (bundleScore >= 60) { score -= 20; cap = Math.min(cap, 46); reasons.push(`coordinated-launch likelihood ${Math.round(bundleScore)}%`); }
+ else if (bundleScore >= 35) { score -= 11; reasons.push(`some launch coordination (${Math.round(bundleScore)}%)`); }
+ }
+ const top10 = num(st.top10Pct, NaN);
+ if (Number.isFinite(top10)) {
+ if (top10 >= 80) { score -= 22; cap = Math.min(cap, 44); reasons.push(`top-10 wallets hold ${Math.round(top10)}%`); }
+ else if (top10 >= 60) { score -= 12; reasons.push(`top-10 wallets hold ${Math.round(top10)}%`); }
+ else if (top10 > 0 && top10 < 35) { score += 6; }
+ }
+ const connectivity = num(st.bubblemapConnectivity, NaN);
+ if (Number.isFinite(connectivity) && connectivity >= 60) {
+ score -= 10; cap = Math.min(cap, 55);
+ reasons.push(`buyers are heavily interconnected (${Math.round(connectivity)}%)`);
+ }
+
+ const uniqueBuyers = num(st.uniqueBuyers);
+ if (uniqueBuyers >= 60) { score += 16; reasons.push(`${uniqueBuyers} unique early buyers — broad base`); }
+ else if (uniqueBuyers >= 25) { score += 9; reasons.push(`${uniqueBuyers} unique early buyers`); }
+ else if (uniqueBuyers > 0 && uniqueBuyers < 8) { score -= 8; reasons.push(`only ${uniqueBuyers} unique buyers — thin`); }
+
+ const topHolderPct = num(st.topHolderPct);
+ if (topHolderPct >= 50) { score -= 26; cap = Math.min(cap, 45); reasons.push(`top wallet holds ${Math.round(topHolderPct)}% — extreme concentration`); }
+ else if (topHolderPct >= 30) { score -= 14; reasons.push(`top wallet holds ${Math.round(topHolderPct)}%`); }
+ else if (topHolderPct > 0 && topHolderPct < 12) { score += 6; }
+
+ const creatorHoldPct = num(st.creatorHoldPct);
+ if (creatorHoldPct >= 25) { score -= 16; reasons.push(`creator still holds ${Math.round(creatorHoldPct)}%`); }
+
+ const devSoldPct = num(st.devSoldPct);
+ if (devSoldPct >= 50) { score -= 24; cap = Math.min(cap, 38); reasons.push(`dev already sold ${Math.round(devSoldPct)}% — bailing`); }
+ else if (devSoldPct >= 20) { score -= 10; reasons.push(`dev sold ${Math.round(devSoldPct)}%`); }
+
+ // Single-funder cluster: many "different" wallets fed by one source = a
+ // bundle wearing a wide-base costume.
+ const funderClusterPct = num(st.funderClusterPct);
+ if (funderClusterPct >= 50) { score -= 22; cap = Math.min(cap, 42); reasons.push(`${Math.round(funderClusterPct)}% of buyers share one funder — bundle`); }
+ else if (funderClusterPct >= 30) { score -= 12; reasons.push(`${Math.round(funderClusterPct)}% of buyers share a funder`); }
+
+ if (st.bundleFlag) { score -= 18; cap = Math.min(cap, 48); reasons.push('flagged as a bundle launch'); }
+
+ if (reasons.length === 0) reasons.push('clean, distributed launch structure');
+
+ return { score: clamp(score), reasons, cap };
+}
+
+/**
+ * Narrative — cultural strength of the coin itself. The classifier supplies a
+ * virality estimate (0–100) and a category; some categories carry more durable
+ * upside on pump.fun than others. This pillar is intentionally the lightest
+ * mover: a great story can't save a rugged structure, but it breaks ties.
+ *
+ * @param {object} nv narrative slice of CoinIntel
+ * @returns {{score:number, reasons:string[]}}
+ */
+export function narrativeScore(nv = {}) {
+ const reasons = [];
+ const virality = num(nv.virality, NaN);
+ const confidence = num(nv.confidence, 0.5);
+
+ // Category priors: how often this flavor sustains attention. Tuned, not gospel.
+ const CATEGORY_PRIOR = {
+ news: 70, culture: 66, ai: 64, meme: 60, animal: 56, celebrity: 54,
+ political: 52, community: 58, tech: 50, utility: 46, unknown: 40,
+ };
+ const cat = String(nv.category || 'unknown').toLowerCase();
+ const prior = CATEGORY_PRIOR[cat] ?? 40;
+
+ let score;
+ if (Number.isFinite(virality)) {
+ // Blend the classifier's virality with the category prior, weighted by the
+ // classifier's confidence so a low-confidence call leans on the prior.
+ score = virality * (0.4 + 0.4 * confidence) + prior * (0.6 - 0.4 * confidence);
+ reasons.push(`${cat} narrative, virality ${Math.round(virality)}/100`);
+ } else {
+ score = prior;
+ reasons.push(`${cat} narrative (no virality estimate yet)`);
+ }
+
+ if (cat === 'news') reasons.push('riding a live news story — fast but fragile');
+ if (cat === 'unknown') reasons.push('narrative unclassified — treat with caution');
+
+ return { score: clamp(score), reasons };
+}
+
+/**
+ * Momentum / behavior — is real buying pressure showing up, and is the dev's
+ * own buy sized like conviction or like a honeypot? Reads the early footprint.
+ *
+ * @param {object} bh behavior slice of CoinIntel
+ * @returns {{score:number, reasons:string[]}}
+ */
+export function momentumScore(bh = {}) {
+ const reasons = [];
+ let score = 50;
+
+ const buys = num(bh.buyCount);
+ const sells = num(bh.sellCount);
+ if (buys + sells > 0) {
+ const buyShare = buys / (buys + sells);
+ if (buyShare >= 0.8 && buys >= 10) { score += 22; reasons.push(`${buys} buys vs ${sells} sells — strong inflow`); }
+ else if (buyShare >= 0.65) { score += 12; reasons.push('buyers outnumber sellers'); }
+ else if (buyShare < 0.45) { score -= 16; reasons.push(`${sells} sells vs ${buys} buys — distribution`); }
+ }
+
+ const earlyBuyers = num(bh.earlyBuyerCount);
+ if (earlyBuyers >= 40) { score += 14; reasons.push('rapid early-buyer pile-in'); }
+ else if (earlyBuyers >= 15) { score += 7; }
+
+ // Dev buy sizing: a reasonable dev buy signals skin in the game; a giant one
+ // signals the dev is the top holder (honeypot risk); zero is just neutral.
+ const devBuy = num(bh.devBuySol, NaN);
+ if (Number.isFinite(devBuy)) {
+ if (devBuy >= 0.2 && devBuy <= 2.5) { score += 8; reasons.push(`dev bought ${devBuy.toFixed(2)} SOL — skin in the game`); }
+ else if (devBuy > 6) { score -= 14; reasons.push(`dev bought ${devBuy.toFixed(1)} SOL — oversized dev position`); }
+ }
+
+ if (reasons.length === 0) reasons.push('no clear momentum yet — too early');
+ return { score: clamp(score), reasons };
+}
+
+/**
+ * Fuse the four pillars into Oracle Conviction. Applies the structural cap
+ * (a launch can't score "strong" if its structure flags a bundle/rug), assigns
+ * a tier, and returns a fully transparent breakdown.
+ *
+ * @param {object} intel normalized CoinIntel (see sources.js)
+ * @returns {{
+ * score:number, tier:string, tierLabel:string,
+ * pillars:{pedigree:number,structure:number,narrative:number,momentum:number},
+ * weights:typeof WEIGHTS,
+ * reasons:string[], badges:string[], structureCap:number
+ * }}
+ */
+export function convict(intel = {}) {
+ const ped = pedigreeScore(intel.smartMoney);
+ const str = structureScore(intel.structure);
+ const nar = narrativeScore(intel.narrative);
+ const mom = momentumScore(intel.behavior);
+
+ const pillars = {
+ pedigree: Math.round(ped.score),
+ structure: Math.round(str.score),
+ narrative: Math.round(nar.score),
+ momentum: Math.round(mom.score),
+ };
+
+ let score =
+ ped.score * WEIGHTS.pedigree +
+ str.score * WEIGHTS.structure +
+ nar.score * WEIGHTS.narrative +
+ mom.score * WEIGHTS.momentum;
+
+ // Structural red flags impose a hard ceiling — pedigree/narrative can't paper
+ // over a bundle or a dumping dev.
+ score = Math.min(score, str.cap);
+ score = clamp(Math.round(score));
+
+ const tier = TIERS.find((t) => score >= t.min) || TIERS[TIERS.length - 1];
+
+ // Badges: compact, high-signal flags for cards (the UI renders these as pills).
+ const badges = [];
+ if (num(intel.smartMoney?.smartWalletCount) >= 3) badges.push('smart-money');
+ if (str.cap < 50) badges.push('structure-flag');
+ if (String(intel.narrative?.category).toLowerCase() === 'news') badges.push('news');
+ if (pillars.momentum >= 72) badges.push('momentum');
+ if (score >= 86) badges.push('prime');
+
+ // Order reasons by pillar contribution so the most decisive shows first.
+ const reasons = [
+ ...ped.reasons.map((t) => ({ pillar: 'pedigree', text: t })),
+ ...str.reasons.map((t) => ({ pillar: 'structure', text: t })),
+ ...mom.reasons.map((t) => ({ pillar: 'momentum', text: t })),
+ ...nar.reasons.map((t) => ({ pillar: 'narrative', text: t })),
+ ];
+
+ return {
+ score,
+ tier: tier.tier,
+ tierLabel: tier.label,
+ pillars,
+ weights: WEIGHTS,
+ structureCap: str.cap,
+ reasons,
+ badges,
+ };
+}
+
+/** Map a tier to a UI tone (mirrors the page's CSS class suffixes). */
+export function tierTone(tier) {
+ switch (tier) {
+ case 'prime': return 'good';
+ case 'strong': return 'good';
+ case 'lean': return 'warn';
+ case 'watch': return 'neutral';
+ default: return 'bad';
+ }
+}
diff --git a/api/_lib/oracle/narrative.js b/api/_lib/oracle/narrative.js
new file mode 100644
index 000000000..c5882abce
--- /dev/null
+++ b/api/_lib/oracle/narrative.js
@@ -0,0 +1,162 @@
+// Oracle — cultural narrative classifier.
+//
+// The user's ask: don't just tag a coin "meme" — understand the *thesis*. Is it
+// a news-story meme riding a live headline? A culture/community coin? A tech/AI
+// play? An animal? A celebrity? Each flavor behaves differently on pump.fun, so
+// the conviction engine weights them differently (see conviction.js narrative
+// pillar). This module produces that read.
+//
+// Two paths, both REAL — never a mock:
+// 1. llmComplete (free providers first per platform policy) returns a strict
+// JSON read of category + narrative thesis + a 0–100 virality estimate.
+// 2. If the LLM is unavailable or returns garbage, a deterministic keyword
+// classifier produces a sane category + baseline virality so the pipeline
+// never stalls and never fabricates confidence it doesn't have.
+//
+// Category set is aligned with the existing pump_coin_intel taxonomy so the two
+// systems agree; Oracle adds the free-text `narrative` and `virality`.
+
+import { llmComplete } from '../llm.js';
+
+export const CATEGORIES = [
+ 'meme', 'tech', 'ai', 'culture', 'community',
+ 'political', 'news', 'animal', 'celebrity', 'utility', 'unknown',
+];
+const CATEGORY_SET = new Set(CATEGORIES);
+
+// Keyword lexicons for the deterministic fallback. Deliberately broad — the
+// fallback only needs to be directionally right; the LLM path is the precise one.
+const LEXICON = {
+ ai: ['ai', 'agent', 'gpt', 'llm', 'neural', 'model', 'machine learning', 'inference', 'agentic', 'autonomous'],
+ tech: ['protocol', 'chain', 'zk', 'rollup', 'defi', 'staking', 'oracle', 'infra', 'sdk', 'api', 'l2', 'rwa', 'depin'],
+ animal: ['dog', 'cat', 'shiba', 'inu', 'frog', 'pepe', 'doge', 'wif', 'hat', 'bonk', 'monkey', 'ape', 'bird', 'penguin', 'hippo', 'capybara', 'goat'],
+ political: ['trump', 'biden', 'maga', 'election', 'president', 'senate', '政', 'kamala', 'vance', '政府', 'government', 'vote'],
+ celebrity: ['elon', 'musk', 'kanye', 'taylor', 'drake', 'mrbeast', 'ronaldo', 'messi', 'celebrity', 'star'],
+ news: ['breaking', 'just in', 'announced', 'launches', 'report', 'headline', 'today', 'news', 'leaked', 'confirmed'],
+ community: ['community', 'dao', 'cto', 'takeover', 'family', 'army', 'holders', 'together', 'movement'],
+ culture: ['vibe', 'aesthetic', 'core', 'lore', 'meta', 'based', 'gigachad', 'sigma', 'brainrot', 'skibidi', 'rizz'],
+ utility: ['tool', 'utility', 'dashboard', 'tracker', 'bot', 'scanner', 'terminal', 'app', 'platform'],
+ meme: ['meme', 'coin', 'moon', 'pump', 'lol', 'kek', '420', '69', 'wojak', 'chad'],
+};
+
+const clamp = (n, lo = 0, hi = 100) => Math.max(lo, Math.min(hi, n));
+
+function corpus({ name, symbol, description } = {}) {
+ return [name, symbol, description].filter(Boolean).join(' ').toLowerCase();
+}
+
+/**
+ * Deterministic keyword classifier. Real fallback — scores each category by
+ * keyword hits, picks the best, and derives a baseline virality from signal
+ * richness (links present, description length, punchy symbol).
+ *
+ * @param {object} meta { name, symbol, description, twitter, telegram, website }
+ * @returns {{category:string, narrative:string, virality:number, confidence:number, tags:string[], source:'heuristic'}}
+ */
+export function heuristicNarrative(meta = {}) {
+ const text = corpus(meta);
+ const tags = [];
+ let best = 'unknown';
+ let bestHits = 0;
+
+ // Category ordering matters for ties: more specific categories first.
+ for (const cat of ['ai', 'tech', 'political', 'celebrity', 'animal', 'news', 'community', 'culture', 'utility', 'meme']) {
+ let hits = 0;
+ for (const kw of LEXICON[cat]) {
+ if (kw && text.includes(kw)) { hits += 1; if (tags.length < 6 && !tags.includes(kw)) tags.push(kw); }
+ }
+ if (hits > bestHits) { bestHits = hits; best = cat; }
+ }
+
+ // Baseline virality from how much signal the launch carries.
+ let virality = 30;
+ if (meta.twitter) virality += 12;
+ if (meta.telegram) virality += 8;
+ if (meta.website) virality += 6;
+ if (meta.description && meta.description.length > 40) virality += 8;
+ if (meta.symbol && meta.symbol.length <= 5) virality += 6; // punchy tickers travel
+ virality += Math.min(18, bestHits * 4);
+ virality = clamp(virality);
+
+ const narrative = bestHits
+ ? `Keyword read: ${best} (${tags.slice(0, 3).join(', ')})`
+ : 'Unclassified — no strong narrative keywords detected';
+
+ return {
+ category: best,
+ narrative,
+ virality,
+ confidence: bestHits ? clamp(30 + bestHits * 12, 0, 80) / 100 : 0.2,
+ tags,
+ source: 'heuristic',
+ };
+}
+
+// Tolerant JSON extraction — models occasionally wrap JSON in prose or fences.
+function parseJsonish(text) {
+ if (!text) return null;
+ let t = String(text).trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim();
+ const start = t.indexOf('{');
+ const end = t.lastIndexOf('}');
+ if (start === -1 || end === -1 || end < start) return null;
+ try { return JSON.parse(t.slice(start, end + 1)); } catch { return null; }
+}
+
+const SYSTEM = `You are Oracle, a pump.fun launch analyst. Classify a new token's CULTURAL NARRATIVE from its metadata.
+Return ONLY minified JSON, no prose, with exactly these keys:
+{"category": one of ["meme","tech","ai","culture","community","political","news","animal","celebrity","utility","unknown"],
+ "narrative": "one crisp sentence naming the actual thesis/story (e.g. 'rides today's <headline> news', 'CTO community revival', 'AI agent infra')",
+ "virality": integer 0-100 (how likely this catches sustained attention; reward live news hooks, recognizable culture, clean tickers; punish generic/empty),
+ "tags": array of up to 5 short lowercase tags,
+ "confidence": number 0-1}
+Be decisive. If it's a meme riding a current event, prefer "news". If it's a community/CTO takeover, prefer "community". If empty/spam, category "unknown" with low virality.`;
+
+/**
+ * Classify a coin's narrative. Tries the LLM (free-first); on any failure or a
+ * malformed response, returns the deterministic heuristic. Never throws.
+ *
+ * @param {object} meta { name, symbol, description, twitter, telegram, website }
+ * @param {object} [opts] { timeoutMs }
+ * @returns {Promise<{category:string, narrative:string, virality:number, confidence:number, tags:string[], source:'llm'|'heuristic'}>}
+ */
+export async function classifyNarrative(meta = {}, opts = {}) {
+ const user = JSON.stringify({
+ name: meta.name || null,
+ symbol: meta.symbol || null,
+ description: (meta.description || '').slice(0, 600) || null,
+ links: {
+ twitter: meta.twitter || null,
+ telegram: meta.telegram || null,
+ website: meta.website || null,
+ },
+ });
+
+ let res;
+ try {
+ res = await llmComplete({
+ system: SYSTEM,
+ user,
+ maxTokens: 220,
+ timeoutMs: opts.timeoutMs ?? 12_000,
+ track: { tool: 'oracle_narrative' },
+ });
+ } catch {
+ return heuristicNarrative(meta);
+ }
+
+ const parsed = parseJsonish(res?.text);
+ if (!parsed || typeof parsed !== 'object') return heuristicNarrative(meta);
+
+ const category = CATEGORY_SET.has(String(parsed.category)) ? String(parsed.category) : 'unknown';
+ const virality = clamp(Math.round(Number(parsed.virality)));
+ if (!Number.isFinite(virality)) return heuristicNarrative(meta);
+
+ return {
+ category,
+ narrative: String(parsed.narrative || '').slice(0, 200) || 'No narrative provided',
+ virality,
+ confidence: Math.max(0, Math.min(1, Number(parsed.confidence) || 0.5)),
+ tags: Array.isArray(parsed.tags) ? parsed.tags.slice(0, 5).map((t) => String(t).toLowerCase().slice(0, 24)) : [],
+ source: 'llm',
+ };
+}
diff --git a/api/_lib/oracle/sources.js b/api/_lib/oracle/sources.js
new file mode 100644
index 000000000..838a61f2f
--- /dev/null
+++ b/api/_lib/oracle/sources.js
@@ -0,0 +1,207 @@
+// Oracle — source adapter over the data brain.
+//
+// This is the only place Oracle touches the platform's existing pump.fun tables.
+// It reads them defensively (every query is isolated so a missing/younger table
+// degrades that one slice to null instead of failing the whole assembly) and
+// maps them into the single normalized `CoinIntel` shape the pure conviction
+// engine consumes. Keeping the coupling here means a schema change in the brain
+// only ever breaks this file, never the scoring logic or the API surface.
+//
+// Brain tables read:
+// pump_coin_intel — coin record + precomputed structural/narrative signals
+// coin_smart_money — pedigree: proven-money score + notable wallets
+// oracle_narrative — Oracle's own cultural read (virality), if classified
+// pump_coin_outcomes — ground-truth outcome (for the conviction backtest)
+
+import { sql } from '../db.js';
+
+const LAMPORTS = 1e9;
+const n = (v) => (v == null ? null : Number(v));
+const pct01 = (v) => (v == null ? null : Math.max(0, Math.min(100, Number(v) * 100)));
+
+/** Best-effort single-row query; returns null on any error (missing table etc). */
+async function tryRow(fn) {
+ try {
+ const rows = await fn();
+ return rows && rows[0] ? rows[0] : null;
+ } catch {
+ return null;
+ }
+}
+async function tryRows(fn) {
+ try {
+ return (await fn()) || [];
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Assemble the normalized CoinIntel for one mint from the brain. Any slice that
+ * isn't available yet is simply omitted — the conviction engine tolerates gaps.
+ *
+ * @param {string} mint
+ * @param {string} network
+ * @returns {Promise<object|null>} CoinIntel, or null if the coin is unknown
+ */
+export async function assembleIntel(mint, network = 'mainnet') {
+ const coin = await tryRow(() => sql`
+ select mint, symbol, name, image_uri, category, narrative, classify_confidence,
+ created_at, first_seen_at,
+ dev_buy_lamports, dev_sold, dev_sell_lamports,
+ buy_count, sell_count, buy_volume_lamports, sell_volume_lamports,
+ unique_buyers, largest_buy_lamports,
+ bundle_score, organic_score, concentration_top10, bubblemap_connectivity,
+ quality_score, risk_flags
+ from pump_coin_intel where mint = ${mint} and network = ${network} limit 1
+ `);
+ if (!coin) return null;
+
+ const [smart, narr] = await Promise.all([
+ tryRow(() => sql`
+ select smart_money_score, smart_wallet_count, proven_buy_lamports, total_buy_lamports, notable
+ from coin_smart_money where mint = ${mint} and network = ${network} limit 1
+ `),
+ tryRow(() => sql`
+ select category, narrative, virality, confidence
+ from oracle_narrative where mint = ${mint} and network = ${network} limit 1
+ `),
+ ]);
+
+ return toCoinIntel({ coin, smart, narr });
+}
+
+/**
+ * Map raw brain rows → normalized CoinIntel. Pure given its inputs (exported so
+ * it can be unit-tested without a DB).
+ */
+export function toCoinIntel({ coin, smart, narr }) {
+ const riskFlags = Array.isArray(coin.risk_flags) ? coin.risk_flags : [];
+ const devBuy = n(coin.dev_buy_lamports);
+ const buyVol = n(coin.buy_volume_lamports) || 0;
+ const largest = n(coin.largest_buy_lamports);
+
+ // Single-biggest-buyer share of buy volume — a top-holder proxy.
+ const topHolderPct = largest != null && buyVol > 0 ? (largest / buyVol) * 100 : null;
+ // Dev footprint as a share of buy volume — a creator-hold proxy.
+ const creatorHoldPct = devBuy != null && buyVol > 0 ? (devBuy / buyVol) * 100 : null;
+ const devSoldPct = coin.dev_sold && devBuy
+ ? (n(coin.dev_sell_lamports) || 0) / devBuy * 100
+ : 0;
+
+ const bundleScore = pct01(coin.bundle_score); // 0..100
+ const organicScore = pct01(coin.organic_score);
+ const top10Pct = pct01(coin.concentration_top10);
+ const connectivity = pct01(coin.bubblemap_connectivity);
+ const bundleFlag = riskFlags.includes('bundle_launch') || (bundleScore != null && bundleScore >= 60);
+
+ // Narrative: Oracle's own classification (has virality) wins; else fall back
+ // to the brain's category with a virality proxy derived from quality/organic.
+ const narrative = narr
+ ? { category: narr.category, virality: n(narr.virality), confidence: n(narr.confidence) }
+ : {
+ category: coin.category || 'unknown',
+ virality: n(coin.quality_score) != null ? Math.round(n(coin.quality_score) * 0.8 + (organicScore || 0) * 0.2) : null,
+ confidence: n(coin.classify_confidence) ?? 0.5,
+ };
+
+ const notable = Array.isArray(smart?.notable) ? smart.notable
+ : (typeof smart?.notable === 'string' ? safeJson(smart.notable) : []);
+
+ return {
+ mint: coin.mint,
+ symbol: coin.symbol,
+ name: coin.name,
+ image_uri: coin.image_uri,
+ category: narrative.category,
+ createdAt: coin.created_at || coin.first_seen_at,
+
+ smartMoney: {
+ score: n(smart?.smart_money_score),
+ smartWalletCount: n(smart?.smart_wallet_count) || (Array.isArray(notable) ? notable.length : 0),
+ provenBuyLamports: n(smart?.proven_buy_lamports) || 0,
+ totalBuyLamports: n(smart?.total_buy_lamports) || buyVol,
+ notable: Array.isArray(notable) ? notable : [],
+ },
+ structure: {
+ uniqueBuyers: n(coin.unique_buyers) || 0,
+ topHolderPct,
+ creatorHoldPct,
+ devSoldPct,
+ organicScore,
+ bundleScore,
+ top10Pct,
+ bubblemapConnectivity: connectivity,
+ bundleFlag,
+ },
+ narrative,
+ behavior: {
+ devBuySol: devBuy != null ? devBuy / LAMPORTS : null,
+ buyCount: n(coin.buy_count) || 0,
+ sellCount: n(coin.sell_count) || 0,
+ buyVolSol: buyVol / LAMPORTS,
+ sellVolSol: (n(coin.sell_volume_lamports) || 0) / LAMPORTS,
+ earlyBuyerCount: n(coin.unique_buyers) || 0,
+ },
+ riskFlags,
+ qualityScore: n(coin.quality_score),
+ };
+}
+
+function safeJson(s) {
+ try { return JSON.parse(s); } catch { return []; }
+}
+
+/**
+ * Recent coins worth (re)scoring — newest first from the brain's coin table.
+ * Used by the ingestion augmentor and as a fallback when oracle_conviction is
+ * cold.
+ *
+ * @param {object} opts { network, limit, sinceSeconds }
+ * @returns {Promise<string[]>} mints
+ */
+export async function recentMints({ network = 'mainnet', limit = 100, sinceSeconds = 6 * 3600 } = {}) {
+ const rows = await tryRows(() => sql`
+ select mint from pump_coin_intel
+ where network = ${network}
+ and first_seen_at > now() - (${sinceSeconds} || ' seconds')::interval
+ order by first_seen_at desc
+ limit ${Math.min(500, Math.max(1, limit))}
+ `);
+ return rows.map((r) => r.mint);
+}
+
+/**
+ * A wallet's reputation + recent footprint, for the wallet profile endpoint.
+ * @param {string} wallet
+ * @param {string} network
+ */
+export async function walletProfile(wallet, network = 'mainnet') {
+ const rep = await tryRow(() => sql`
+ select wallet, coins_traded, early_entries, wins, early_wins, duds, dumps,
+ creator_count, creator_wins, win_rate, early_win_rate, dump_rate,
+ smart_money_score, label, first_seen_at, last_active_at
+ from wallet_reputation where wallet = ${wallet} and network = ${network} limit 1
+ `);
+ const recent = await tryRows(() => sql`
+ select w.mint, w.buy_lamports, w.sell_lamports, w.is_creator, w.last_seen_at,
+ i.symbol, i.name, i.image_uri, i.category
+ from pump_coin_wallets w
+ left join pump_coin_intel i on i.mint = w.mint
+ where w.wallet = ${wallet}
+ order by w.last_seen_at desc
+ limit 25
+ `);
+ return { rep, recent };
+}
+
+/**
+ * Ground-truth outcome for a mint (for the conviction-tier backtest).
+ * @param {string} mint
+ */
+export async function coinOutcome(mint, network = 'mainnet') {
+ return tryRow(() => sql`
+ select graduated, rugged, ath_multiple, last_market_cap_usd
+ from pump_coin_outcomes where mint = ${mint} limit 1
+ `).catch(() => null);
+}
diff --git a/api/_lib/oracle/store.js b/api/_lib/oracle/store.js
new file mode 100644
index 000000000..854c60b39
--- /dev/null
+++ b/api/_lib/oracle/store.js
@@ -0,0 +1,276 @@
+// Oracle — store. Reads/writes Oracle's own tables and orchestrates the
+// score-one-coin flow (assemble intel from the brain → ensure a narrative read →
+// fuse conviction → cache it). Used by both the ingestion augmentor (writes) and
+// the read APIs (lazy-score-on-miss, so the feed is warm even before the worker
+// has swept a brand-new coin).
+
+import { sql } from '../db.js';
+import { assembleIntel, walletProfile, coinOutcome } from './sources.js';
+import { classifyNarrative } from './narrative.js';
+import { convict } from './conviction.js';
+
+/** Persist a narrative classification. */
+export async function upsertNarrative(mint, network, narr) {
+ await sql`
+ insert into oracle_narrative (mint, network, category, narrative, virality, confidence, tags, source, classified_at)
+ values (${mint}, ${network}, ${narr.category}, ${narr.narrative}, ${narr.virality},
+ ${narr.confidence}, ${JSON.stringify(narr.tags || [])}::jsonb, ${narr.source}, now())
+ on conflict (mint, network) do update set
+ category = excluded.category, narrative = excluded.narrative,
+ virality = excluded.virality, confidence = excluded.confidence,
+ tags = excluded.tags, source = excluded.source, classified_at = now()
+ `;
+}
+
+/** Persist a fused conviction verdict for a coin. */
+export async function upsertConviction({ mint, network, intel, verdict }) {
+ await sql`
+ insert into oracle_conviction (
+ mint, network, symbol, name, image_uri,
+ score, tier, pedigree, structure, narrative, momentum, structure_cap,
+ badges, reasons, components, category, smart_wallet_count, coin_first_seen_at, scored_at
+ ) values (
+ ${mint}, ${network}, ${intel.symbol || null}, ${intel.name || null}, ${intel.image_uri || null},
+ ${verdict.score}, ${verdict.tier}, ${verdict.pillars.pedigree}, ${verdict.pillars.structure},
+ ${verdict.pillars.narrative}, ${verdict.pillars.momentum}, ${verdict.structureCap},
+ ${JSON.stringify(verdict.badges)}::jsonb, ${JSON.stringify(verdict.reasons)}::jsonb,
+ ${JSON.stringify(componentSummary(intel))}::jsonb, ${intel.category || null},
+ ${intel.smartMoney?.smartWalletCount || 0}, ${intel.createdAt || null}, now()
+ )
+ on conflict (mint, network) do update set
+ symbol = excluded.symbol, name = excluded.name, image_uri = excluded.image_uri,
+ score = excluded.score, tier = excluded.tier,
+ pedigree = excluded.pedigree, structure = excluded.structure,
+ narrative = excluded.narrative, momentum = excluded.momentum,
+ structure_cap = excluded.structure_cap, badges = excluded.badges,
+ reasons = excluded.reasons, components = excluded.components,
+ category = excluded.category, smart_wallet_count = excluded.smart_wallet_count,
+ scored_at = now()
+ `;
+}
+
+// Compact audit trail of the normalized inputs that produced a verdict.
+function componentSummary(intel) {
+ return {
+ pedigree: intel.smartMoney,
+ structure: intel.structure,
+ narrative: intel.narrative,
+ behavior: intel.behavior,
+ quality: intel.qualityScore,
+ risk_flags: intel.riskFlags,
+ };
+}
+
+/**
+ * Score one coin end-to-end. Assembles intel from the brain; if no narrative
+ * read exists yet (and classify=true) it runs the classifier and stores it;
+ * fuses conviction; caches it. Returns the verdict + intel, or null if the coin
+ * is unknown to the brain.
+ *
+ * @param {string} mint
+ * @param {object} opts { network, classify, persist }
+ */
+export async function scoreCoin(mint, { network = 'mainnet', classify = true, persist = true } = {}) {
+ let intel = await assembleIntel(mint, network);
+ if (!intel) return null;
+
+ // Ensure a narrative read with a virality estimate. If the brain hasn't given
+ // us one (oracle_narrative miss → fallback used a proxy with no virality),
+ // classify now and persist so the next read is warm.
+ if (classify && (intel.narrative?.virality == null)) {
+ const narr = await classifyNarrative({
+ name: intel.name, symbol: intel.symbol,
+ description: intel.components?.description, // may be undefined; classifier tolerates
+ });
+ if (persist) { try { await upsertNarrative(mint, network, narr); } catch { /* non-fatal */ } }
+ intel = { ...intel, narrative: narr, category: narr.category };
+ }
+
+ const verdict = convict(intel);
+ if (persist) { try { await upsertConviction({ mint, network, intel, verdict }); } catch { /* non-fatal */ } }
+ return { intel, verdict };
+}
+
+/**
+ * Read the live conviction feed. Serves from the oracle_conviction cache.
+ * @param {object} opts { network, limit, minScore, tier, category, sinceSeconds }
+ */
+export async function readFeed({ network = 'mainnet', limit = 50, minScore = 0, tier = null, category = null, sinceSeconds = 12 * 3600 } = {}) {
+ const lim = Math.min(200, Math.max(1, Number(limit) || 50));
+ const rows = await sql`
+ select mint, symbol, name, image_uri, score, tier, pedigree, structure, narrative, momentum,
+ badges, category, smart_wallet_count, scored_at, coin_first_seen_at
+ from oracle_conviction
+ where network = ${network}
+ and score >= ${Number(minScore) || 0}
+ and (${tier}::text is null or tier = ${tier})
+ and (${category}::text is null or category = ${category})
+ and scored_at > now() - (${sinceSeconds} || ' seconds')::interval
+ order by score desc, scored_at desc
+ limit ${lim}
+ `;
+ return rows.map(rowToFeedItem);
+}
+
+/** Newly-scored coins after a cursor — powers the SSE stream. */
+export async function feedSince({ network = 'mainnet', sinceIso, limit = 40 } = {}) {
+ const rows = await sql`
+ select mint, symbol, name, image_uri, score, tier, pedigree, structure, narrative, momentum,
+ badges, category, smart_wallet_count, scored_at, coin_first_seen_at
+ from oracle_conviction
+ where network = ${network} and scored_at > ${sinceIso}::timestamptz
+ order by scored_at asc
+ limit ${Math.min(100, Math.max(1, limit))}
+ `;
+ return rows.map(rowToFeedItem);
+}
+
+function rowToFeedItem(r) {
+ return {
+ mint: r.mint, symbol: r.symbol, name: r.name, image_uri: r.image_uri,
+ score: r.score, tier: r.tier,
+ pillars: { pedigree: r.pedigree, structure: r.structure, narrative: r.narrative, momentum: r.momentum },
+ badges: r.badges || [],
+ category: r.category,
+ smart_wallet_count: r.smart_wallet_count,
+ scored_at: r.scored_at,
+ coin_first_seen_at: r.coin_first_seen_at,
+ };
+}
+
+/** Full intel for one coin: cached verdict + live who's-in trader breakdown. */
+export async function readCoin(mint, network = 'mainnet') {
+ const cached = await sql`
+ select * from oracle_conviction where mint = ${mint} and network = ${network} limit 1
+ `.then((r) => r[0]).catch(() => null);
+
+ // "Who's in" — join the coin's wallet footprint to reputation labels, ranked
+ // by net SOL in. This is the trader classification the user asked for, live.
+ const whosIn = await sql`
+ select w.wallet, w.buy_lamports, w.sell_lamports, w.is_creator, w.funder,
+ r.label, r.smart_money_score, r.win_rate, r.early_win_rate
+ from pump_coin_wallets w
+ left join wallet_reputation r on r.wallet = w.wallet and r.network = ${network}
+ where w.mint = ${mint}
+ order by w.buy_lamports desc
+ limit 40
+ `.catch(() => []);
+
+ const [narr, outcome] = await Promise.all([
+ sql`select category, narrative, virality, confidence, source from oracle_narrative where mint = ${mint} and network = ${network} limit 1`
+ .then((r) => r[0]).catch(() => null),
+ coinOutcome(mint, network),
+ ]);
+
+ return {
+ conviction: cached ? rowToFeedItem(cached) : null,
+ reasons: cached?.reasons || [],
+ components: cached?.components || null,
+ structure_cap: cached?.structure_cap ?? null,
+ narrative: narr,
+ outcome,
+ whos_in: whosIn.map((w) => ({
+ wallet: w.wallet,
+ label: w.label || 'unproven',
+ score: w.smart_money_score != null ? Number(w.smart_money_score) : null,
+ win_rate: w.win_rate != null ? Number(w.win_rate) : null,
+ early_win_rate: w.early_win_rate != null ? Number(w.early_win_rate) : null,
+ buy_sol: Number(w.buy_lamports || 0) / 1e9,
+ sell_sol: Number(w.sell_lamports || 0) / 1e9,
+ is_creator: w.is_creator,
+ funder: w.funder,
+ })),
+ };
+}
+
+/** Wallet reputation leaderboard. */
+export async function readLeaderboard({ network = 'mainnet', limit = 50, label = null } = {}) {
+ const rows = await sql`
+ select wallet, label, smart_money_score, win_rate, early_win_rate, dump_rate,
+ coins_traded, early_entries, wins, duds, last_active_at
+ from wallet_reputation
+ where network = ${network}
+ and (${label}::text is null or label = ${label})
+ order by smart_money_score desc nulls last
+ limit ${Math.min(200, Math.max(1, limit))}
+ `.catch(() => []);
+ return rows.map((r) => ({
+ wallet: r.wallet, label: r.label, score: Number(r.smart_money_score || 0),
+ win_rate: Number(r.win_rate || 0), early_win_rate: Number(r.early_win_rate || 0),
+ dump_rate: Number(r.dump_rate || 0), coins_traded: r.coins_traded,
+ early_entries: r.early_entries, wins: r.wins, duds: r.duds, last_active_at: r.last_active_at,
+ }));
+}
+
+/** A wallet's full profile (rep + recent coins). */
+export async function readWallet(wallet, network = 'mainnet') {
+ return walletProfile(wallet, network);
+}
+
+/**
+ * Proof of edge: conviction-tier win rate. Joins cached verdicts to ground-truth
+ * outcomes and reports, per tier, how often the coin went on to graduate / N×.
+ */
+export async function convictionBacktest({ network = 'mainnet' } = {}) {
+ const rows = await sql`
+ select c.tier,
+ count(*)::int as scored,
+ count(o.mint)::int as resolved,
+ coalesce(sum(case when o.graduated then 1 else 0 end),0)::int as graduated,
+ coalesce(sum(case when o.rugged then 1 else 0 end),0)::int as rugged,
+ coalesce(avg(o.ath_multiple),0)::numeric as avg_ath_multiple
+ from oracle_conviction c
+ left join pump_coin_outcomes o on o.mint = c.mint
+ where c.network = ${network}
+ group by c.tier
+ `.catch(() => []);
+ const order = { prime: 0, strong: 1, lean: 2, watch: 3, avoid: 4 };
+ return rows
+ .map((r) => ({
+ tier: r.tier, scored: r.scored, resolved: r.resolved,
+ graduated: r.graduated, rugged: r.rugged,
+ grad_rate: r.resolved ? Math.round((r.graduated / r.resolved) * 100) : null,
+ avg_ath_multiple: Number(r.avg_ath_multiple) || 0,
+ }))
+ .sort((a, b) => (order[a.tier] ?? 9) - (order[b.tier] ?? 9));
+}
+
+// ── Agent watch (action loop config) ─────────────────────────────────────────
+
+export async function getWatch(agentId, network = 'mainnet') {
+ return sql`select * from oracle_agent_watch where agent_id = ${agentId} and network = ${network} limit 1`
+ .then((r) => r[0] || null).catch(() => null);
+}
+
+export async function upsertWatch(agentId, userId, network, cfg) {
+ const row = await sql`
+ insert into oracle_agent_watch (
+ agent_id, user_id, network, armed, mode, min_score, min_tier, categories,
+ per_trade_sol, max_daily_sol, max_open, require_smart_money, updated_at
+ ) values (
+ ${agentId}, ${userId || null}, ${network}, ${!!cfg.armed}, ${cfg.mode || 'simulate'},
+ ${cfg.min_score ?? 80}, ${cfg.min_tier || 'strong'}, ${JSON.stringify(cfg.categories || [])}::jsonb,
+ ${cfg.per_trade_sol ?? 0.05}, ${cfg.max_daily_sol ?? 0.5}, ${cfg.max_open ?? 5},
+ ${cfg.require_smart_money !== false}, now()
+ )
+ on conflict (agent_id, network) do update set
+ user_id = coalesce(excluded.user_id, oracle_agent_watch.user_id),
+ armed = excluded.armed, mode = excluded.mode, min_score = excluded.min_score,
+ min_tier = excluded.min_tier, categories = excluded.categories,
+ per_trade_sol = excluded.per_trade_sol, max_daily_sol = excluded.max_daily_sol,
+ max_open = excluded.max_open, require_smart_money = excluded.require_smart_money,
+ updated_at = now()
+ returning *
+ `;
+ return row[0];
+}
+
+export async function recentActions(agentId, network = 'mainnet', limit = 50) {
+ return sql`
+ select mint, symbol, conviction, tier, mode, size_sol, status, reason,
+ tx_signature, peak_multiple, realized_pnl_sol, outcome, acted_at
+ from oracle_watch_actions
+ where agent_id = ${agentId} and network = ${network}
+ order by acted_at desc limit ${Math.min(100, Math.max(1, limit))}
+ `.catch(() => []);
+}
diff --git a/api/oracle/coin.js b/api/oracle/coin.js
new file mode 100644
index 000000000..9bfaebbdd
--- /dev/null
+++ b/api/oracle/coin.js
@@ -0,0 +1,52 @@
+/**
+ * Oracle — full intel for one coin.
+ *
+ * GET /api/oracle/coin?mint=<mint>&network=mainnet
+ *
+ * Returns the fused conviction verdict (lazy-scored with a fresh narrative read
+ * on a cache miss), the transparent pillar reasons, the narrative classification,
+ * the ground-truth outcome if known, and the live "who's in" trader breakdown —
+ * every early wallet labeled by its data-brain archetype + track record. This is
+ * the trader-classification surface the product is built around.
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { readCoin, scoreCoin } from '../_lib/oracle/store.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const mint = (url.searchParams.get('mint') || '').trim();
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+
+ if (!MINT_RE.test(mint)) return error(res, 400, 'validation_error', 'a valid base58 mint is required');
+
+ let coin = await safeReadCoin(mint, network);
+
+ // Cache miss (no verdict yet) → score it now, with a real narrative read.
+ if (!coin || !coin.conviction) {
+ const scored = await scoreCoin(mint, { network, classify: true, persist: true }).catch(() => null);
+ if (!scored) {
+ // The coin is unknown to the data brain (never observed).
+ return error(res, 404, 'not_found', 'this mint has not been observed yet');
+ }
+ coin = await safeReadCoin(mint, network);
+ }
+
+ return json(res, 200, { network, mint, ...coin }, {
+ 'Cache-Control': 'public, max-age=5, stale-while-revalidate=30',
+ });
+});
+
+async function safeReadCoin(mint, network) {
+ try { return await readCoin(mint, network); } catch { return null; }
+}
diff --git a/api/oracle/feed.js b/api/oracle/feed.js
new file mode 100644
index 000000000..ca704409b
--- /dev/null
+++ b/api/oracle/feed.js
@@ -0,0 +1,60 @@
+/**
+ * Oracle — live conviction feed.
+ *
+ * GET /api/oracle/feed?network=mainnet&limit=50&min_score=0&tier=strong&category=ai
+ *
+ * Serves the materialized oracle_conviction cache (one fast indexed read). On a
+ * cold cache it opportunistically scores a handful of recent coins straight from
+ * the data brain (no LLM — DB-only, fast) so the feed is never empty before the
+ * ingestion augmentor has swept. Also returns the conviction-tier backtest so
+ * the UI can prove the edge.
+ */
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { readFeed, convictionBacktest, scoreCoin } from '../_lib/oracle/store.js';
+import { recentMints } from '../_lib/oracle/sources.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const TIERS = new Set(['prime', 'strong', 'lean', 'watch', 'avoid']);
+const CATEGORIES = new Set(['meme', 'tech', 'ai', 'culture', 'community', 'political', 'news', 'animal', 'celebrity', 'utility', 'unknown']);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const p = url.searchParams;
+ const network = NETWORKS.has(p.get('network')) ? p.get('network') : 'mainnet';
+ const limit = Math.min(200, Math.max(1, Number(p.get('limit')) || 50));
+ const minScore = Math.max(0, Math.min(100, Number(p.get('min_score')) || 0));
+ const tier = TIERS.has(p.get('tier')) ? p.get('tier') : null;
+ const category = CATEGORIES.has(p.get('category')) ? p.get('category') : null;
+
+ let items = await safeFeed({ network, limit, minScore, tier, category });
+
+ // Cold-start warm: if the cache is empty, score a few recent brain coins
+ // (DB-only, no LLM) so the page has something real to render immediately.
+ if (items.length === 0) {
+ const mints = await recentMints({ network, limit: 8, sinceSeconds: 6 * 3600 }).catch(() => []);
+ await Promise.allSettled(mints.map((m) => scoreCoin(m, { network, classify: false, persist: true })));
+ items = await safeFeed({ network, limit, minScore, tier, category });
+ }
+
+ const backtest = await convictionBacktest({ network }).catch(() => []);
+
+ return json(res, 200, {
+ network,
+ count: items.length,
+ items,
+ backtest,
+ generated_at: new Date().toISOString(),
+ }, { 'Cache-Control': 'public, max-age=3, stale-while-revalidate=15' });
+});
+
+async function safeFeed(opts) {
+ try { return await readFeed(opts); } catch { return []; }
+}
diff --git a/api/oracle/stream.js b/api/oracle/stream.js
new file mode 100644
index 000000000..ed122cd33
--- /dev/null
+++ b/api/oracle/stream.js
@@ -0,0 +1,79 @@
+/**
+ * Oracle — live conviction stream (SSE).
+ *
+ * GET /api/oracle/stream?network=mainnet&min_score=0
+ *
+ * The ingestion augmentor is a separate process, so this endpoint can't read its
+ * memory — it DB-polls oracle_conviction for rows scored since a cursor (~2s) and
+ * fans new/updated verdicts to every connected client. Neon serverless HTTP
+ * can't hold a LISTEN connection, so polling is the right call (matches the
+ * sniper/club stream pattern). Events: hello, coin, ping, bye.
+ */
+
+import { cors, method, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { feedSince } from '../_lib/oracle/store.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const MAX_DURATION_MS = 90_000;
+const PING_INTERVAL_MS = 15_000;
+const POLL_INTERVAL_MS = 2_000;
+
+export default async function handleOracleStream(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+ const minScore = Math.max(0, Math.min(100, Number(url.searchParams.get('min_score')) || 0));
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => {
+ if (!active || res.writableEnded) return;
+ try { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); } catch { /* client gone */ }
+ };
+
+ send('hello', { ts: Date.now(), network });
+
+ // Stream only fresh verdicts; the feed endpoint supplies the initial backlog.
+ let cursor = new Date().toISOString();
+
+ const poll = async () => {
+ if (!active) return;
+ try {
+ const items = await feedSince({ network, sinceIso: cursor, limit: 40 });
+ for (const it of items) {
+ if (it.score < minScore) continue;
+ send('coin', it);
+ }
+ if (items.length) cursor = items[items.length - 1].scored_at || cursor;
+ } catch { /* transient DB error — next tick retries */ }
+ };
+
+ const pollTimer = setInterval(poll, POLL_INTERVAL_MS);
+ const pingTimer = setInterval(() => send('ping', { ts: Date.now() }), PING_INTERVAL_MS);
+ const stopTimer = setTimeout(() => { send('bye', { reason: 'rotate' }); cleanup(); }, MAX_DURATION_MS);
+
+ function cleanup() {
+ if (!active) return;
+ active = false;
+ clearInterval(pollTimer);
+ clearInterval(pingTimer);
+ clearTimeout(stopTimer);
+ try { res.end(); } catch { /* already closed */ }
+ }
+
+ req.on('close', cleanup);
+ req.on('error', cleanup);
+}
diff --git a/api/oracle/wallet.js b/api/oracle/wallet.js
new file mode 100644
index 000000000..42641728c
--- /dev/null
+++ b/api/oracle/wallet.js
@@ -0,0 +1,86 @@
+/**
+ * Oracle — wallet intelligence.
+ *
+ * GET /api/oracle/wallet?address=<wallet>&network=mainnet → one wallet's profile
+ * GET /api/oracle/wallet?leaderboard=1&label=smart_money → reputation leaderboard
+ *
+ * The leaderboard ranks every wallet the brain has judged by smart-money score;
+ * the profile returns a wallet's archetype, track record, and recent coins. This
+ * is the "classify the actual traders" surface — across the whole order book, not
+ * just one coin.
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { readLeaderboard, readWallet } from '../_lib/oracle/store.js';
+import { archetypeFor } from '../_lib/oracle/archetype.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const LABELS = new Set(['smart_money', 'sniper', 'dumper', 'rugger', 'fresh', 'neutral', 'unproven']);
+const WALLET_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const p = url.searchParams;
+ const network = NETWORKS.has(p.get('network')) ? p.get('network') : 'mainnet';
+
+ // Leaderboard mode.
+ if (p.get('leaderboard') === '1' || p.get('leaderboard') === 'true') {
+ const label = LABELS.has(p.get('label')) ? p.get('label') : null;
+ const limit = Math.min(200, Math.max(1, Number(p.get('limit')) || 50));
+ const rows = await readLeaderboard({ network, limit, label }).catch(() => []);
+ const items = rows.map((r) => ({ ...r, archetype: archetypeFor(r.label) }));
+ return json(res, 200, { network, count: items.length, items }, {
+ 'Cache-Control': 'public, max-age=10, stale-while-revalidate=60',
+ });
+ }
+
+ // Single-wallet profile mode.
+ const address = (p.get('address') || '').trim();
+ if (!WALLET_RE.test(address)) return error(res, 400, 'validation_error', 'a valid wallet address or leaderboard=1 is required');
+
+ const { rep, recent } = await readWallet(address, network).catch(() => ({ rep: null, recent: [] }));
+ if (!rep) {
+ // Unknown wallet — still return a well-formed unproven profile.
+ return json(res, 200, {
+ network, address, known: false,
+ archetype: archetypeFor(null),
+ reputation: null,
+ recent: [],
+ });
+ }
+
+ return json(res, 200, {
+ network, address, known: true,
+ archetype: archetypeFor(rep.label),
+ reputation: {
+ label: rep.label,
+ score: Number(rep.smart_money_score || 0),
+ win_rate: Number(rep.win_rate || 0),
+ early_win_rate: Number(rep.early_win_rate || 0),
+ dump_rate: Number(rep.dump_rate || 0),
+ coins_traded: rep.coins_traded,
+ early_entries: rep.early_entries,
+ wins: rep.wins,
+ early_wins: rep.early_wins,
+ duds: rep.duds,
+ dumps: rep.dumps,
+ creator_count: rep.creator_count,
+ creator_wins: rep.creator_wins,
+ first_seen_at: rep.first_seen_at,
+ last_active_at: rep.last_active_at,
+ },
+ recent: recent.map((c) => ({
+ mint: c.mint, symbol: c.symbol, name: c.name, image_uri: c.image_uri, category: c.category,
+ buy_sol: Number(c.buy_lamports || 0) / 1e9,
+ sell_sol: Number(c.sell_lamports || 0) / 1e9,
+ is_creator: c.is_creator, last_seen_at: c.last_seen_at,
+ })),
+ }, { 'Cache-Control': 'public, max-age=10, stale-while-revalidate=60' });
+});
diff --git a/api/oracle/watch.js b/api/oracle/watch.js
new file mode 100644
index 000000000..10807273c
--- /dev/null
+++ b/api/oracle/watch.js
@@ -0,0 +1,136 @@
+/**
+ * Oracle — agent action loop config ("arm my agent").
+ *
+ * GET /api/oracle/watch?agent_id=<uuid>&network=mainnet → current config + recent actions
+ * POST /api/oracle/watch { agent_id, armed, mode, min_score, ... } → arm/update
+ *
+ * Arming an agent to act on conviction is an explicit, owner-only opt-in. The
+ * agent watches the live conviction stream; when a coin crosses `min_score` (and
+ * its narrative is in `categories`, and — if required — at least one proven
+ * wallet is in), the loop executes a small buy from the agent's own custodial
+ * Solana wallet. `mode` defaults to 'simulate'; real spend is opt-in and capped.
+ *
+ * Auth: session cookie OR bearer token, scoped to agents the caller owns
+ * (agent_identities.user_id).
+ */
+
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { z } from 'zod';
+import { getWatch, upsertWatch, recentActions } from '../_lib/oracle/store.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const TIERS = new Set(['prime', 'strong', 'lean', 'watch']);
+const CATEGORIES = new Set(['meme', 'tech', 'ai', 'culture', 'community', 'political', 'news', 'animal', 'celebrity', 'utility', 'unknown']);
+const numish = z.union([z.string(), z.number()]);
+
+const WATCH_SCHEMA = z.object({
+ agent_id: z.string().uuid(),
+ network: z.enum(['mainnet', 'devnet']).optional(),
+ armed: z.boolean().optional(),
+ mode: z.enum(['simulate', 'live']).optional(),
+ min_score: numish.optional(),
+ min_tier: z.string().optional(),
+ categories: z.array(z.string()).optional(),
+ per_trade_sol: numish.optional(),
+ max_daily_sol: numish.optional(),
+ max_open: numish.optional(),
+ require_smart_money: z.boolean().optional(),
+});
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+async function ownsAgent(userId, agentId) {
+ const rows = await sql`
+ select id from agent_identities
+ where id = ${agentId} and user_id = ${userId} and deleted_at is null
+ limit 1
+ `.catch(() => []);
+ return rows.length > 0;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const userId = await resolveUserId(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in to arm an agent');
+
+ if (req.method === 'GET') {
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const agentId = (url.searchParams.get('agent_id') || '').trim();
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+ if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required');
+ if (!(await ownsAgent(userId, agentId))) return error(res, 403, 'forbidden', 'you do not own this agent');
+
+ const [watch, actions] = await Promise.all([
+ getWatch(agentId, network),
+ recentActions(agentId, network, 50),
+ ]);
+ return json(res, 200, { agent_id: agentId, network, watch: watch || defaultWatch(agentId, network), actions });
+ }
+
+ // POST — arm / update.
+ const body = await readJson(req).catch(() => null);
+ const parsed = WATCH_SCHEMA.safeParse(body);
+ if (!parsed.success) return error(res, 400, 'validation_error', 'invalid watch config', { issues: parsed.error.issues });
+
+ const cfg = parsed.data;
+ const network = NETWORKS.has(cfg.network) ? cfg.network : 'mainnet';
+ if (!(await ownsAgent(userId, cfg.agent_id))) return error(res, 403, 'forbidden', 'you do not own this agent');
+
+ // Normalize + clamp the risk knobs server-side; never trust the client.
+ const minScore = clampInt(cfg.min_score, 0, 100, 80);
+ const minTier = TIERS.has(cfg.min_tier) ? cfg.min_tier : 'strong';
+ const categories = Array.isArray(cfg.categories) ? cfg.categories.filter((c) => CATEGORIES.has(c)).slice(0, 11) : [];
+ const perTrade = clampNum(cfg.per_trade_sol, 0.001, 5, 0.05);
+ const maxDaily = clampNum(cfg.max_daily_sol, perTrade, 50, Math.max(0.5, perTrade * 10));
+ const maxOpen = clampInt(cfg.max_open, 1, 50, 5);
+
+ // A live, armed agent with no size makes no sense — guard it.
+ if (cfg.armed && cfg.mode === 'live' && perTrade <= 0) {
+ return error(res, 400, 'validation_error', 'set a per-trade size before arming a live agent');
+ }
+
+ const saved = await upsertWatch(cfg.agent_id, userId, network, {
+ armed: !!cfg.armed,
+ mode: cfg.mode || 'simulate',
+ min_score: minScore,
+ min_tier: minTier,
+ categories,
+ per_trade_sol: perTrade,
+ max_daily_sol: maxDaily,
+ max_open: maxOpen,
+ require_smart_money: cfg.require_smart_money !== false,
+ });
+
+ return json(res, 200, { agent_id: cfg.agent_id, network, watch: saved });
+});
+
+function defaultWatch(agentId, network) {
+ return {
+ agent_id: agentId, network, armed: false, mode: 'simulate',
+ min_score: 80, min_tier: 'strong', categories: [],
+ per_trade_sol: 0.05, max_daily_sol: 0.5, max_open: 5, require_smart_money: true,
+ };
+}
+
+function clampInt(v, lo, hi, dflt) {
+ const n = Math.round(Number(v));
+ return Number.isFinite(n) ? Math.max(lo, Math.min(hi, n)) : dflt;
+}
+function clampNum(v, lo, hi, dflt) {
+ const n = Number(v);
+ return Number.isFinite(n) ? Math.max(lo, Math.min(hi, n)) : dflt;
+}
diff --git a/api/pump/launch-detail.js b/api/pump/launch-detail.js
new file mode 100644
index 000000000..aa88915f1
--- /dev/null
+++ b/api/pump/launch-detail.js
@@ -0,0 +1,266 @@
+/**
+ * /api/pump/launch-detail — the single server-side aggregator behind the rich
+ * /launches/<mint> coin page.
+ *
+ * GET /api/pump/launch-detail?mint=<mint>&network=mainnet|devnet
+ *
+ * One round-trip fuses every DB-side truth we hold about a coin so the page
+ * paints a complete picture before any client-side enrichment:
+ *
+ * · registry — is this a three.ws agent launch? (pump_agent_mints) +
+ * the agent identity and avatar behind it
+ * · economics — confirmed agent payments, unique payers, buyback burns
+ * (pump_agent_payments / pump_buyback_runs)
+ * · intel — the Coin Intelligence Engine's first-seconds verdict
+ * (pump_coin_intel) — quality / bundle / organic / risk flags
+ * · outcome — graduated / rugged / ATH multiple (pump_coin_outcomes)
+ * · trader — the launching agent's verifiable track record
+ * (trader-stats truth layer, same numbers as the leaderboard)
+ *
+ * Live market price, the price chart, the trade tape, holder cohorts and the
+ * community feed are streamed in by the client from their own dedicated
+ * endpoints — this aggregator stays a fast, cacheable database read.
+ *
+ * Public + IP rate-limited. Every number traces to an on-chain transaction or a
+ * row we persisted from one; nothing here is synthesized. A coin that isn't a
+ * three.ws launch still resolves (found:false) with whatever intel we observed,
+ * so the page works for any pump.fun mint, not only ours.
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { publicUrl as r2PublicUrl } from '../_lib/r2.js';
+import { normalizeGatewayURL } from '../../src/ipfs.js';
+import { getTraderStats } from '../_lib/trader-stats.js';
+
+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const lamportsToSol = (v) => (v == null ? null : Number(BigInt(v)) / 1e9);
+const num = (v) => (v == null ? null : Number(v));
+
+// The agent avatar is non-critical enrichment. If the R2 public-URL resolver
+// throws (e.g. a misconfigured S3_PUBLIC_DOMAIN), degrade the avatar to null
+// rather than 500 the entire coin page over a decorative thumbnail.
+function safeR2Url(key) {
+ if (!key) return null;
+ try {
+ return r2PublicUrl(key);
+ } catch {
+ return null;
+ }
+}
+
+// Short-lived per-instance cache — the page is read far more than coins are
+// observed, and every underlying query is cheap-but-not-free.
+const CACHE = new Map();
+const TTL_MS = 15_000;
+
+function shapeIntel(r) {
+ if (!r) return null;
+ return {
+ symbol: r.symbol,
+ name: r.name,
+ creator: r.creator,
+ image_uri: r.image_uri,
+ description: r.description,
+ socials: { twitter: r.twitter, telegram: r.telegram, website: r.website },
+ created_at: r.created_at,
+ first_seen_at: r.first_seen_at,
+ observation_seconds: r.observation_seconds,
+ quality_score: r.quality_score,
+ bundle_score: num(r.bundle_score),
+ organic_score: num(r.organic_score),
+ snipe_ratio: num(r.snipe_ratio),
+ concentration_top10: num(r.concentration_top10),
+ fresh_wallet_ratio: num(r.fresh_wallet_ratio),
+ bubblemap_connectivity: num(r.bubblemap_connectivity),
+ risk_flags: r.risk_flags || [],
+ category: r.category,
+ tags: r.tags || [],
+ narrative: r.narrative,
+ classify_confidence: num(r.classify_confidence),
+ classify_source: r.classify_source,
+ dev_buy_sol: lamportsToSol(r.dev_buy_lamports),
+ dev_sold: r.dev_sold,
+ buy_count: r.buy_count,
+ sell_count: r.sell_count,
+ buy_volume_sol: lamportsToSol(r.buy_volume_lamports),
+ sell_volume_sol: lamportsToSol(r.sell_volume_lamports),
+ unique_buyers: r.unique_buyers,
+ unique_sellers: r.unique_sellers,
+ largest_buy_sol: lamportsToSol(r.largest_buy_lamports),
+ };
+}
+
+function shapeOutcome(o) {
+ if (!o) return null;
+ return {
+ outcome: o.outcome,
+ graduated: o.graduated,
+ rugged: o.rugged,
+ ath_multiple: num(o.ath_multiple),
+ ath_market_cap_usd: num(o.ath_market_cap_usd),
+ last_market_cap_usd: num(o.last_market_cap_usd),
+ labeled_at: o.labeled_at,
+ };
+}
+
+async function buildDetail(mint, network) {
+ // Registry row (+ agent identity + avatar) — the authoritative "is this a
+ // three.ws launch, and whose agent is it" answer.
+ const [reg] = await sql`
+ select pam.id, pam.mint, pam.network, pam.name, pam.symbol, pam.buyback_bps,
+ pam.agent_authority, pam.metadata_uri, pam.quote_mint,
+ pam.sharing_config, pam.created_at,
+ ai.id as agent_id, ai.name as agent_name, ai.description as agent_description,
+ ai.is_public as agent_public,
+ a.thumbnail_key as avatar_thumbnail_key, a.visibility as avatar_visibility
+ from pump_agent_mints pam
+ left join agent_identities ai on ai.id = pam.agent_id and ai.deleted_at is null
+ left join avatars a on a.id = ai.avatar_id and a.deleted_at is null
+ where pam.mint=${mint} and pam.network=${network}
+ limit 1
+ `;
+
+ // Intel + outcome (observed by the Coin Intelligence Engine). Independent of
+ // the registry — works for any mint the engine watched.
+ const [intelRow] = await sql`
+ select * from pump_coin_intel where mint=${mint} limit 1
+ `;
+ const [outcomeRow] = await sql`
+ select graduated, rugged, outcome, ath_multiple, ath_market_cap_usd,
+ last_market_cap_usd, labeled_at
+ from pump_coin_outcomes where mint=${mint} limit 1
+ `;
+
+ // Economics + the agent's track record only exist for registry coins.
+ let economics = null;
+ let trader = null;
+ if (reg) {
+ const [stats] = await sql`
+ select
+ count(*) filter (where status='confirmed')::int as confirmed_payments,
+ count(distinct payer_wallet) filter (where status='confirmed')::int as unique_payers,
+ coalesce(sum(amount_atomics) filter (where status='confirmed'),0)::text as total_atomics,
+ max(confirmed_at) filter (where status='confirmed') as last_payment_at
+ from pump_agent_payments where mint_id=${reg.id}
+ `;
+ const [burnRow] = await sql`
+ select
+ count(*) filter (where status='confirmed')::int as runs,
+ coalesce(sum(burn_amount) filter (where status='confirmed'),0)::text as total_burned,
+ max(created_at) as last_burn_at
+ from pump_buyback_runs where mint_id=${reg.id}
+ `;
+ const burnsFeed = await sql`
+ select id, currency_mint, tx_signature, burn_amount, created_at
+ from pump_buyback_runs
+ where mint_id=${reg.id} and status='confirmed'
+ order by created_at desc limit 8
+ `;
+ economics = {
+ confirmed_payments: stats?.confirmed_payments ?? 0,
+ unique_payers: stats?.unique_payers ?? 0,
+ total_atomics: stats?.total_atomics ?? '0',
+ last_payment_at: stats?.last_payment_at ?? null,
+ burns: {
+ runs: burnRow?.runs ?? 0,
+ total_burned: burnRow?.total_burned ?? '0',
+ last_burn_at: burnRow?.last_burn_at ?? null,
+ },
+ burns_feed: burnsFeed,
+ };
+
+ // The launching agent's verifiable PnL — same truth layer as the
+ // leaderboard, so the page and /leaderboard can never disagree. Public
+ // agents only; private track records stay private.
+ if (reg.agent_id && reg.agent_public) {
+ try {
+ const s = await getTraderStats({ agentId: reg.agent_id, network, window: 'all' });
+ if (s?.metrics && s.metrics.closed_count > 0) {
+ const m = s.metrics;
+ trader = {
+ agent_id: reg.agent_id,
+ score: m.score,
+ verified: m.verified,
+ closed_count: m.closed_count,
+ open_count: m.open_count,
+ win_rate: m.win_rate,
+ realized_pnl_sol: m.realized_pnl_sol,
+ realized_pnl_usd: m.realized_pnl_usd,
+ roi_pct: m.roi_pct,
+ unique_coins: m.unique_coins,
+ best_pnl_pct: m.best_pnl_pct,
+ last_active_at: m.last_active_at,
+ };
+ }
+ } catch {
+ /* track record is best-effort enrichment; never block the page on it */
+ }
+ }
+ }
+
+ const avatarPublic =
+ reg?.avatar_visibility === 'public' || reg?.avatar_visibility === 'unlisted';
+
+ return {
+ mint,
+ network,
+ found: !!reg,
+ registry: reg
+ ? {
+ name: reg.name,
+ symbol: reg.symbol,
+ buyback_bps: reg.buyback_bps,
+ agent_authority: reg.agent_authority,
+ metadata_uri: normalizeGatewayURL(reg.metadata_uri) || reg.metadata_uri,
+ quote_mint: reg.quote_mint,
+ sharing_config: reg.sharing_config,
+ created_at: reg.created_at,
+ }
+ : null,
+ agent: reg?.agent_id
+ ? {
+ id: reg.agent_id,
+ name: reg.agent_name,
+ description: reg.agent_description,
+ url: `/agents/${reg.agent_id}`,
+ is_public: reg.agent_public,
+ avatar_thumbnail_url: avatarPublic ? safeR2Url(reg.avatar_thumbnail_key) : null,
+ }
+ : null,
+ economics,
+ intel: shapeIntel(intelRow),
+ outcome: shapeOutcome(outcomeRow),
+ trader,
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const mint = (url.searchParams.get('mint') || '').trim();
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ if (!MINT_RE.test(mint))
+ return error(res, 400, 'invalid_mint', 'mint must be a base58 address');
+
+ const cacheKey = `${network}:${mint}`;
+ const now = Date.now();
+ const hit = CACHE.get(cacheKey);
+ if (hit && now - hit.at < TTL_MS) {
+ res.setHeader('cache-control', 'public, max-age=15, s-maxage=30');
+ return json(res, 200, hit.body);
+ }
+
+ const body = await buildDetail(mint, network);
+ CACHE.set(cacheKey, { at: now, body });
+ if (CACHE.size > 300) CACHE.delete(CACHE.keys().next().value);
+
+ res.setHeader('cache-control', 'public, max-age=15, s-maxage=30');
+ return json(res, 200, body);
+});
diff --git a/data/changelog.json b/data/changelog.json
index 398fe0247..dd4e8d037 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,27 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-16",
+ "title": "Oracle — one conviction score per launch, and an agent that acts on it",
+ "summary": "Oracle is a new way to read pump.fun: instead of a wall of separate metrics, every launch gets one transparent 0–100 conviction score that fuses four reads — WHO is buying it (the proven track record of the wallets in the book), HOW it's being bought (organic vs. a bundle or a single-funder cluster), WHAT it is (a live cultural-narrative read — meme, tech, AI, a news-story meme, a culture or community coin), and HOW it's moving. A hard structural cap means a coordinated bundle or a dumping dev can never read 'strong,' no matter who's in it. Open any coin to see the full breakdown, the exact reasons, and a live 'who's in' panel that labels every early wallet by archetype — smart money, sniper, dumper, rugger — with its real win rate. A wallet leaderboard ranks the proven money, and an honest 'edge' tab shows the realized graduation rate by conviction tier — no backfilled numbers. Best of all, you can arm your 3D AI agent to act: it watches the live conviction stream and buys a small position the moment a coin clears your bar, starting in simulate so you can watch it work before any real spend. The more coins and wallets the platform watches, the sharper every score.",
+ "tags": ["feature"],
+ "link": "/oracle"
+ },
+ {
+ "date": "2026-06-16",
+ "title": "Every launch now has its own page — the full story of a coin in one place",
+ "summary": "Until now, clicking a coin on the launches feed sent you out to pump.fun. Now every launch opens a rich profile that stays on three.ws and answers every question a trader actually has, all from real on-chain data: live price, market cap and graduation progress; the Coin Intelligence verdict from the coin's first ~90 seconds (a quality score plus organic-vs-bundle, sniping, holder concentration, fresh-wallet and funder-clustering signals, with any risk flags called out); the labeled outcome if it graduated or rugged, with its all-time-high multiple; a live price chart and a live trade tape that ticks every buy and sell as it lands; holder count and concentration; the agent behind the mint and its verifiable TraderScore; and the buyback-and-burn economics for agent-payment coins, each burn linking to its on-chain transaction. Watch a coin, share its page, jump into its 3D world, or open it in 3D — every number traces back to a real transaction.",
+ "tags": ["feature"],
+ "link": "/launches"
+ },
+ {
+ "date": "2026-06-16",
+ "title": "The Sniper Arena is now a living 3D world",
+ "summary": "The arena used to be a flat leaderboard. Now it's a real 3D world you walk into. Every armed AI agent stands on the trading floor as an animated avatar — the #1 agent up on a gold podium — and when they trade live, you see it happen: a cheer and a coin burst on a buy, confetti and a back-flip on a big win, a slump on a loss, each one tied to the same on-chain trade scrolling in the live tape. Pick your own avatar from a roster or the community gallery and walk the floor in third person with WASD or a touch joystick. Floating name tags track each agent with their live P&L, and a banner calls out the biggest win as it lands. Every number is real and verifiable on-chain — now it has a face.",
+ "tags": ["feature"],
+ "link": "/play/arena"
+ },
{
"date": "2026-06-15",
"title": "Coin Radar — every pump.fun launch watched, scored, and classified the moment it goes live",
diff --git a/package.json b/package.json
index 19e421973..e7f81488c 100644
--- a/package.json
+++ b/package.json
@@ -135,6 +135,7 @@
"validate:cards": "node scripts/validate-agent-cards.mjs",
"db:migrate": "node scripts/apply-migrations.mjs --apply",
"db:status": "node scripts/apply-migrations.mjs",
+ "worker:oracle": "node workers/oracle/index.js",
"pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js",
"pump:refresh-idls": "node scripts/refresh-pump-idls.mjs",
"seed:skills": "node scripts/seed-skills.js",
diff --git a/pages/coin-intel.html b/pages/coin-intel.html
index fe63b237c..d57c81c2a 100644
--- a/pages/coin-intel.html
+++ b/pages/coin-intel.html
@@ -308,6 +308,11 @@
<meta property="og:image" content="https://three.ws/og-image.png" />
<meta name="twitter:card" content="summary_large_image" />
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"Coin Intelligence","applicationCategory":"FinanceApplication","operatingSystem":"Web","description":"Real-time pump.fun launch intelligence — classification, organic-vs-bundle detection, trader/wallet classification, and a learning quality model.","url":"https://three.ws/coin-intel","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+
+ <meta property="og:site_name" content="three.ws">
+ <meta name="twitter:title" content="Coin Intelligence · three.ws">
+ <meta name="twitter:description" content="Every pump.fun launch watched and classified in real time — organic vs bundle, the wallets behind it, a transparent quality score, and a model that learns which signals predict winners.">
+ <meta name="twitter:image" content="https://three.ws/og-image.png">
</head>
<body>
<header class="site-header"><div id="nav-container"></div></header>
diff --git a/pages/launch-detail.html b/pages/launch-detail.html
new file mode 100644
index 000000000..6897d3bdc
--- /dev/null
+++ b/pages/launch-detail.html
@@ -0,0 +1,81 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Coin · three.ws</title>
+ <meta
+ name="description"
+ content="A live, on-chain profile for a coin launched on three.ws — market cap, the Coin Intelligence verdict, holder distribution, the live trade tape, and the agent behind the mint."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/launches" />
+ <meta property="og:title" content="Coin · three.ws" />
+ <meta
+ property="og:description"
+ content="A live, on-chain profile for a coin launched on three.ws — market cap, intelligence verdict, holders, live trades, and the agent behind it."
+ />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Coin · three.ws" />
+ <meta
+ name="twitter:description"
+ content="A live, on-chain profile for a coin launched on three.ws — market cap, intelligence verdict, holders, live trades, and the agent behind it."
+ />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/launch-detail.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <link rel="canonical" href="https://three.ws/launches" />
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <!-- Ambient field — drifting particle constellation behind everything. -->
+ <canvas id="ld-field" aria-hidden="true"></canvas>
+ <div class="ld-aurora" aria-hidden="true"></div>
+
+ <main id="ld-shell" class="ld-shell" aria-busy="true">
+ <a class="ld-back" href="/launches" aria-label="Back to all launches">← All launches</a>
+
+ <!-- Hero / identity. Hydrated by src/launch-detail.js. -->
+ <section id="ld-hero" class="ld-hero" aria-label="Coin overview"></section>
+
+ <!-- Primary intelligence + market column, secondary sidebar. -->
+ <div class="ld-body">
+ <div class="ld-main">
+ <section id="ld-verdict" class="ld-section" aria-label="Coin Intelligence verdict"></section>
+ <section id="ld-chart" class="ld-section" aria-label="Price history"></section>
+ <section id="ld-distribution" class="ld-section" aria-label="Holder distribution"></section>
+ <section id="ld-economics" class="ld-section" aria-label="Buyback &amp; burn economics"></section>
+ </div>
+ <aside class="ld-side">
+ <section id="ld-agent" class="ld-section" aria-label="The agent behind this coin"></section>
+ <section id="ld-tape" class="ld-section" aria-label="Live trades"></section>
+ <section id="ld-community" class="ld-section" aria-label="Community"></section>
+ <section id="ld-actions" class="ld-section ld-actions" aria-label="Actions"></section>
+ </aside>
+ </div>
+
+ <div id="ld-state" class="ld-state" role="status"></div>
+ </main>
+
+ <script type="module" src="/src/launch-detail.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/pages/launch.html b/pages/launch.html
index 298ff6e40..3bab9e766 100644
--- a/pages/launch.html
+++ b/pages/launch.html
@@ -115,7 +115,9 @@
box-shadow: 0 0 6px rgba(164, 240, 188, 0.6);
}
</style>
- </head>
+
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Launch a Coin","description":"Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.","url":"https://three.ws/launch","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+</head>
<body class="lc-page">
<header><div id="nav-container"></div></header>
<script src="/nav.js"></script>
diff --git a/pages/oracle.html b/pages/oracle.html
new file mode 100644
index 000000000..072d1bb58
--- /dev/null
+++ b/pages/oracle.html
@@ -0,0 +1,320 @@
+<!doctype html>
+<html lang="en" data-theme="dark">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <title>Oracle — fused pump.fun conviction · three.ws</title>
+ <meta name="description" content="Oracle fuses who's buying, how they're buying, what the coin is, and how it's moving into one live conviction score for every pump.fun launch — and lets your 3D AI agent act on the highest-conviction plays. The more data we watch, the sharper every score." />
+ <meta property="og:title" content="Oracle · three.ws" />
+ <meta property="og:description" content="One conviction score per pump.fun launch, fused from full-coverage wallet + coin + structure data. Watch it live. Arm your agent to act on it." />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/oracle" />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Oracle — fused pump.fun conviction" />
+ <meta name="twitter:description" content="One live conviction score per launch, fused from the most data on pump.fun. Arm your agent to act on it." />
+ <link rel="canonical" href="https://three.ws/oracle" />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/nav.css" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"Oracle","applicationCategory":"FinanceApplication","description":"Fused pump.fun conviction scoring — who's buying, how, what, and how it's moving, in one live score, with an agent action loop.","url":"https://three.ws/oracle","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ <style>
+ :root {
+ --bg: #05060c; --panel: rgba(13,15,23,0.72); --panel-solid: #0c0e16; --line: rgba(255,255,255,0.09);
+ --ink: #eaeefa; --muted: #8a92a8; --faint: rgba(255,255,255,0.45);
+ --cyan: #5fe3ff; --violet: #a07bff; --gold: #fbbf24; --up: #34d399; --down: #f87171; --amber: #ff9d4d;
+ --r: 16px; --r-sm: 11px;
+ --mono: ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, monospace;
+ --shadow: 0 18px 52px -22px rgba(0,0,0,0.86), 0 1px 0 rgba(255,255,255,0.05) inset;
+ --blur: saturate(160%) blur(16px);
+ /* pillar accents */
+ --p-ped: #5fe3ff; --p-str: #34d399; --p-nar: #a07bff; --p-mom: #fbbf24;
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; min-height: 100%; background: var(--bg); color: var(--ink);
+ font: 15px/1.55 Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; -webkit-font-smoothing: antialiased; }
+ body { background:
+ radial-gradient(58% 48% at 82% -6%, color-mix(in srgb, var(--violet) 17%, transparent), transparent 70%),
+ radial-gradient(48% 42% at 3% -2%, color-mix(in srgb, var(--cyan) 13%, transparent), transparent 66%), var(--bg); }
+ a { color: inherit; text-decoration: none; }
+ button { font: inherit; color: inherit; cursor: pointer; }
+ .wrap { max-width: 1200px; margin: 0 auto; padding: 0 18px 90px; }
+
+ /* hero */
+ .hero { padding: 40px 0 22px; }
+ .eyebrow { display: inline-flex; align-items: center; gap: 8px; font: 600 12px/1 var(--mono); letter-spacing: .04em;
+ text-transform: uppercase; color: var(--cyan); padding: 7px 12px; border: 1px solid color-mix(in srgb, var(--cyan) 30%, var(--line));
+ border-radius: 999px; background: color-mix(in srgb, var(--cyan) 9%, transparent); }
+ .eyebrow i { width: 7px; height: 7px; border-radius: 50%; background: var(--up); box-shadow: 0 0 0 0 rgba(52,211,153,.6); animation: pulse 1.9s infinite; }
+ .eyebrow i.off { background: var(--muted); animation: none; }
+ @keyframes pulse { 0%{box-shadow:0 0 0 0 rgba(52,211,153,.5)} 70%{box-shadow:0 0 0 7px rgba(52,211,153,0)} 100%{box-shadow:0 0 0 0 rgba(52,211,153,0)} }
+ .hero h1 { font-size: clamp(30px, 5vw, 48px); line-height: 1.04; letter-spacing: -0.026em; margin: 18px 0 12px; font-weight: 800; }
+ .hero h1 span { background: linear-gradient(100deg, var(--cyan), var(--violet)); -webkit-background-clip: text; background-clip: text; color: transparent; }
+ .hero p { max-width: 700px; font-size: 16px; color: var(--muted); margin: 0; }
+ .statline { display: flex; flex-wrap: wrap; gap: 26px; margin-top: 22px; }
+ .statline div span { display: block; font: 600 10.5px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--faint); margin-bottom: 5px; }
+ .statline div b { font: 800 22px/1 var(--mono); }
+
+ /* tabs */
+ .tabs { display: flex; gap: 6px; margin: 28px 0 18px; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
+ .tab { padding: 11px 6px; margin-bottom: -1px; border: none; background: none; color: var(--muted); font-weight: 600; font-size: 14px;
+ border-bottom: 2px solid transparent; transition: color .2s, border-color .2s; }
+ .tab:hover { color: var(--ink); }
+ .tab.on { color: var(--ink); border-bottom-color: var(--cyan); }
+ .tab .ct { font: 600 11px/1 var(--mono); color: var(--faint); margin-left: 6px; }
+ .view { display: none; } .view.on { display: block; animation: fade .3s; }
+ @keyframes fade { from { opacity: 0; transform: translateY(4px); } }
+
+ /* filters */
+ .filters { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 16px; }
+ .seg { display: inline-flex; background: var(--panel); border: 1px solid var(--line); border-radius: 999px; padding: 3px; gap: 2px; }
+ .seg button { padding: 6px 12px; border-radius: 999px; border: none; background: none; color: var(--muted); font: 600 12.5px/1 var(--mono); transition: background .16s, color .16s; }
+ .seg button.on { background: color-mix(in srgb, var(--cyan) 20%, transparent); color: var(--ink); }
+ .sel { background: var(--panel); border: 1px solid var(--line); border-radius: 999px; color: var(--ink); padding: 7px 12px; font: 600 12.5px/1 var(--mono); }
+
+ /* coin grid */
+ .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 14px; }
+ .coin { text-align: left; width: 100%; background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ border: 1px solid var(--line); border-radius: var(--r); padding: 15px; box-shadow: var(--shadow);
+ display: flex; flex-direction: column; gap: 13px; transition: transform .14s, border-color .18s; }
+ .coin:hover { transform: translateY(-3px); border-color: color-mix(in srgb, var(--cyan) 42%, var(--line)); }
+ .coin.flash { animation: flashin .9s ease-out; }
+ @keyframes flashin { 0% { box-shadow: 0 0 0 2px color-mix(in srgb, var(--cyan) 70%, transparent); transform: translateY(-6px); } 100% { box-shadow: var(--shadow); } }
+ .coin-top { display: grid; grid-template-columns: 46px 1fr auto; gap: 12px; align-items: center; }
+ .coin-img { width: 46px; height: 46px; border-radius: 12px; object-fit: cover; background: radial-gradient(120% 100% at 50% 0%, #1b2233, #0d1018); border: 1px solid var(--line); display: grid; place-items: center; font: 700 17px/1 var(--mono); color: var(--faint); }
+ .coin-id { min-width: 0; }
+ .coin-sym { font-weight: 700; font-size: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .coin-name { font-size: 12.5px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ /* conviction dial */
+ .dial { text-align: center; }
+ .dial b { font: 800 26px/1 var(--mono); display: block; }
+ .dial span { font: 600 9px/1 var(--mono); text-transform: uppercase; letter-spacing: .09em; color: var(--faint); }
+ .t-prime b, .t-strong b { color: var(--up); }
+ .t-lean b { color: var(--gold); }
+ .t-watch b { color: var(--muted); }
+ .t-avoid b { color: var(--down); }
+ .tierpill { display: inline-block; font: 700 9.5px/1 var(--mono); text-transform: uppercase; letter-spacing: .08em; padding: 4px 7px; border-radius: 6px; margin-top: 4px; }
+ .tp-prime, .tp-strong { background: color-mix(in srgb, var(--up) 18%, transparent); color: var(--up); }
+ .tp-lean { background: color-mix(in srgb, var(--gold) 16%, transparent); color: var(--gold); }
+ .tp-watch { background: rgba(255,255,255,0.06); color: var(--faint); }
+ .tp-avoid { background: color-mix(in srgb, var(--down) 16%, transparent); color: var(--down); }
+ /* pillar bars */
+ .pillars { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
+ .pil { }
+ .pil .lab { display: flex; justify-content: space-between; font: 600 9.5px/1 var(--mono); color: var(--faint); text-transform: uppercase; letter-spacing: .05em; margin-bottom: 4px; }
+ .pil .lab b { color: var(--ink); }
+ .pil .track { height: 5px; border-radius: 3px; background: rgba(255,255,255,0.07); overflow: hidden; }
+ .pil .fill { height: 100%; border-radius: 3px; transition: width .5s cubic-bezier(.22,1,.36,1); }
+ .pil.ped .fill { background: var(--p-ped); } .pil.str .fill { background: var(--p-str); }
+ .pil.nar .fill { background: var(--p-nar); } .pil.mom .fill { background: var(--p-mom); }
+ .coin-meta { display: flex; gap: 7px; flex-wrap: wrap; }
+ .chip { font: 600 11px/1 var(--mono); padding: 5px 9px; border-radius: 8px; background: rgba(255,255,255,0.05); border: 1px solid var(--line); color: var(--muted); }
+ .chip b { color: var(--ink); }
+ .chip.cat { color: var(--violet); border-color: color-mix(in srgb, var(--violet) 30%, var(--line)); }
+ .chip.sm { color: var(--up); border-color: color-mix(in srgb, var(--up) 30%, var(--line)); }
+ .chip.flag { color: var(--down); border-color: color-mix(in srgb, var(--down) 30%, var(--line)); }
+ .chip.news { color: var(--amber); border-color: color-mix(in srgb, var(--amber) 30%, var(--line)); }
+
+ /* wallet leaderboard */
+ .lwrap { background: var(--panel); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; box-shadow: var(--shadow); }
+ .lhead, .lrow { display: grid; grid-template-columns: 38px 1fr 110px 86px 86px; gap: 10px; align-items: center; padding: 12px 16px; }
+ .lhead { font: 600 10.5px/1 var(--mono); text-transform: uppercase; letter-spacing: .08em; color: var(--faint); border-bottom: 1px solid var(--line); }
+ .lrow { border: 0; border-bottom: 1px solid var(--line); width: 100%; background: none; text-align: left; transition: background .16s; }
+ .lrow:last-child { border-bottom: none; }
+ .lrow:hover { background: rgba(255,255,255,0.04); }
+ .lrank { font: 700 14px/1 var(--mono); color: var(--faint); } .lrank.top { color: var(--gold); }
+ .lw { min-width: 0; display: flex; align-items: center; gap: 9px; }
+ .lw-addr { font: 600 13px/1 var(--mono); overflow: hidden; text-overflow: ellipsis; }
+ .lscore { font: 800 16px/1 var(--mono); text-align: right; }
+ .lstat { font: 600 13px/1 var(--mono); text-align: right; color: var(--muted); } .lstat b { color: var(--ink); }
+ .nlabel { font: 600 10px/1 var(--mono); padding: 4px 7px; border-radius: 6px; white-space: nowrap; }
+ .lb-smart_money { background: color-mix(in srgb, var(--up) 18%, transparent); color: var(--up); }
+ .lb-sniper { background: color-mix(in srgb, var(--gold) 16%, transparent); color: var(--gold); }
+ .lb-dumper, .lb-rugger { background: color-mix(in srgb, var(--down) 18%, transparent); color: var(--down); }
+ .lb-neutral, .lb-fresh, .lb-unproven { background: rgba(255,255,255,0.06); color: var(--faint); }
+
+ /* edge / backtest */
+ .edge { background: var(--panel); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; box-shadow: var(--shadow); }
+ .ehead, .erow { display: grid; grid-template-columns: 110px 1fr 92px 92px 96px; gap: 10px; align-items: center; padding: 13px 18px; }
+ .ehead { font: 600 10.5px/1 var(--mono); text-transform: uppercase; letter-spacing: .08em; color: var(--faint); border-bottom: 1px solid var(--line); }
+ .erow { border-bottom: 1px solid var(--line); } .erow:last-child { border: none; }
+ .gradbar { height: 7px; border-radius: 4px; background: rgba(255,255,255,0.07); overflow: hidden; }
+ .gradbar i { display: block; height: 100%; background: linear-gradient(90deg, var(--up), var(--cyan)); }
+ .intro { color: var(--muted); font-size: 13.5px; max-width: 720px; margin: 0 0 16px; }
+
+ /* agent panel */
+ .apanel { display: grid; grid-template-columns: 1.1fr 1fr; gap: 16px; align-items: start; }
+ .card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--r); padding: 18px; box-shadow: var(--shadow); }
+ .card h3 { margin: 0 0 4px; font-size: 16px; letter-spacing: -0.01em; }
+ .card .sub { color: var(--muted); font-size: 13px; margin: 0 0 16px; }
+ .field { margin-bottom: 14px; }
+ .field label { display: block; font: 600 10.5px/1 var(--mono); text-transform: uppercase; letter-spacing: .07em; color: var(--faint); margin-bottom: 7px; }
+ .field input, .field select { width: 100%; background: rgba(255,255,255,0.03); border: 1px solid var(--line); border-radius: var(--r-sm); color: var(--ink); padding: 10px 12px; font: 600 14px/1 var(--mono); }
+ .field input:focus, .field select:focus { outline: 2px solid color-mix(in srgb, var(--cyan) 60%, transparent); outline-offset: 1px; }
+ .row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
+ .toggle { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 0; border-top: 1px solid var(--line); }
+ .toggle .t-lab b { display: block; font-size: 14px; }
+ .toggle .t-lab span { font-size: 12px; color: var(--muted); }
+ .sw { width: 46px; height: 26px; border-radius: 999px; background: rgba(255,255,255,0.1); border: 1px solid var(--line); position: relative; transition: background .2s; flex: none; }
+ .sw::after { content: ""; position: absolute; top: 2px; left: 2px; width: 20px; height: 20px; border-radius: 50%; background: #fff; transition: transform .2s; }
+ .sw.on { background: var(--up); } .sw.on::after { transform: translateX(20px); }
+ .sw.live.on { background: var(--amber); }
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; }
+ .cchip { padding: 6px 10px; border-radius: 999px; border: 1px solid var(--line); background: rgba(255,255,255,0.03); font: 600 12px/1 var(--mono); color: var(--muted); }
+ .cchip.on { border-color: color-mix(in srgb, var(--violet) 50%, var(--line)); color: var(--ink); background: color-mix(in srgb, var(--violet) 15%, transparent); }
+
+ /* drawer */
+ .drawer { position: fixed; inset: 0; z-index: 40; display: none; } .drawer.open { display: block; }
+ .dr-back { position: absolute; inset: 0; background: rgba(3,4,8,0.68); backdrop-filter: blur(5px); animation: fade .25s; }
+ .dr-panel { position: absolute; right: 0; top: 0; bottom: 0; width: min(520px, 100vw); background: var(--panel-solid);
+ border-left: 1px solid var(--line); box-shadow: var(--shadow); overflow: auto; animation: slidein .3s cubic-bezier(.22,1,.36,1); }
+ @keyframes slidein { from { transform: translateX(34px); opacity: .4; } }
+ .dr-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 18px 20px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--panel-solid); z-index: 1; }
+ .dr-head h3 { margin: 0; font-size: 18px; letter-spacing: -0.01em; }
+ .dr-x { width: 34px; height: 34px; border-radius: 10px; border: 1px solid var(--line); background: rgba(255,255,255,0.03); display: grid; place-items: center; }
+ .dr-x:hover { border-color: var(--cyan); }
+ .dr-body { padding: 18px 20px; }
+ .dr-sec { font: 600 11px/1 var(--mono); text-transform: uppercase; letter-spacing: .09em; color: var(--faint); margin: 20px 0 10px; }
+ .reason { display: flex; gap: 9px; align-items: flex-start; padding: 8px 0; border-bottom: 1px solid var(--line); font-size: 13px; }
+ .reason:last-child { border: none; }
+ .rdot { width: 8px; height: 8px; border-radius: 50%; margin-top: 5px; flex: none; }
+ .rdot.pedigree { background: var(--p-ped); } .rdot.structure { background: var(--p-str); }
+ .rdot.narrative { background: var(--p-nar); } .rdot.momentum { background: var(--p-mom); }
+ .nwallet { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: center; padding: 11px 0; border-bottom: 1px solid var(--line); }
+ .nwallet:last-child { border: none; }
+ .nw-left { min-width: 0; display: flex; flex-direction: column; gap: 4px; }
+ .nw-addr { font: 600 12.5px/1 var(--mono); display: flex; align-items: center; gap: 8px; }
+ .nw-sub { font: 600 10.5px/1 var(--mono); color: var(--faint); }
+ .nw-buy { font: 700 13px/1 var(--mono); text-align: right; }
+ .solscan { font: 600 12px/1 var(--mono); color: var(--cyan); }
+
+ /* states + buttons */
+ .state { padding: 56px 22px; text-align: center; color: var(--muted); }
+ .state b { display: block; color: var(--ink); font-size: 16px; margin-bottom: 8px; }
+ .btn { display: inline-flex; align-items: center; gap: 8px; padding: 10px 16px; border-radius: 999px; border: 1px solid var(--line);
+ background: var(--panel); font-weight: 600; font-size: 13px; transition: transform .12s, border-color .2s, opacity .2s; }
+ .btn:hover { transform: translateY(-1px); border-color: color-mix(in srgb, var(--cyan) 50%, var(--line)); }
+ .btn:disabled { opacity: .5; cursor: not-allowed; transform: none; }
+ .btn.primary { background: linear-gradient(135deg, color-mix(in srgb, var(--cyan) 26%, var(--panel)), color-mix(in srgb, var(--violet) 26%, var(--panel))); border-color: color-mix(in srgb, var(--cyan) 42%, var(--line)); color: #fff; width: 100%; justify-content: center; padding: 12px; }
+ .btn.full { width: 100%; justify-content: center; }
+ .skel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--r); height: 196px; position: relative; overflow: hidden; }
+ .skel::after { content: ""; position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.05), transparent); animation: shimmer 1.4s infinite; }
+ @keyframes shimmer { to { transform: translateX(100%); } }
+ .note { font-size: 12px; color: var(--faint); margin-top: 10px; }
+ .note.warn { color: var(--amber); }
+
+ .foot { margin-top: 34px; padding-top: 18px; border-top: 1px solid var(--line); font-size: 12.5px; color: var(--faint); }
+ .foot b { color: var(--muted); }
+
+ @media (max-width: 760px) {
+ .apanel { grid-template-columns: 1fr; }
+ .lhead, .lrow { grid-template-columns: 30px 1fr 84px 70px; }
+ .ehead, .erow { grid-template-columns: 84px 1fr 70px 76px; }
+ .colhide { display: none; }
+ .dr-panel { width: 100vw; }
+ }
+ @media (prefers-reduced-motion: reduce) { * { animation-duration: .01ms !important; transition-duration: .01ms !important; } }
+ </style>
+</head>
+<body>
+ <div id="nav-container"></div>
+ <script defer src="/nav.js"></script>
+
+ <main class="wrap">
+ <header class="hero">
+ <span class="eyebrow"><i id="liveDot"></i> <span id="liveLabel">Live · fused conviction</span></span>
+ <h1>Stop guessing the coin.<br><span>Know the conviction.</span></h1>
+ <p>Oracle fuses four reads on every pump.fun launch — <b>who's</b> buying it (proven-wallet pedigree), <b>how</b> it's being bought (bundle vs. organic structure), <b>what</b> it is (cultural narrative), and <b>how</b> it's moving — into one transparent 0–100 conviction score. The more coins and wallets we watch, the sharper every score. Then arm your 3D agent to act on the plays that clear your bar.</p>
+ <div class="statline">
+ <div><span>Coins scored</span><b id="stScored">—</b></div>
+ <div><span>Strong+ live</span><b id="stStrong">—</b></div>
+ <div><span>Smart wallets in play</span><b id="stSmart">—</b></div>
+ <div><span>Updated</span><b id="stUpdated">—</b></div>
+ </div>
+ </header>
+
+ <nav class="tabs" role="tablist">
+ <button class="tab on" data-view="feed" role="tab">Live conviction <span class="ct" id="ctFeed"></span></button>
+ <button class="tab" data-view="wallets" role="tab">Top wallets <span class="ct" id="ctWallets"></span></button>
+ <button class="tab" data-view="edge" role="tab">The edge</button>
+ <button class="tab" data-view="agent" role="tab">Arm your agent</button>
+ </nav>
+
+ <!-- FEED -->
+ <section class="view on" id="view-feed">
+ <div class="filters">
+ <div class="seg" id="tierSeg">
+ <button data-tier="" class="on">All</button>
+ <button data-tier="prime">Prime</button>
+ <button data-tier="strong">Strong</button>
+ <button data-tier="lean">Lean</button>
+ </div>
+ <select class="sel" id="catSel" aria-label="Filter by narrative">
+ <option value="">All narratives</option>
+ </select>
+ <select class="sel" id="minSel" aria-label="Minimum score">
+ <option value="0">Any score</option>
+ <option value="56">≥ 56 (Lean)</option>
+ <option value="72">≥ 72 (Strong)</option>
+ <option value="86">≥ 86 (Prime)</option>
+ </select>
+ </div>
+ <div class="grid" id="feedGrid"></div>
+ </section>
+
+ <!-- WALLETS -->
+ <section class="view" id="view-wallets">
+ <p class="intro">Every wallet Oracle has judged, ranked by its real track record — how often it's an early buyer of coins that went on to graduate, against how often it sprays into duds or dumps on its followers. This is the pedigree that powers the conviction score.</p>
+ <div class="filters">
+ <div class="seg" id="labelSeg">
+ <button data-label="" class="on">All</button>
+ <button data-label="smart_money">Smart money</button>
+ <button data-label="sniper">Snipers</button>
+ <button data-label="rugger">Ruggers</button>
+ </div>
+ </div>
+ <div class="lwrap" id="walletWrap"></div>
+ </section>
+
+ <!-- EDGE -->
+ <section class="view" id="view-edge">
+ <p class="intro">Proof, not promises. Every conviction verdict is checked against ground truth — did the coin actually graduate to Raydium? This is the realized graduation rate by conviction tier across everything Oracle has scored. The edge only counts if the higher tiers win more often.</p>
+ <div class="edge" id="edgeWrap"></div>
+ </section>
+
+ <!-- AGENT -->
+ <section class="view" id="view-agent">
+ <div class="apanel">
+ <div class="card" id="armCard">
+ <h3>Arm your 3D agent</h3>
+ <p class="sub">Your agent watches the live conviction stream and acts the instant a coin clears your bar — buying a small position from its own custodial Solana wallet. Starts in <b>simulate</b> so you can watch it work risk-free before any real spend.</p>
+ <div id="armBody"></div>
+ </div>
+ <div class="card">
+ <h3>Recent actions</h3>
+ <p class="sub">Every move your agent makes — simulated or live — lands here, then gets graded against the outcome. This is your agent's win-rate ledger.</p>
+ <div id="actionsBody"><div class="state">Sign in and arm an agent to see its actions.</div></div>
+ </div>
+ </div>
+ </section>
+
+ <footer class="foot">
+ <b>How conviction is built.</b> Oracle reads the platform's full-coverage pump.fun data — every coin, every wallet, every outcome — and fuses pedigree (34%), structure (30%), narrative (18%) and momentum (18%) into one score, with a hard structural cap so a bundle or a dumping dev can never read "strong." Nothing here is financial advice; conviction is a probability, not a promise. Trade small, especially early.
+ </footer>
+ </main>
+
+ <!-- coin drawer -->
+ <div class="drawer" id="drawer" aria-hidden="true">
+ <div class="dr-back" data-close></div>
+ <div class="dr-panel" role="dialog" aria-modal="true" aria-label="Coin conviction detail">
+ <div class="dr-head">
+ <h3 id="drTitle">—</h3>
+ <button class="dr-x" data-close aria-label="Close">✕</button>
+ </div>
+ <div class="dr-body" id="drBody"></div>
+ </div>
+ </div>
+
+ <script type="module" src="/src/oracle.js"></script>
+</body>
+</html>
diff --git a/pages/play/arena.html b/pages/play/arena.html
index 6bfab46ee..d0069200a 100644
--- a/pages/play/arena.html
+++ b/pages/play/arena.html
@@ -212,6 +212,8 @@
}
@media (prefers-reduced-motion: reduce) { * { animation-duration: .01ms !important; } }
</style>
+
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Sniper Arena — autonomous AI agents trading live","description":"Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.","url":"https://three.ws/play/arena","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
</head>
<body>
<canvas id="scene"></canvas>
diff --git a/pages/three.html b/pages/three.html
index bd61d86fa..d95b66579 100644
--- a/pages/three.html
+++ b/pages/three.html
@@ -26,7 +26,10 @@
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
- </head>
+
+ <link rel="canonical" href="https://three.ws/three">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"The $THREE Economy","description":"How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.","url":"https://three.ws/three","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+</head>
<body>
<script type="module" src="/src/three-economy.js"></script>
</body>
diff --git a/public/changelog.json b/public/changelog.json
index 0f1a8a07d..0bc28c68b 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,41 @@
{
- "generated_at": "2026-06-15T22:38:43.771Z",
+ "generated_at": "2026-06-16T01:40:04.863Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-16",
+ "type": "update",
+ "title": "Every launch now has its own page — the full story of a coin in one place",
+ "summary": "Until now, clicking a coin on the launches feed sent you out to pump.fun. Now every launch opens a rich profile that stays on three.ws and answers every question a trader actually has, all from real on-chain data: live price, market cap and graduation progress; the Coin Intelligence verdict from the coin's first ~90 seconds (a quality score plus organic-vs-bundle, sniping, holder concentration, fresh-wallet and funder-clustering signals, with any risk flags called out); the labeled outcome if it graduated or rugged, with its all-time-high multiple; a live price chart and a live trade tape that ticks every buy and sell as it lands; holder count and concentration; the agent behind the mint and its verifiable TraderScore; and the buyback-and-burn economics for agent-payment coins, each burn linking to its on-chain transaction. Watch a coin, share its page, jump into its 3D world, or open it in 3D — every number traces back to a real transaction.",
+ "link": "/launches",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-16",
+ "type": "update",
+ "title": "Oracle — one conviction score per launch, and an agent that acts on it",
+ "summary": "Oracle is a new way to read pump.fun: instead of a wall of separate metrics, every launch gets one transparent 0–100 conviction score that fuses four reads — WHO is buying it (the proven track record of the wallets in the book), HOW it's being bought (organic vs. a bundle or a single-funder cluster), WHAT it is (a live cultural-narrative read — meme, tech, AI, a news-story meme, a culture or community coin), and HOW it's moving. A hard structural cap means a coordinated bundle or a dumping dev can never read 'strong,' no matter who's in it. Open any coin to see the full breakdown, the exact reasons, and a live 'who's in' panel that labels every early wallet by archetype — smart money, sniper, dumper, rugger — with its real win rate. A wallet leaderboard ranks the proven money, and an honest 'edge' tab shows the realized graduation rate by conviction tier — no backfilled numbers. Best of all, you can arm your 3D AI agent to act: it watches the live conviction stream and buys a small position the moment a coin clears your bar, starting in simulate so you can watch it work before any real spend. The more coins and wallets the platform watches, the sharper every score.",
+ "link": "/oracle",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-16",
+ "type": "update",
+ "title": "The Sniper Arena is now a living 3D world",
+ "summary": "The arena used to be a flat leaderboard. Now it's a real 3D world you walk into. Every armed AI agent stands on the trading floor as an animated avatar — the #1 agent up on a gold podium — and when they trade live, you see it happen: a cheer and a coin burst on a buy, confetti and a back-flip on a big win, a slump on a loss, each one tied to the same on-chain trade scrolling in the live tape. Pick your own avatar from a roster or the community gallery and walk the floor in third person with WASD or a touch joystick. Floating name tags track each agent with their live P&L, and a banner calls out the biggest win as it lands. Every number is real and verifiable on-chain — now it has a face.",
+ "link": "/play/arena",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-15",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index 172a62ea0..4d24abdfa 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,30 @@
<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>Every launch now has its own page — the full story of a coin in one place</title>
+ <link>https://three.ws/launches</link>
+ <guid isPermaLink="false">2026-06-16:Every launch now has its own page — the full story of a coin in one place</guid>
+ <pubDate>Tue, 16 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Until now, clicking a coin on the launches feed sent you out to pump.fun. Now every launch opens a rich profile that stays on three.ws and answers every question a trader actually has, all from real on-chain data: live price, market cap and graduation progress; the Coin Intelligence verdict from the coin's first ~90 seconds (a quality score plus organic-vs-bundle, sniping, holder concentration, fresh-wallet and funder-clustering signals, with any risk flags called out); the labeled outcome if it graduated or rugged, with its all-time-high multiple; a live price chart and a live trade tape that ticks every buy and sell as it lands; holder count and concentration; the agent behind the mint and its verifiable TraderScore; and the buyback-and-burn economics for agent-payment coins, each burn linking to its on-chain transaction. Watch a coin, share its page, jump into its 3D world, or open it in 3D — every number traces back to a real transaction.</description>
+ </item>
+ <item>
+ <title>Oracle — one conviction score per launch, and an agent that acts on it</title>
+ <link>https://three.ws/oracle</link>
+ <guid isPermaLink="false">2026-06-16:Oracle — one conviction score per launch, and an agent that acts on it</guid>
+ <pubDate>Tue, 16 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Oracle is a new way to read pump.fun: instead of a wall of separate metrics, every launch gets one transparent 0–100 conviction score that fuses four reads — WHO is buying it (the proven track record of the wallets in the book), HOW it's being bought (organic vs. a bundle or a single-funder cluster), WHAT it is (a live cultural-narrative read — meme, tech, AI, a news-story meme, a culture or community coin), and HOW it's moving. A hard structural cap means a coordinated bundle or a dumping dev can never read 'strong,' no matter who's in it. Open any coin to see the full breakdown, the exact reasons, and a live 'who's in' panel that labels every early wallet by archetype — smart money, sniper, dumper, rugger — with its real win rate. A wallet leaderboard ranks the proven money, and an honest 'edge' tab shows the realized graduation rate by conviction tier — no backfilled numbers. Best of all, you can arm your 3D AI agent to act: it watches the live conviction stream and buys a small position the moment a coin clears your bar, starting in simulate so you can watch it work before any real spend. The more coins and wallets the platform watches, the sharper every score.</description>
+ </item>
+ <item>
+ <title>The Sniper Arena is now a living 3D world</title>
+ <link>https://three.ws/play/arena</link>
+ <guid isPermaLink="false">2026-06-16:The Sniper Arena is now a living 3D world</guid>
+ <pubDate>Tue, 16 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The arena used to be a flat leaderboard. Now it's a real 3D world you walk into. Every armed AI agent stands on the trading floor as an animated avatar — the #1 agent up on a gold podium — and when they trade live, you see it happen: a cheer and a coin burst on a buy, confetti and a back-flip on a big win, a slump on a loss, each one tied to the same on-chain trade scrolling in the live tape. Pick your own avatar from a roster or the community gallery and walk the floor in third person with WASD or a touch joystick. Floating name tags track each agent with their live P&amp;L, and a banner calls out the biggest win as it lands. Every number is real and verifiable on-chain — now it has a face.</description>
+ </item>
<item>
<title>Coin Intelligence</title>
<link>https://three.ws/coin-intel</link>
diff --git a/public/features.json b/public/features.json
index 9ff23d6bf..1111b0b9c 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T22:38:43.759Z",
+ "generated_at": "2026-06-16T01:40:04.848Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/nav-data.js b/public/nav-data.js
index b3150e695..4c36ed85b 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -126,6 +126,13 @@ export const NAV_GROUPS = [
badge: 'New',
desc: 'Which wallets actually win — and what the proven money is buying now',
},
+ {
+ title: 'Oracle',
+ href: '/oracle',
+ badge: 'New',
+ badgeTone: 'live',
+ desc: 'One fused conviction score per launch — and arm your agent to act on it',
+ },
{
title: '3D Visualizer',
href: '/pump-visualizer',
diff --git a/src/launch-detail.css b/src/launch-detail.css
new file mode 100644
index 000000000..714affd9d
--- /dev/null
+++ b/src/launch-detail.css
@@ -0,0 +1,564 @@
+/* /launches/<mint> — the rich profile for one coin.
+ Token-driven (public/tokens.css via nav.css); no hardcoded palette.
+
+ Shares the editorial monochrome language of /launches: ambient field, glass
+ panels, signal-tinted accents (good=success, warn, danger). Every panel owns
+ a designed empty/error state; reduced-motion calms all motion; light theme
+ remaps entirely through tokens. */
+
+body {
+ margin: 0;
+ background: var(--bg-0);
+ color: var(--ink);
+ font-family: var(--font-body);
+ overflow-x: hidden;
+}
+
+/* ── Ambient layers ───────────────────────────────────────────────────────── */
+
+#ld-field {
+ position: fixed;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ pointer-events: none;
+ opacity: 0.8;
+}
+
+.ld-aurora {
+ position: fixed;
+ inset: -20%;
+ z-index: 0;
+ pointer-events: none;
+ background:
+ radial-gradient(36% 28% at 16% 10%, var(--accent-soft), transparent 70%),
+ radial-gradient(30% 26% at 86% 26%, var(--surface-3), transparent 70%),
+ radial-gradient(40% 34% at 60% 96%, var(--surface-2), transparent 72%);
+ filter: blur(52px);
+ animation: ld-aurora-drift 28s var(--ease-standard) infinite alternate;
+}
+
+@keyframes ld-aurora-drift {
+ from { transform: translate3d(-1.5%, -1%, 0) scale(1); }
+ to { transform: translate3d(1.5%, 2%, 0) scale(1.06); }
+}
+
+/* ── Shell ────────────────────────────────────────────────────────────────── */
+
+.ld-shell {
+ position: relative;
+ z-index: 1;
+ max-width: 1120px;
+ margin: 0 auto;
+ padding: calc(var(--header-h) + var(--space-lg)) var(--space-lg) var(--space-2xl);
+}
+
+.ld-back {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2xs);
+ font-size: var(--text-sm);
+ color: var(--ink-dim);
+ text-decoration: none;
+ padding: var(--space-2xs) 0;
+ margin-bottom: var(--space-md);
+ transition: color var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard);
+}
+.ld-back:hover { color: var(--ink-bright); transform: translateX(-2px); }
+.ld-back:focus-visible {
+ outline: var(--focus-ring-width) solid var(--focus-ring-color);
+ outline-offset: var(--focus-ring-offset);
+ border-radius: var(--radius-sm);
+}
+
+/* ── Sections (glass panels) ──────────────────────────────────────────────── */
+
+.ld-section,
+.ld-hero {
+ position: relative;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--surface-1);
+ backdrop-filter: blur(var(--blur-md));
+ padding: var(--space-lg);
+ opacity: 0;
+ transform: translateY(10px);
+ transition: opacity var(--duration-base) var(--ease-out), transform var(--duration-base) var(--ease-out);
+}
+.ld-section.ld-revealed,
+.ld-hero.ld-revealed { opacity: 1; transform: none; }
+@media (prefers-reduced-motion: reduce) {
+ .ld-section, .ld-hero { transition: none; opacity: 1; transform: none; }
+ .ld-aurora { animation: none; }
+}
+.ld-section[hidden] { display: none; }
+
+.ld-sec-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ margin-bottom: var(--space-md);
+}
+.ld-sec-title {
+ display: flex;
+ align-items: center;
+ gap: var(--space-xs);
+ margin: 0;
+ font-family: var(--font-display);
+ font-size: var(--text-md);
+ font-weight: var(--weight-semibold);
+ letter-spacing: -0.01em;
+ color: var(--ink-bright);
+}
+.ld-sec-tag {
+ font-size: var(--text-2xs);
+ text-transform: uppercase;
+ letter-spacing: 0.16em;
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ padding: 2px var(--space-xs);
+ white-space: nowrap;
+}
+
+/* ── Layout ───────────────────────────────────────────────────────────────── */
+
+.ld-hero { margin-bottom: var(--space-lg); }
+
+.ld-body {
+ display: grid;
+ grid-template-columns: minmax(0, 1.7fr) minmax(0, 1fr);
+ gap: var(--space-lg);
+ align-items: start;
+}
+.ld-main, .ld-side {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-lg);
+ min-width: 0;
+}
+@media (max-width: 880px) {
+ .ld-body { grid-template-columns: 1fr; }
+}
+
+/* ── Hero content ─────────────────────────────────────────────────────────── */
+
+.ld-hero-top {
+ display: flex;
+ align-items: center;
+ gap: var(--space-md);
+}
+.ld-coin-avatar {
+ flex: 0 0 auto;
+ width: 72px;
+ height: 72px;
+ border-radius: var(--radius-md);
+ overflow: hidden;
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-3);
+ display: grid;
+ place-items: center;
+}
+.ld-coin-avatar img { width: 100%; height: 100%; object-fit: cover; }
+.ld-avatar-glyph {
+ font-family: var(--font-display);
+ font-size: var(--text-2xl);
+ font-weight: var(--weight-bold);
+ color: var(--ink-bright);
+}
+
+.ld-id { flex: 1 1 auto; min-width: 0; }
+.ld-id-line {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: var(--space-xs) var(--space-sm);
+}
+.ld-name {
+ margin: 0;
+ font-family: var(--font-display);
+ font-size: var(--text-2xl);
+ font-weight: var(--weight-bold);
+ letter-spacing: -0.02em;
+ color: var(--ink-bright);
+ line-height: 1.05;
+ overflow-wrap: anywhere;
+}
+.ld-symbol {
+ font-family: var(--font-mono);
+ font-size: var(--text-md);
+ color: var(--ink-dim);
+}
+.ld-id-meta {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: var(--space-xs);
+ margin-top: var(--space-xs);
+}
+.ld-chip {
+ font-size: var(--text-2xs);
+ text-transform: capitalize;
+ letter-spacing: 0.04em;
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ padding: 2px var(--space-xs);
+ background: var(--surface-2);
+}
+.ld-chip-launch {
+ color: var(--ink-bright);
+ border-color: var(--stroke-strong);
+ background: var(--accent-soft);
+}
+.ld-copy {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ color: var(--ink-dim);
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ padding: 2px var(--space-xs);
+ cursor: pointer;
+ transition: color var(--duration-fast), border-color var(--duration-fast);
+}
+.ld-copy:hover { color: var(--ink-bright); border-color: var(--stroke-strong); }
+.ld-copied { color: var(--success); border-color: var(--success); }
+
+.ld-socials { display: flex; gap: var(--space-xs); margin-top: var(--space-sm); }
+.ld-social {
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ text-decoration: none;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm);
+ padding: 2px var(--space-xs);
+ transition: color var(--duration-fast), border-color var(--duration-fast);
+}
+.ld-social:hover { color: var(--ink-bright); border-color: var(--stroke-strong); }
+
+/* graduation ring */
+.ld-grad {
+ flex: 0 0 auto;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 2px;
+}
+.ld-ring { width: 76px; height: 76px; }
+.ld-ring-track { fill: none; stroke: var(--stroke-strong); stroke-width: 5; }
+.ld-ring-arc {
+ fill: none;
+ stroke: var(--success);
+ stroke-width: 5;
+ stroke-linecap: round;
+ transition: stroke-dasharray var(--duration-slow) var(--ease-out);
+}
+.ld-grad-cap { display: flex; flex-direction: column; align-items: center; }
+.ld-grad-pct { font-size: var(--text-sm); font-weight: var(--weight-semibold); color: var(--ink-bright); }
+.ld-grad-sub { font-size: var(--text-2xs); color: var(--ink-dim); }
+
+.ld-outcome {
+ font-size: var(--text-2xs);
+ font-weight: var(--weight-semibold);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ border-radius: var(--radius-pill);
+ padding: 3px var(--space-sm);
+ display: inline-flex;
+ gap: var(--space-2xs);
+ align-items: center;
+}
+.ld-outcome b { font-weight: var(--weight-bold); }
+.ld-outcome-good { color: var(--success); border: 1px solid var(--success); background: color-mix(in srgb, var(--success) 12%, transparent); }
+.ld-outcome-bad { color: var(--danger); border: 1px solid var(--danger); background: color-mix(in srgb, var(--danger) 12%, transparent); }
+.ld-outcome-muted { color: var(--ink-dim); border: 1px solid var(--stroke); }
+
+.ld-hero-stats {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: var(--space-sm);
+ margin: var(--space-lg) 0 0;
+}
+.ld-stat {
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ background: var(--surface-2);
+ padding: var(--space-sm) var(--space-md);
+}
+.ld-stat dt { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim); margin: 0 0 2px; }
+.ld-stat dd { margin: 0; font-family: var(--font-mono); font-size: var(--text-lg); font-weight: var(--weight-semibold); color: var(--ink-bright); }
+@media (max-width: 560px) {
+ .ld-hero-top { flex-wrap: wrap; }
+ .ld-hero-stats { grid-template-columns: repeat(2, 1fr); }
+ .ld-name { font-size: var(--text-xl); }
+}
+
+/* ── Signal tones (shared) ────────────────────────────────────────────────── */
+
+.ld-good { color: var(--success); }
+.ld-warn { color: var(--warn); }
+.ld-danger { color: var(--danger); }
+.ld-muted { color: var(--ink-dim); }
+.lb-pos { color: var(--success); }
+.lb-neg { color: var(--danger); }
+.lb-muted { color: var(--ink-dim); }
+
+/* ── Verdict ──────────────────────────────────────────────────────────────── */
+
+.ld-verdict { display: flex; flex-direction: column; gap: var(--space-md); }
+.ld-verdict-head { display: flex; align-items: center; gap: var(--space-md); }
+.ld-quality {
+ flex: 0 0 auto;
+ width: 84px;
+ height: 84px;
+ border-radius: var(--radius-md);
+ display: grid;
+ place-items: center;
+ border: 1px solid currentColor;
+ background: color-mix(in srgb, currentColor 8%, transparent);
+}
+.ld-quality-good { color: var(--success); }
+.ld-quality-warn { color: var(--warn); }
+.ld-quality-danger { color: var(--danger); }
+.ld-quality-muted { color: var(--ink-dim); }
+.ld-quality-num { font-family: var(--font-display); font-size: var(--text-2xl); font-weight: var(--weight-bold); line-height: 1; }
+.ld-quality-max { font-size: var(--text-2xs); color: var(--ink-dim); }
+.ld-verdict-copy { min-width: 0; }
+.ld-verdict-label { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim); }
+.ld-narrative { margin: var(--space-2xs) 0 0; font-size: var(--text-sm); color: var(--ink); line-height: 1.5; }
+
+.ld-flags { display: flex; flex-wrap: wrap; gap: var(--space-xs); }
+.ld-flag {
+ font-size: var(--text-2xs);
+ font-weight: var(--weight-medium);
+ border-radius: var(--radius-pill);
+ padding: 3px var(--space-sm);
+ border: 1px solid currentColor;
+ background: color-mix(in srgb, currentColor 10%, transparent);
+ cursor: help;
+}
+.ld-flag-good { color: var(--success); }
+.ld-flag-warn { color: var(--warn); }
+.ld-flag-danger { color: var(--danger); }
+
+.ld-gauges {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: var(--space-sm) var(--space-md);
+}
+@media (max-width: 560px) { .ld-gauges { grid-template-columns: 1fr; } }
+.ld-gauge-head { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 4px; }
+.ld-gauge-label { font-size: var(--text-xs); color: var(--ink-dim); }
+.ld-gauge-val { font-family: var(--font-mono); font-size: var(--text-xs); font-weight: var(--weight-semibold); }
+.ld-gauge-track { height: 6px; border-radius: var(--radius-pill); background: var(--surface-3); overflow: hidden; }
+.ld-gauge-fill { height: 100%; border-radius: var(--radius-pill); transition: width var(--duration-slow) var(--ease-out); }
+.ld-fill-good { background: var(--success); }
+.ld-fill-warn { background: var(--warn); }
+.ld-fill-danger { background: var(--danger); }
+.ld-fill-muted { background: var(--stroke-strong); }
+
+.ld-aggregates {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-xs);
+ padding-top: var(--space-sm);
+ border-top: 1px solid var(--stroke);
+}
+.ld-kv {
+ display: inline-flex;
+ gap: var(--space-2xs);
+ align-items: baseline;
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm);
+ padding: 3px var(--space-xs);
+}
+.ld-kv b { font-family: var(--font-mono); color: var(--ink-bright); font-weight: var(--weight-semibold); }
+
+/* ── Chart ────────────────────────────────────────────────────────────────── */
+
+.ld-chart { display: flex; flex-direction: column; gap: var(--space-sm); }
+.ld-chart-bar { display: flex; gap: 4px; }
+.ld-int-btn {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ color: var(--ink-dim);
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm);
+ padding: 3px var(--space-sm);
+ cursor: pointer;
+ transition: color var(--duration-fast), background var(--duration-fast), border-color var(--duration-fast);
+}
+.ld-int-btn:hover { color: var(--ink-bright); }
+.ld-int-btn.active { color: var(--ink-bright); border-color: var(--stroke-strong); background: var(--surface-3); }
+.ld-chart-canvas { position: relative; min-height: 200px; }
+.ld-chart-readout { display: flex; align-items: baseline; gap: var(--space-sm); margin-bottom: var(--space-2xs); }
+.ld-chart-price { font-family: var(--font-mono); font-size: var(--text-lg); font-weight: var(--weight-semibold); color: var(--ink-bright); }
+.ld-chart-change { font-family: var(--font-mono); font-size: var(--text-sm); }
+.ld-chart-svg { width: 100%; height: 220px; display: block; }
+.ld-chart-up { color: var(--success); }
+.ld-chart-down { color: var(--danger); }
+
+/* ── Distribution ─────────────────────────────────────────────────────────── */
+
+.ld-dist { display: flex; flex-direction: column; gap: var(--space-md); }
+.ld-metrics { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
+.ld-metric {
+ flex: 1 1 90px;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ background: var(--surface-2);
+ padding: var(--space-sm);
+}
+.ld-metric-label { display: block; font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-dim); }
+.ld-metric-val { font-family: var(--font-mono); font-size: var(--text-md); font-weight: var(--weight-semibold); color: var(--ink-bright); }
+.ld-conc-track { height: 10px; border-radius: var(--radius-pill); background: var(--surface-3); overflow: hidden; }
+.ld-conc-top { height: 100%; background: var(--warn); border-radius: var(--radius-pill); transition: width var(--duration-slow) var(--ease-out); }
+.ld-conc-top.ld-good { background: var(--success); }
+.ld-conc-top.ld-danger { background: var(--danger); }
+.ld-conc-legend { display: flex; justify-content: space-between; font-size: var(--text-2xs); color: var(--ink-dim); margin-top: 4px; }
+.ld-cohorts { display: flex; flex-wrap: wrap; gap: var(--space-xs); }
+.ld-cohort {
+ display: inline-flex; gap: var(--space-2xs); align-items: baseline;
+ font-size: var(--text-xs); color: var(--ink-dim);
+ border: 1px solid var(--stroke); border-radius: var(--radius-pill);
+ padding: 3px var(--space-sm); background: var(--surface-2);
+}
+.ld-cohort b { font-family: var(--font-mono); color: var(--ink-bright); }
+
+/* ── Economics ────────────────────────────────────────────────────────────── */
+
+.ld-econ { display: flex; flex-direction: column; gap: var(--space-md); }
+.ld-econ-lede { margin: 0; font-size: var(--text-sm); color: var(--ink-dim); line-height: 1.5; }
+.ld-econ-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-sm); }
+@media (max-width: 640px) { .ld-econ-grid { grid-template-columns: repeat(2, 1fr); } }
+.ld-econ-metric {
+ display: flex; flex-direction: column; gap: 2px;
+ border: 1px solid var(--stroke); border-radius: var(--radius-md);
+ background: var(--surface-2); padding: var(--space-sm);
+}
+.ld-econ-val { font-family: var(--font-mono); font-size: var(--text-lg); font-weight: var(--weight-bold); color: var(--ink-bright); }
+.ld-econ-label { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-dim); }
+.ld-econ-sub { font-size: var(--text-2xs); color: var(--ink-faint); }
+.ld-burn-feed { display: flex; flex-direction: column; gap: var(--space-2xs); padding-top: var(--space-sm); border-top: 1px solid var(--stroke); }
+.ld-burn-feed-title { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim); }
+.ld-burn-row {
+ display: flex; align-items: center; gap: var(--space-sm);
+ text-decoration: none; color: var(--ink-dim);
+ font-size: var(--text-xs); padding: var(--space-2xs) 0;
+ border-bottom: 1px solid var(--surface-3);
+ transition: color var(--duration-fast);
+}
+.ld-burn-row:last-child { border-bottom: none; }
+.ld-burn-row:hover { color: var(--ink-bright); }
+.ld-burn-amt { font-family: var(--font-mono); color: var(--ink); }
+.ld-burn-time { margin-left: auto; }
+.ld-burn-link { color: var(--ink-faint); }
+
+/* ── Agent ────────────────────────────────────────────────────────────────── */
+
+.ld-agent-body { display: flex; flex-direction: column; gap: var(--space-md); }
+.ld-agent-head {
+ display: flex; align-items: center; gap: var(--space-sm);
+ text-decoration: none; padding: var(--space-sm);
+ border: 1px solid var(--stroke); border-radius: var(--radius-md);
+ background: var(--surface-2);
+ transition: border-color var(--duration-fast), background var(--duration-fast);
+}
+.ld-agent-head:hover { border-color: var(--stroke-strong); background: var(--surface-3); }
+.ld-agent-avatar { width: 40px; height: 40px; border-radius: var(--radius-sm); object-fit: cover; flex: 0 0 auto; }
+.ld-agent-avatar-fallback { display: grid; place-items: center; background: var(--surface-3); color: var(--ink-bright); font-weight: var(--weight-bold); }
+.ld-agent-id { flex: 1 1 auto; min-width: 0; }
+.ld-agent-name { display: block; font-weight: var(--weight-semibold); color: var(--ink-bright); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.ld-agent-role { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-dim); }
+.ld-agent-go { color: var(--ink-dim); }
+.ld-agent-desc { margin: 0; font-size: var(--text-sm); color: var(--ink-dim); line-height: 1.5; }
+.ld-agent-note { margin: 0; font-size: var(--text-xs); color: var(--ink-faint); }
+
+.ld-trader { display: flex; gap: var(--space-md); align-items: center; }
+.ld-trader-score { width: 76px; height: 76px; border-radius: var(--radius-md); display: grid; place-items: center; border: 1px solid currentColor; background: color-mix(in srgb, currentColor 8%, transparent); flex: 0 0 auto; }
+.ld-trader-num { font-family: var(--font-display); font-size: var(--text-xl); font-weight: var(--weight-bold); line-height: 1; }
+.ld-trader-max { font-size: 9px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-dim); }
+.ld-trader-stats { flex: 1 1 auto; display: flex; flex-direction: column; gap: 3px; }
+.ld-trader-row { display: flex; justify-content: space-between; font-size: var(--text-xs); }
+.ld-tl { color: var(--ink-dim); }
+.ld-tv { font-family: var(--font-mono); color: var(--ink-bright); }
+.ld-verified svg { width: 14px; height: 14px; vertical-align: middle; }
+
+/* ── Live tape ────────────────────────────────────────────────────────────── */
+
+.ld-live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ink-dim); display: inline-block; transition: background var(--duration-base); }
+.ld-live-dot.ld-live-on { background: var(--success); box-shadow: 0 0 0 0 color-mix(in srgb, var(--success) 60%, transparent); animation: ld-pulse 1.8s var(--ease-standard) infinite; }
+@keyframes ld-pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--success) 55%, transparent); } 70% { box-shadow: 0 0 0 6px transparent; } 100% { box-shadow: 0 0 0 0 transparent; } }
+@media (prefers-reduced-motion: reduce) { .ld-live-dot.ld-live-on { animation: none; } }
+.ld-tape-list { display: flex; flex-direction: column; gap: 2px; max-height: 340px; overflow-y: auto; }
+.ld-trade {
+ display: flex; align-items: center; gap: var(--space-sm);
+ font-family: var(--font-mono); font-size: var(--text-xs);
+ padding: var(--space-2xs) var(--space-xs); border-radius: var(--radius-sm);
+}
+.ld-trade-side { font-weight: var(--weight-bold); width: 34px; }
+.ld-buy { background: color-mix(in srgb, var(--success) 7%, transparent); }
+.ld-buy .ld-trade-side { color: var(--success); }
+.ld-sell { background: color-mix(in srgb, var(--danger) 7%, transparent); }
+.ld-sell .ld-trade-side { color: var(--danger); }
+.ld-trade-amt { color: var(--ink-bright); }
+.ld-trade-who { margin-left: auto; color: var(--ink-dim); }
+.ld-trade-in { animation: ld-slide-in var(--duration-base) var(--ease-out); }
+@keyframes ld-slide-in { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: none; } }
+.ld-tape-empty { font-size: var(--text-xs); color: var(--ink-faint); padding: var(--space-sm); text-align: center; }
+
+/* ── Community + actions ──────────────────────────────────────────────────── */
+
+.ld-community p { margin: 0 0 var(--space-sm); font-size: var(--text-sm); color: var(--ink-dim); line-height: 1.5; }
+.ld-community-ctas, .ld-action-grid { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
+.ld-action-grid .ld-btn { flex: 1 1 auto; justify-content: center; }
+
+/* ── Buttons ──────────────────────────────────────────────────────────────── */
+
+.ld-btn {
+ display: inline-flex; align-items: center; gap: var(--space-2xs);
+ font-size: var(--text-sm); font-weight: var(--weight-medium);
+ text-decoration: none; cursor: pointer;
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-md);
+ padding: var(--space-sm) var(--space-md);
+ background: var(--surface-2); color: var(--ink);
+ transition: transform var(--duration-fast) var(--ease-standard), background var(--duration-fast), border-color var(--duration-fast), color var(--duration-fast);
+}
+.ld-btn:hover { transform: translateY(-1px); border-color: var(--ink-dim); color: var(--ink-bright); }
+.ld-btn:active { transform: translateY(0); }
+.ld-btn:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }
+.ld-btn-primary { background: var(--accent); color: var(--bg-0); border-color: var(--accent); }
+.ld-btn-primary:hover { color: var(--bg-0); filter: brightness(1.08); }
+.ld-btn-ghost { background: transparent; }
+.ld-btn-block { width: 100%; justify-content: center; }
+.ld-watch-on { color: var(--warn); border-color: var(--warn); }
+
+/* ── States ───────────────────────────────────────────────────────────────── */
+
+.ld-empty { text-align: center; padding: var(--space-md) 0; }
+.ld-empty-sm { padding: var(--space-sm) 0; }
+.ld-empty-title { font-weight: var(--weight-semibold); color: var(--ink-bright); margin: 0 0 var(--space-2xs); }
+.ld-empty p { margin: 0 0 var(--space-sm); font-size: var(--text-sm); color: var(--ink-dim); }
+
+.ld-state { margin-top: var(--space-lg); }
+.ld-fatal { text-align: center; max-width: 460px; margin: var(--space-2xl) auto; }
+.ld-fatal h1 { font-family: var(--font-display); font-size: var(--text-xl); color: var(--ink-bright); margin: 0 0 var(--space-sm); }
+.ld-fatal p { color: var(--ink-dim); margin: 0 0 var(--space-lg); }
+.ld-fatal-ctas { display: flex; gap: var(--space-sm); justify-content: center; flex-wrap: wrap; }
+
+/* ── Skeletons ────────────────────────────────────────────────────────────── */
+
+.ld-skel { border-radius: var(--radius-sm); background: linear-gradient(90deg, var(--surface-2) 25%, var(--surface-3) 37%, var(--surface-2) 63%); background-size: 400% 100%; animation: ld-shimmer 1.4s ease infinite; }
+.ld-skel-avatar { width: 72px; height: 72px; border-radius: var(--radius-md); }
+.ld-skel-stack { flex: 1 1 auto; display: flex; flex-direction: column; gap: var(--space-sm); }
+.ld-skel-chart { height: 200px; }
+@keyframes ld-shimmer { from { background-position: 100% 0; } to { background-position: -100% 0; } }
+@media (prefers-reduced-motion: reduce) { .ld-skel { animation: none; } }
diff --git a/src/launch-detail.js b/src/launch-detail.js
new file mode 100644
index 000000000..6633c1fc6
--- /dev/null
+++ b/src/launch-detail.js
@@ -0,0 +1,1204 @@
+// ════════════════════════════════════════════════════════════════════════════
+// /launches/<mint> — the rich, addressable profile for one coin.
+//
+// Every other launch surface bounces traders out to pump.fun. This page keeps
+// them on three.ws and answers every question a trader actually has, in one
+// place, from real on-chain data:
+//
+// · WHAT is it — live name / symbol / logo / price / market cap /
+// graduation, streamed from /api/pump/coin
+// · IS IT SAFE — the Coin Intelligence verdict (quality / bundle /
+// organic / snipe / concentration / fresh wallets /
+// risk flags), from /api/pump/launch-detail
+// · WHAT HAPPENED — the labeled outcome (graduated / rugged / ATH ×)
+// · WHERE IS IT GOING — the live price chart (/api/pump/price-history) and
+// the live trade tape (/api/pump/trades-stream, SSE)
+// · WHO HOLDS IT — holder count + concentration (/api/coin/:mint/cohorts)
+// · WHO MADE IT — the agent behind the mint and its verifiable track
+// record (TraderScore), deep-linked to /trader & /agents
+// · WHY HOLD — buyback-and-burn economics for agent-payment coins
+// · WHAT CAN I DO — buy, view in 3D, enter the coin's world, watch, share
+//
+// Honesty contract: a signal the engine did not measure renders as "not
+// measured", never as 0. A coin we never observed still renders — the page
+// degrades to whatever is real for that mint and tells the user what's missing.
+// ════════════════════════════════════════════════════════════════════════════
+
+import {
+ escapeHtml,
+ compact,
+ fmtSol,
+ fmtUsd,
+ fmtPct,
+ pnlClass,
+ shortAddr,
+ relTime,
+ verifiedBadge,
+} from './trader-format.js';
+
+const GRADUATION_CAP_USD = 69_000; // pump.fun bonding-curve graduation threshold
+const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const state = {
+ mint: null,
+ network: 'mainnet',
+ detail: null,
+ coin: null,
+ tape: null, // EventSource handle
+ chartInterval: '15m',
+ priceTimer: 0,
+};
+
+// ── DOM helpers ──────────────────────────────────────────────────────────────
+
+function el(tag, props = {}, children = []) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'html') node.innerHTML = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v);
+ }
+ for (const c of [].concat(children || [])) {
+ if (c == null || c === false) continue;
+ node.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
+ }
+ return node;
+}
+
+const $ = (id) => document.getElementById(id);
+const SVG_NS = 'http://www.w3.org/2000/svg';
+
+function svg(tag, attrs) {
+ const node = document.createElementNS(SVG_NS, tag);
+ for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, String(v));
+ return node;
+}
+
+function section(target, title, body, { tag = null } = {}) {
+ const head = el('div', { class: 'ld-sec-head' }, [
+ el('h2', { class: 'ld-sec-title', text: title }),
+ tag ? el('span', { class: 'ld-sec-tag', text: tag }) : null,
+ ]);
+ target.replaceChildren(head, body);
+ target.classList.add('ld-revealed');
+}
+
+// ── formatting ───────────────────────────────────────────────────────────────
+
+function fmtMcap(n) {
+ if (!Number.isFinite(n)) return '—';
+ if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
+ if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
+ if (n >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;
+ return `$${n.toFixed(0)}`;
+}
+
+function fmtPrice(n) {
+ if (!Number.isFinite(n) || n <= 0) return '—';
+ if (n >= 1) return `$${n.toFixed(2)}`;
+ if (n >= 0.001) return `$${n.toFixed(5)}`;
+ return `$${n.toExponential(2)}`;
+}
+
+function pctText(v) {
+ // signal helpers express 0..1 fractions; render as whole percents
+ return v == null ? null : `${Math.round(v * 100)}%`;
+}
+
+// ── mint resolution ──────────────────────────────────────────────────────────
+
+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+function resolveMint() {
+ const parts = location.pathname.split('/').filter(Boolean);
+ const fromPath = parts[0] === 'launches' ? parts[1] : null;
+ const qs = new URLSearchParams(location.search);
+ const fromQuery = qs.get('mint');
+ const candidate = (fromPath || fromQuery || '').trim();
+ state.network = qs.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ return MINT_RE.test(candidate) ? candidate : null;
+}
+
+// ── data ─────────────────────────────────────────────────────────────────────
+
+async function fetchJson(url, { signal } = {}) {
+ const r = await fetch(url, { signal });
+ if (!r.ok) throw new Error(`${url} → ${r.status}`);
+ return r.json();
+}
+
+async function loadDetail() {
+ const params = new URLSearchParams({ mint: state.mint, network: state.network });
+ return fetchJson(`/api/pump/launch-detail?${params}`);
+}
+
+async function loadCoin() {
+ // Live pump.fun market — mainnet only (devnet has no pump.fun market data).
+ if (state.network !== 'mainnet') return null;
+ try {
+ return await fetchJson(`/api/pump/coin?mint=${encodeURIComponent(state.mint)}`);
+ } catch {
+ return null;
+ }
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// HERO
+// ════════════════════════════════════════════════════════════════════════════
+
+function graduationRing(pct, size = 76) {
+ const value = Math.max(0, Math.min(100, Number(pct) || 0));
+ const r = size / 2 - 6;
+ const c = 2 * Math.PI * r;
+ const dash = (value / 100) * c;
+ const node = svg('svg', { viewBox: `0 0 ${size} ${size}`, class: 'ld-ring', role: 'img', 'aria-label': `${Math.round(value)}% to graduation` });
+ node.append(
+ svg('circle', { cx: size / 2, cy: size / 2, r, class: 'ld-ring-track' }),
+ svg('circle', {
+ cx: size / 2,
+ cy: size / 2,
+ r,
+ class: 'ld-ring-arc',
+ 'stroke-dasharray': `${dash.toFixed(1)} ${(c - dash).toFixed(1)}`,
+ transform: `rotate(-90 ${size / 2} ${size / 2})`,
+ }),
+ );
+ return node;
+}
+
+function outcomeBadge(outcome) {
+ if (!outcome || !outcome.outcome) return null;
+ const map = {
+ graduated: { label: 'Graduated', tone: 'good', tip: 'This coin completed its bonding curve and moved to an AMM pool.' },
+ rugged: { label: 'Rugged', tone: 'bad', tip: 'The Intelligence Engine labeled this coin as rugged.' },
+ survived: { label: 'Survived', tone: 'good', tip: 'Still trading after the observation window.' },
+ died: { label: 'Faded', tone: 'muted', tip: 'Activity collapsed shortly after launch.' },
+ unknown: null,
+ };
+ const meta = map[outcome.outcome];
+ if (!meta) return null;
+ const parts = [el('span', { text: meta.label })];
+ if (Number.isFinite(outcome.ath_multiple) && outcome.ath_multiple > 1) {
+ parts.push(el('b', { text: `${outcome.ath_multiple.toFixed(1)}× ATH` }));
+ }
+ return el('span', { class: `ld-outcome ld-outcome-${meta.tone}`, title: meta.tip }, parts);
+}
+
+function socialLinks(socials, intel) {
+ const links = [];
+ const s = socials || {};
+ if (s.twitter) links.push(['𝕏', s.twitter, 'X / Twitter']);
+ if (s.telegram) links.push(['Telegram', s.telegram, 'Telegram']);
+ if (s.website) links.push(['Website', s.website, 'Website']);
+ if (!links.length) return null;
+ return el(
+ 'div',
+ { class: 'ld-socials' },
+ links.map(([label, href, aria]) =>
+ el('a', { class: 'ld-social', href, target: '_blank', rel: 'noopener noreferrer', 'aria-label': aria, text: label }),
+ ),
+ );
+}
+
+function copyButton(value, label) {
+ const btn = el('button', {
+ class: 'ld-copy',
+ type: 'button',
+ 'aria-label': `Copy ${label}`,
+ title: `Copy ${label}`,
+ onclick: async () => {
+ try {
+ await navigator.clipboard.writeText(value);
+ const old = btn.textContent;
+ btn.textContent = 'Copied';
+ btn.classList.add('ld-copied');
+ setTimeout(() => {
+ btn.textContent = old;
+ btn.classList.remove('ld-copied');
+ }, 1400);
+ } catch {
+ /* clipboard blocked — selection fallback */
+ const r = document.createRange();
+ r.selectNodeContents(btn);
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(r);
+ }
+ },
+ text: shortAddr(value, 5, 5),
+ });
+ return btn;
+}
+
+function renderHero() {
+ const target = $('ld-hero');
+ const { detail, coin } = state;
+ const intel = detail.intel;
+ const reg = detail.registry;
+
+ // Identity, with graceful fallback precedence: live market → registry → intel.
+ const name = coin?.name || reg?.name || intel?.name || 'Unknown coin';
+ const symbol = (coin?.symbol || reg?.symbol || intel?.symbol || '').toUpperCase();
+ const image = coin?.image_uri || coin?.image || intel?.image_uri || null;
+
+ document.title = `${symbol ? `$${symbol} · ` : ''}${name} · three.ws`;
+
+ const mcap = Number(coin?.usd_market_cap);
+ const supplyAtomic = Number(coin?.total_supply);
+ const supply = Number.isFinite(supplyAtomic) && supplyAtomic > 0 ? supplyAtomic / 1e6 : null;
+ const price = supply && Number.isFinite(mcap) ? mcap / supply : null;
+ const graduated = coin?.complete === true;
+ const gradPct = graduated ? 100 : Number.isFinite(mcap) ? Math.max(0, Math.min(100, (mcap / GRADUATION_CAP_USD) * 100)) : null;
+
+ const avatar = el('div', { class: 'ld-coin-avatar' }, [
+ image
+ ? el('img', { src: image, alt: '', loading: 'eager', referrerpolicy: 'no-referrer', onerror: function () { this.style.display = 'none'; } })
+ : el('span', { class: 'ld-avatar-glyph', text: (symbol || name)[0] || '?' }),
+ ]);
+
+ const idBlock = el('div', { class: 'ld-id' }, [
+ el('div', { class: 'ld-id-line' }, [
+ el('h1', { class: 'ld-name', text: name }),
+ symbol ? el('span', { class: 'ld-symbol', text: `$${symbol}` }) : null,
+ outcomeBadge(detail.outcome),
+ ]),
+ el('div', { class: 'ld-id-meta' }, [
+ detail.found ? el('span', { class: 'ld-chip ld-chip-launch', title: 'Launched by a three.ws agent', text: 'three.ws launch' }) : null,
+ state.network === 'devnet' ? el('span', { class: 'ld-chip', text: 'Devnet' }) : null,
+ intel?.category ? el('span', { class: 'ld-chip', text: intel.category }) : null,
+ copyButton(state.mint, 'mint address'),
+ ]),
+ socialLinks(intel?.socials, intel),
+ ]);
+
+ // Live market stat strip.
+ const stat = (label, value, cls = '') =>
+ el('div', { class: `ld-stat ${cls}` }, [
+ el('dt', { text: label }),
+ el('dd', { text: value }),
+ ]);
+
+ const stats = el('dl', { class: 'ld-hero-stats' }, [
+ stat('Price', fmtPrice(price)),
+ stat('Market cap', fmtMcap(mcap)),
+ stat('24h volume', fmtMcap(Number(coin?.volume_24h ?? coin?.volume24h))),
+ stat('Launched', reg?.created_at || intel?.created_at ? relTime(reg?.created_at || intel?.created_at) : '—'),
+ ]);
+
+ const gradWrap = gradPct != null
+ ? el('div', { class: 'ld-grad', title: graduated ? 'Graduated to AMM' : `${Math.round(gradPct)}% to graduation` }, [
+ graduationRing(gradPct),
+ el('div', { class: 'ld-grad-cap' }, [
+ el('span', { class: 'ld-grad-pct', text: graduated ? 'Graduated' : `${Math.round(gradPct)}%` }),
+ el('span', { class: 'ld-grad-sub', text: graduated ? 'on AMM' : 'to graduation' }),
+ ]),
+ ])
+ : null;
+
+ target.replaceChildren(
+ el('div', { class: 'ld-hero-top' }, [avatar, idBlock, gradWrap]),
+ stats,
+ );
+ target.classList.add('ld-revealed');
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// INTELLIGENCE VERDICT
+// ════════════════════════════════════════════════════════════════════════════
+
+const FLAG_META = {
+ bundle_launch: { label: 'Bundle launch', tone: 'danger', tip: 'Many wallets bought in the same block — likely coordinated.' },
+ dev_dumped: { label: 'Dev dumped', tone: 'danger', tip: 'The creator sold their position.' },
+ dev_dump: { label: 'Dev dumped', tone: 'danger', tip: 'The creator sold their position.' },
+ single_whale: { label: 'Single whale', tone: 'danger', tip: 'One wallet holds an outsized share of supply.' },
+ low_diversity: { label: 'Low diversity', tone: 'danger', tip: 'Few unique buyers — thin, concentrated participation.' },
+ fresh_wallet_swarm: { label: 'Fresh-wallet swarm', tone: 'danger', tip: 'A cluster of brand-new wallets bought together.' },
+ sell_pressure: { label: 'Sell pressure', tone: 'warn', tip: 'Sells are outpacing buys early.' },
+ sniped: { label: 'Sniped', tone: 'warn', tip: 'Snipers grabbed supply in the first moments.' },
+};
+
+function scoreTone(score) {
+ if (score == null) return 'muted';
+ if (score >= 70) return 'good';
+ if (score >= 45) return 'warn';
+ return 'danger';
+}
+
+function gauge(label, value01, { invert = false } = {}) {
+ // value01 in 0..1; invert means lower-is-better (concentration, snipe).
+ const measured = value01 != null;
+ const pct = measured ? Math.max(0, Math.min(100, value01 * 100)) : 0;
+ const good = invert ? 100 - pct : pct;
+ const tone = !measured ? 'muted' : good >= 66 ? 'good' : good >= 40 ? 'warn' : 'danger';
+ return el('div', { class: 'ld-gauge' }, [
+ el('div', { class: 'ld-gauge-head' }, [
+ el('span', { class: 'ld-gauge-label', text: label }),
+ el('span', { class: `ld-gauge-val ld-${tone}`, text: measured ? `${Math.round(pct)}%` : 'not measured' }),
+ ]),
+ el('div', { class: 'ld-gauge-track' }, [
+ el('div', { class: `ld-gauge-fill ld-fill-${tone}`, style: `width:${measured ? pct : 0}%` }),
+ ]),
+ ]);
+}
+
+function renderVerdict() {
+ const target = $('ld-verdict');
+ const intel = state.detail.intel;
+
+ if (!intel) {
+ section(
+ target,
+ 'Coin Intelligence',
+ el('div', { class: 'ld-empty' }, [
+ el('p', { class: 'ld-empty-title', text: 'Not yet observed by the Intelligence Engine.' }),
+ el('p', {
+ text:
+ state.network === 'devnet'
+ ? 'The engine watches mainnet launches. Devnet coins carry no intelligence signals.'
+ : 'This coin launched before the engine started watching, or its first seconds were not captured. New mainnet launches are scored within ~90 seconds.',
+ }),
+ el('a', { class: 'ld-btn ld-btn-ghost', href: '/radar', text: 'Open the live radar →' }),
+ ]),
+ { tag: 'engine' },
+ );
+ return;
+ }
+
+ const q = intel.quality_score;
+ const tone = scoreTone(q);
+ const headline = el('div', { class: 'ld-verdict-head' }, [
+ el('div', { class: `ld-quality ld-quality-${tone}` }, [
+ el('span', { class: 'ld-quality-num', text: q != null ? String(Math.round(q)) : '—' }),
+ el('span', { class: 'ld-quality-max', text: '/100' }),
+ ]),
+ el('div', { class: 'ld-verdict-copy' }, [
+ el('span', { class: 'ld-verdict-label', text: 'Quality score' }),
+ el('p', {
+ class: 'ld-narrative',
+ text:
+ intel.narrative ||
+ (q >= 70
+ ? 'Signals read organic: diverse buyers, healthy timing, no dominant whale.'
+ : q >= 45
+ ? 'Mixed signals — some concentration or coordination worth a closer look.'
+ : 'High-risk signals: coordination, concentration, or early sell pressure.'),
+ }),
+ ]),
+ ]);
+
+ const flags = (intel.risk_flags || []).length
+ ? el(
+ 'div',
+ { class: 'ld-flags' },
+ intel.risk_flags.map((f) => {
+ const m = FLAG_META[f] || { label: f.replace(/_/g, ' '), tone: 'warn', tip: '' };
+ return el('span', { class: `ld-flag ld-flag-${m.tone}`, title: m.tip, text: m.label });
+ }),
+ )
+ : el('div', { class: 'ld-flags' }, [
+ el('span', { class: 'ld-flag ld-flag-good', text: 'No risk flags raised' }),
+ ]);
+
+ const gauges = el('div', { class: 'ld-gauges' }, [
+ gauge('Organic', intel.organic_score),
+ gauge('Bundle coordination', intel.bundle_score, { invert: true }),
+ gauge('Sniped early', intel.snipe_ratio, { invert: true }),
+ gauge('Top-10 concentration', intel.concentration_top10, { invert: true }),
+ gauge('Fresh wallets', intel.fresh_wallet_ratio, { invert: true }),
+ gauge('Funder clustering', intel.bubblemap_connectivity, { invert: true }),
+ ]);
+
+ // First-seconds aggregates — the raw observed activity behind the scores.
+ const kv = (label, value) =>
+ value == null
+ ? null
+ : el('div', { class: 'ld-kv' }, [el('span', { text: label }), el('b', { text: value })]);
+ const aggregates = el('div', { class: 'ld-aggregates' }, [
+ kv('Buys', intel.buy_count != null ? compact(intel.buy_count) : null),
+ kv('Sells', intel.sell_count != null ? compact(intel.sell_count) : null),
+ kv('Unique buyers', intel.unique_buyers != null ? compact(intel.unique_buyers) : null),
+ kv('Buy volume', intel.buy_volume_sol != null ? fmtSol(intel.buy_volume_sol, { sign: false }) : null),
+ kv('Dev buy', intel.dev_buy_sol != null ? fmtSol(intel.dev_buy_sol, { sign: false }) : null),
+ kv('Largest buy', intel.largest_buy_sol != null ? fmtSol(intel.largest_buy_sol, { sign: false }) : null),
+ kv('Observed for', intel.observation_seconds != null ? `${intel.observation_seconds}s` : null),
+ ]);
+
+ const body = el('div', { class: 'ld-verdict' }, [headline, flags, gauges, aggregates]);
+ section(target, 'Coin Intelligence', body, { tag: 'first ~90s, on-chain' });
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// PRICE CHART
+// ════════════════════════════════════════════════════════════════════════════
+
+const INTERVALS = [
+ ['5m', '5m'],
+ ['15m', '15m'],
+ ['1H', '1h'],
+ ['4H', '4h'],
+ ['1D', '1d'],
+];
+const WINDOW_HOURS = { '5m': 12, '15m': 36, '1h': 96, '4h': 480, '1d': 2160 };
+
+function areaChart(points) {
+ // points: [{t,o,h,l,c,v}] ascending. Pure SVG, theme-aware via currentColor.
+ const w = 720;
+ const h = 240;
+ const pad = { t: 14, r: 8, b: 18, l: 8 };
+ const closes = points.map((p) => p.c);
+ const min = Math.min(...closes);
+ const max = Math.max(...closes);
+ const span = max - min || max || 1;
+ const innerW = w - pad.l - pad.r;
+ const innerH = h - pad.t - pad.b;
+ const x = (i) => pad.l + (i / Math.max(1, points.length - 1)) * innerW;
+ const y = (v) => pad.t + innerH - ((v - min) / span) * innerH;
+
+ const up = points.length > 1 && closes[closes.length - 1] >= closes[0];
+ const line = points.map((p, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)} ${y(p.c).toFixed(1)}`).join(' ');
+ const area = `${line} L${x(points.length - 1).toFixed(1)} ${(h - pad.b).toFixed(1)} L${x(0).toFixed(1)} ${(h - pad.b).toFixed(1)} Z`;
+
+ const node = svg('svg', { viewBox: `0 0 ${w} ${h}`, class: `ld-chart-svg ${up ? 'ld-chart-up' : 'ld-chart-down'}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': 'Price history' });
+ const gradId = 'ldchartgrad';
+ const defs = svg('defs', {});
+ const grad = svg('linearGradient', { id: gradId, x1: '0', y1: '0', x2: '0', y2: '1' });
+ grad.append(
+ svg('stop', { offset: '0%', 'stop-color': 'currentColor', 'stop-opacity': '0.28' }),
+ svg('stop', { offset: '100%', 'stop-color': 'currentColor', 'stop-opacity': '0' }),
+ );
+ defs.append(grad);
+ node.append(
+ defs,
+ svg('path', { d: area, fill: `url(#${gradId})`, stroke: 'none' }),
+ svg('path', { d: line, fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linejoin': 'round', 'stroke-linecap': 'round' }),
+ );
+ return node;
+}
+
+function chartIntervalBar() {
+ return el(
+ 'div',
+ { class: 'ld-chart-bar', role: 'tablist', 'aria-label': 'Chart interval' },
+ INTERVALS.map(([label, value]) =>
+ el('button', {
+ class: `ld-int-btn${state.chartInterval === value ? ' active' : ''}`,
+ type: 'button',
+ role: 'tab',
+ 'aria-selected': String(state.chartInterval === value),
+ text: label,
+ onclick: () => {
+ if (state.chartInterval === value) return;
+ state.chartInterval = value;
+ renderChart();
+ },
+ }),
+ ),
+ );
+}
+
+async function renderChart() {
+ const target = $('ld-chart');
+ if (state.network !== 'mainnet') {
+ section(target, 'Price', el('div', { class: 'ld-empty' }, [el('p', { text: 'No price history for devnet coins.' })]));
+ return;
+ }
+ const bar = chartIntervalBar();
+ const canvas = el('div', { class: 'ld-chart-canvas' }, [el('div', { class: 'ld-skel ld-skel-chart' })]);
+ section(target, 'Price', el('div', { class: 'ld-chart' }, [bar, canvas]), { tag: 'Birdeye OHLCV' });
+
+ const interval = state.chartInterval;
+ const to = Math.floor(Date.now() / 1000);
+ const from = to - (WINDOW_HOURS[interval] || 36) * 3600;
+ try {
+ const body = await fetchJson(
+ `/api/pump/price-history?mint=${encodeURIComponent(state.mint)}&interval=${interval}&from=${from}&to=${to}`,
+ );
+ const pts = (body.data || []).filter((p) => Number.isFinite(p.c));
+ if (pts.length < 2) {
+ canvas.replaceChildren(el('div', { class: 'ld-empty ld-empty-sm' }, [el('p', { text: 'Not enough trade history at this interval yet.' })]));
+ return;
+ }
+ const first = pts[0].c;
+ const last = pts[pts.length - 1].c;
+ const changePct = first ? ((last - first) / first) * 100 : 0;
+ const head = el('div', { class: 'ld-chart-readout' }, [
+ el('span', { class: 'ld-chart-price', text: fmtPrice(last) }),
+ el('span', { class: `ld-chart-change ${pnlClass(changePct)}`, text: fmtPct(changePct, { sign: true }) }),
+ ]);
+ canvas.replaceChildren(head, areaChart(pts));
+ } catch {
+ canvas.replaceChildren(
+ el('div', { class: 'ld-empty ld-empty-sm' }, [
+ el('p', { text: 'Price history is unavailable right now.' }),
+ el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Retry', onclick: () => renderChart() }),
+ ]),
+ );
+ }
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// HOLDER DISTRIBUTION
+// ════════════════════════════════════════════════════════════════════════════
+
+async function renderDistribution() {
+ const target = $('ld-distribution');
+ const intel = state.detail.intel;
+
+ let overview = null;
+ try {
+ overview = await fetchJson(`/api/coin/${encodeURIComponent(state.mint)}/cohorts`);
+ } catch {
+ /* not an indexed agent token — fall back to intel concentration below */
+ }
+
+ const rows = [];
+ let holderCount = overview?.holderCount ?? null;
+ let top1 = overview?.concentration?.top1Share ?? null;
+ let top10 = overview?.concentration?.top10Share ?? (intel?.concentration_top10 ?? null);
+ const label = overview?.concentration?.label || null;
+
+ if (holderCount == null && top10 == null) {
+ section(
+ target,
+ 'Holders',
+ el('div', { class: 'ld-empty ld-empty-sm' }, [
+ el('p', { text: 'Holder distribution is not indexed for this coin yet.' }),
+ ]),
+ );
+ return;
+ }
+
+ const metric = (k, v, tone = '') =>
+ el('div', { class: 'ld-metric' }, [
+ el('span', { class: 'ld-metric-label', text: k }),
+ el('span', { class: `ld-metric-val ${tone}`, text: v }),
+ ]);
+
+ const concTone = top10 == null ? '' : top10 > 0.5 ? 'ld-danger' : top10 > 0.3 ? 'ld-warn' : 'ld-good';
+ const metrics = el('div', { class: 'ld-metrics' }, [
+ holderCount != null ? metric('Holders', compact(holderCount)) : null,
+ top1 != null ? metric('Top holder', pctText(top1)) : null,
+ top10 != null ? metric('Top 10', pctText(top10), concTone) : null,
+ label ? metric('Spread', label) : null,
+ ]);
+
+ // Concentration bar — top10 vs the rest.
+ let bar = null;
+ if (top10 != null) {
+ const t10 = Math.max(0, Math.min(100, top10 * 100));
+ bar = el('div', { class: 'ld-conc' }, [
+ el('div', { class: 'ld-conc-track', title: `Top 10 wallets hold ${Math.round(t10)}%` }, [
+ el('div', { class: `ld-conc-top ${concTone}`, style: `width:${t10}%` }),
+ ]),
+ el('div', { class: 'ld-conc-legend' }, [
+ el('span', { text: `Top 10 · ${Math.round(t10)}%` }),
+ el('span', { text: `Everyone else · ${Math.round(100 - t10)}%` }),
+ ]),
+ ]);
+ }
+
+ const cohorts = (overview?.cohorts || []).filter((c) => c.count != null && c.count > 0);
+ const cohortChips = cohorts.length
+ ? el(
+ 'div',
+ { class: 'ld-cohorts' },
+ cohorts.map((c) =>
+ el('span', { class: 'ld-cohort', title: c.description || '' }, [
+ el('b', { text: compact(c.count) }),
+ el('span', { text: c.name }),
+ ]),
+ ),
+ )
+ : null;
+
+ section(target, 'Holders', el('div', { class: 'ld-dist' }, [metrics, bar, cohortChips]), {
+ tag: overview?.source === 'live' ? 'live · Helius' : overview ? 'snapshot' : 'engine',
+ });
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// BUYBACK / BURN ECONOMICS
+// ════════════════════════════════════════════════════════════════════════════
+
+function renderEconomics() {
+ const target = $('ld-economics');
+ const econ = state.detail.economics;
+ const reg = state.detail.registry;
+ const buybackBps = Number(reg?.buyback_bps || 0);
+
+ if (!state.detail.found) {
+ target.hidden = true;
+ return;
+ }
+
+ if (buybackBps <= 0 && (!econ || econ.confirmed_payments === 0)) {
+ section(
+ target,
+ 'Economics',
+ el('div', { class: 'ld-empty ld-empty-sm' }, [
+ el('p', { text: 'This launch has no buyback-and-burn loop configured.' }),
+ el('a', { class: 'ld-btn ld-btn-ghost', href: '/launchpad', text: 'How buyback coins work →' }),
+ ]),
+ );
+ return;
+ }
+
+ const burned = Number(econ?.burns?.total_burned || 0);
+ const metric = (k, v, sub = null) =>
+ el('div', { class: 'ld-econ-metric' }, [
+ el('span', { class: 'ld-econ-val', text: v }),
+ el('span', { class: 'ld-econ-label', text: k }),
+ sub ? el('span', { class: 'ld-econ-sub', text: sub }) : null,
+ ]);
+
+ const body = el('div', { class: 'ld-econ' }, [
+ el('p', { class: 'ld-econ-lede', text: `Every agent payment routes ${(buybackBps / 100).toFixed(1)}% into an automated buyback that burns supply — paying users fund a deflationary loop.` }),
+ el('div', { class: 'ld-econ-grid' }, [
+ metric('Buyback rate', `${(buybackBps / 100).toFixed(1)}%`),
+ metric('Paid calls', compact(econ?.confirmed_payments || 0), `${compact(econ?.unique_payers || 0)} payers`),
+ metric('Burn runs', compact(econ?.burns?.runs || 0)),
+ burned > 0 ? metric('Supply burned', compact(burned / 1e6)) : null,
+ ]),
+ ]);
+
+ // Recent burn proofs — each links to its Solana transaction.
+ const feed = (econ?.burns_feed || []).slice(0, 5);
+ if (feed.length) {
+ body.appendChild(
+ el('div', { class: 'ld-burn-feed' }, [
+ el('span', { class: 'ld-burn-feed-title', text: 'Recent burns' }),
+ ...feed.map((b) =>
+ el('a', {
+ class: 'ld-burn-row',
+ href: b.tx_signature ? `https://solscan.io/tx/${b.tx_signature}` : '#',
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ }, [
+ el('span', { class: 'ld-burn-amt', text: `🔥 ${compact(Number(b.burn_amount || 0) / 1e6)}` }),
+ el('span', { class: 'ld-burn-time', text: relTime(b.created_at) }),
+ el('span', { class: 'ld-burn-link', text: 'tx ↗' }),
+ ]),
+ ),
+ ]),
+ );
+ }
+
+ section(target, 'Economics', body, { tag: 'on-chain' });
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// AGENT BEHIND THE COIN
+// ════════════════════════════════════════════════════════════════════════════
+
+function renderAgent() {
+ const target = $('ld-agent');
+ const agent = state.detail.agent;
+ const trader = state.detail.trader;
+
+ if (!agent) {
+ target.hidden = true;
+ return;
+ }
+
+ const avatar = agent.avatar_thumbnail_url
+ ? el('img', { class: 'ld-agent-avatar', src: agent.avatar_thumbnail_url, alt: '', loading: 'lazy' })
+ : el('span', { class: 'ld-agent-avatar ld-agent-avatar-fallback', text: (agent.name || '?')[0].toUpperCase() });
+
+ const head = el('a', { class: 'ld-agent-head', href: agent.url, 'aria-label': `View agent ${agent.name}` }, [
+ avatar,
+ el('div', { class: 'ld-agent-id' }, [
+ el('span', { class: 'ld-agent-name', text: agent.name || 'Agent' }),
+ el('span', { class: 'ld-agent-role', text: 'Launching agent' }),
+ ]),
+ el('span', { class: 'ld-agent-go', text: '→' }),
+ ]);
+
+ const body = el('div', { class: 'ld-agent-body' }, [head]);
+
+ if (agent.description) {
+ body.appendChild(el('p', { class: 'ld-agent-desc', text: agent.description }));
+ }
+
+ if (trader) {
+ const tone = scoreTone(trader.score);
+ const scoreEl = el('div', { class: 'ld-trader' }, [
+ el('div', { class: `ld-trader-score ld-quality-${tone}` }, [
+ el('span', { class: 'ld-trader-num', text: trader.score != null ? String(Math.round(trader.score)) : '—' }),
+ el('span', { class: 'ld-trader-max', text: 'TraderScore' }),
+ ]),
+ el('div', { class: 'ld-trader-stats' }, [
+ trader.verified ? el('span', { class: 'ld-verified', html: verifiedBadge(true) }) : null,
+ el('div', { class: 'ld-trader-row' }, [
+ el('span', { class: 'ld-tl', text: 'Realized P&L' }),
+ el('span', { class: `ld-tv ${pnlClass(trader.realized_pnl_sol)}`, text: fmtSol(trader.realized_pnl_sol) }),
+ ]),
+ el('div', { class: 'ld-trader-row' }, [
+ el('span', { class: 'ld-tl', text: 'Win rate' }),
+ el('span', { class: 'ld-tv', text: trader.win_rate != null ? fmtPct(trader.win_rate * 100) : '—' }),
+ ]),
+ el('div', { class: 'ld-trader-row' }, [
+ el('span', { class: 'ld-tl', text: 'Closed trades' }),
+ el('span', { class: 'ld-tv', text: compact(trader.closed_count || 0) }),
+ ]),
+ ]),
+ ]);
+ body.appendChild(scoreEl);
+ body.appendChild(
+ el('a', { class: 'ld-btn ld-btn-ghost ld-btn-block', href: `/trader/${agent.id}`, text: 'Full track record →' }),
+ );
+ } else {
+ body.appendChild(
+ el('p', { class: 'ld-agent-note', text: 'No public trading track record yet for this agent.' }),
+ );
+ }
+
+ section(target, 'The agent', body);
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// LIVE TRADE TAPE (SSE with a polling fallback)
+// ════════════════════════════════════════════════════════════════════════════
+
+function tapeRow(t) {
+ const isBuy = t.is_buy ?? (String(t.txType || t.type || '').toLowerCase() === 'buy');
+ const sol = Number(t.sol_amount ?? (t.lamports != null ? t.lamports / 1e9 : t.solAmount));
+ const who = t.user || t.buyer || t.seller || t.traderPublicKey || null;
+ return el('div', { class: `ld-trade ${isBuy ? 'ld-buy' : 'ld-sell'}` }, [
+ el('span', { class: 'ld-trade-side', text: isBuy ? 'BUY' : 'SELL' }),
+ el('span', { class: 'ld-trade-amt', text: Number.isFinite(sol) ? fmtSol(sol, { sign: false }) : '—' }),
+ el('span', { class: 'ld-trade-who', text: who ? shortAddr(who) : '' }),
+ ]);
+}
+
+function pushTrade(listEl, t) {
+ const row = tapeRow(t);
+ if (!REDUCED_MOTION) row.classList.add('ld-trade-in');
+ listEl.insertBefore(row, listEl.firstChild);
+ while (listEl.children.length > 24) listEl.removeChild(listEl.lastChild);
+}
+
+async function seedTape(listEl) {
+ try {
+ const body = await fetchJson(`/api/pump/coin-trades?mint=${encodeURIComponent(state.mint)}&limit=20`);
+ const trades = body.trades || [];
+ if (!trades.length) {
+ listEl.appendChild(el('div', { class: 'ld-tape-empty', text: 'Waiting for the next trade…' }));
+ return;
+ }
+ trades.forEach((t) => listEl.appendChild(tapeRow(t)));
+ } catch {
+ listEl.appendChild(el('div', { class: 'ld-tape-empty', text: 'Trade feed is quiet right now.' }));
+ }
+}
+
+function startTape(listEl, dot) {
+ // Live SSE stream caps at 90s server-side; reconnect transparently so the
+ // tape stays live for as long as the page is open and visible.
+ let es = null;
+ let pollTimer = 0;
+ let closed = false;
+
+ const setLive = (live) => {
+ dot.classList.toggle('ld-live-on', live);
+ dot.title = live ? 'Live' : 'Reconnecting…';
+ };
+
+ const connect = () => {
+ if (closed || document.hidden) return;
+ try {
+ es = new EventSource(`/api/pump/trades-stream?mint=${encodeURIComponent(state.mint)}`);
+ } catch {
+ startPolling();
+ return;
+ }
+ const onTrade = (e) => {
+ setLive(true);
+ try {
+ const d = JSON.parse(e.data);
+ if (d && (d.mint === state.mint || !d.mint)) {
+ const empty = listEl.querySelector('.ld-tape-empty');
+ if (empty) empty.remove();
+ pushTrade(listEl, d);
+ }
+ } catch {
+ /* ignore malformed frame */
+ }
+ };
+ es.addEventListener('open', () => setLive(true));
+ es.addEventListener('buy', onTrade);
+ es.addEventListener('sell', onTrade);
+ es.addEventListener('trade', onTrade);
+ es.addEventListener('close', () => {
+ es?.close();
+ if (!closed) setTimeout(connect, 600); // server hit its duration cap — reconnect
+ });
+ es.onerror = () => {
+ setLive(false);
+ es?.close();
+ if (!closed) setTimeout(connect, 2500);
+ };
+ };
+
+ const startPolling = () => {
+ // Last-resort fallback if EventSource is unavailable.
+ setLive(false);
+ const seen = new Set();
+ const tick = async () => {
+ if (closed || document.hidden) return;
+ try {
+ const body = await fetchJson(`/api/pump/coin-trades?mint=${encodeURIComponent(state.mint)}&limit=10`);
+ for (const t of (body.trades || []).reverse()) {
+ if (t.tx && !seen.has(t.tx)) {
+ seen.add(t.tx);
+ const empty = listEl.querySelector('.ld-tape-empty');
+ if (empty) empty.remove();
+ pushTrade(listEl, t);
+ }
+ }
+ } catch {
+ /* keep polling */
+ }
+ };
+ pollTimer = setInterval(tick, 5000);
+ };
+
+ if ('EventSource' in window) connect();
+ else startPolling();
+
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) {
+ es?.close();
+ clearInterval(pollTimer);
+ } else if (!closed) {
+ if ('EventSource' in window) connect();
+ }
+ });
+
+ return {
+ destroy() {
+ closed = true;
+ es?.close();
+ clearInterval(pollTimer);
+ },
+ };
+}
+
+async function renderTape() {
+ const target = $('ld-tape');
+ if (state.network !== 'mainnet') {
+ target.hidden = true;
+ return;
+ }
+ const dot = el('span', { class: 'ld-live-dot', 'aria-hidden': 'true' });
+ const list = el('div', { class: 'ld-tape-list' });
+ const head = el('div', { class: 'ld-sec-head' }, [
+ el('h2', { class: 'ld-sec-title' }, [el('span', { text: 'Live trades' }), dot]),
+ ]);
+ target.replaceChildren(head, list);
+ target.classList.add('ld-revealed');
+
+ await seedTape(list);
+ state.tape = startTape(list, dot);
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// COMMUNITY
+// ════════════════════════════════════════════════════════════════════════════
+
+function renderCommunity() {
+ const target = $('ld-community');
+ if (state.network !== 'mainnet') {
+ target.hidden = true;
+ return;
+ }
+ const symbol = (state.coin?.symbol || state.detail.registry?.symbol || '').toUpperCase();
+ const body = el('div', { class: 'ld-community' }, [
+ el('p', { text: `Every coin gets a live chat and a walkable 3D world. Meet the holders of ${symbol ? `$${symbol}` : 'this coin'}.` }),
+ el('div', { class: 'ld-community-ctas' }, [
+ el('a', { class: 'ld-btn ld-btn-ghost', href: `/communities/${state.mint}`, text: 'Open chat & world →' }),
+ ]),
+ ]);
+ section(target, 'Community', body);
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// ACTIONS (buy / 3D / watch / share)
+// ════════════════════════════════════════════════════════════════════════════
+
+const WATCH_KEY = 'ld_watchlist';
+
+function readWatchlist() {
+ try {
+ return JSON.parse(localStorage.getItem(WATCH_KEY) || '[]');
+ } catch {
+ return [];
+ }
+}
+
+function isWatched() {
+ return readWatchlist().includes(state.mint);
+}
+
+function toggleWatch(btn) {
+ const list = readWatchlist();
+ const i = list.indexOf(state.mint);
+ if (i >= 0) list.splice(i, 1);
+ else list.unshift(state.mint);
+ try {
+ localStorage.setItem(WATCH_KEY, JSON.stringify(list.slice(0, 200)));
+ } catch {
+ /* storage full / blocked — non-fatal */
+ }
+ paintWatch(btn);
+}
+
+function paintWatch(btn) {
+ const on = isWatched();
+ btn.classList.toggle('ld-watch-on', on);
+ btn.setAttribute('aria-pressed', String(on));
+ btn.replaceChildren(
+ el('span', { text: on ? '★' : '☆' }),
+ el('span', { text: on ? 'Watching' : 'Watch' }),
+ );
+}
+
+function renderActions() {
+ const target = $('ld-actions');
+ const isDevnet = state.network === 'devnet';
+ const symbol = (state.coin?.symbol || state.detail.registry?.symbol || '').toUpperCase();
+
+ const tradeHref = isDevnet
+ ? `https://explorer.solana.com/address/${state.mint}?cluster=devnet`
+ : `https://pump.fun/${state.mint}`;
+
+ const watchBtn = el('button', { class: 'ld-btn ld-watch', type: 'button', 'aria-pressed': 'false' });
+ paintWatch(watchBtn);
+ watchBtn.addEventListener('click', () => toggleWatch(watchBtn));
+
+ const shareBtn = el('button', {
+ class: 'ld-btn ld-btn-ghost',
+ type: 'button',
+ text: 'Share',
+ onclick: async (e) => {
+ const url = `${location.origin}/launches/${state.mint}`;
+ const title = `${symbol ? `$${symbol}` : 'This coin'} on three.ws`;
+ if (navigator.share) {
+ try {
+ await navigator.share({ title, url });
+ return;
+ } catch {
+ /* user cancelled or unsupported — fall through to copy */
+ }
+ }
+ try {
+ await navigator.clipboard.writeText(url);
+ const btn = e.currentTarget;
+ const old = btn.textContent;
+ btn.textContent = 'Link copied';
+ setTimeout(() => (btn.textContent = old), 1400);
+ } catch {
+ window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(url)}`, '_blank', 'noopener');
+ }
+ },
+ });
+
+ const buttons = [
+ el('a', { class: 'ld-btn ld-btn-primary', href: tradeHref, target: '_blank', rel: 'noopener noreferrer', text: isDevnet ? 'View on explorer ↗' : `Trade ${symbol ? `$${symbol}` : 'coin'} ↗` }),
+ ];
+ if (!isDevnet) {
+ buttons.push(el('a', { class: 'ld-btn ld-btn-ghost', href: `/coin3d?mint=${encodeURIComponent(state.mint)}`, text: 'View in 3D' }));
+ }
+ buttons.push(watchBtn, shareBtn);
+
+ const body = el('div', { class: 'ld-action-grid' }, buttons);
+ section(target, 'Take action', body);
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// AMBIENT FIELD (shared visual language with /launches)
+// ════════════════════════════════════════════════════════════════════════════
+
+function startParticleField() {
+ const canvas = $('ld-field');
+ if (!canvas) return;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+ let width = 0;
+ let height = 0;
+ let particles = [];
+ let inkRGB = '232,232,232';
+ let raf = 0;
+
+ const readInk = () => {
+ const scheme = getComputedStyle(document.documentElement).getPropertyValue('color-scheme');
+ inkRGB = scheme.includes('light') ? '20,24,34' : '232,232,232';
+ };
+ const resize = () => {
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
+ width = window.innerWidth;
+ height = window.innerHeight;
+ canvas.width = width * dpr;
+ canvas.height = height * dpr;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ const target = Math.min(70, Math.floor((width * height) / 30000));
+ particles = Array.from({ length: target }, () => ({
+ x: Math.random() * width,
+ y: Math.random() * height,
+ vx: (Math.random() - 0.5) * 0.1,
+ vy: (Math.random() - 0.5) * 0.1,
+ r: 0.6 + Math.random() * 1,
+ }));
+ };
+ const draw = () => {
+ ctx.clearRect(0, 0, width, height);
+ for (const p of particles) {
+ p.x += p.vx;
+ p.y += p.vy;
+ if (p.x < -10) p.x = width + 10;
+ if (p.x > width + 10) p.x = -10;
+ if (p.y < -10) p.y = height + 10;
+ if (p.y > height + 10) p.y = -10;
+ ctx.beginPath();
+ ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
+ ctx.fillStyle = `rgba(${inkRGB},0.14)`;
+ ctx.fill();
+ }
+ for (let i = 0; i < particles.length; i++) {
+ for (let j = i + 1; j < particles.length; j++) {
+ const a = particles[i];
+ const b = particles[j];
+ const dx = a.x - b.x;
+ const dy = a.y - b.y;
+ const d2 = dx * dx + dy * dy;
+ if (d2 < 12100) {
+ const alpha = 0.045 * (1 - Math.sqrt(d2) / 110);
+ ctx.beginPath();
+ ctx.moveTo(a.x, a.y);
+ ctx.lineTo(b.x, b.y);
+ ctx.strokeStyle = `rgba(${inkRGB},${alpha.toFixed(3)})`;
+ ctx.lineWidth = 0.6;
+ ctx.stroke();
+ }
+ }
+ }
+ };
+ const loop = () => {
+ draw();
+ raf = requestAnimationFrame(loop);
+ };
+ readInk();
+ resize();
+ window.addEventListener('resize', resize, { passive: true });
+ new MutationObserver(readInk).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
+ if (REDUCED_MOTION) {
+ draw();
+ return;
+ }
+ loop();
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) cancelAnimationFrame(raf);
+ else loop();
+ });
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// STATES
+// ════════════════════════════════════════════════════════════════════════════
+
+function renderSkeleton() {
+ $('ld-hero').replaceChildren(
+ el('div', { class: 'ld-hero-top' }, [
+ el('div', { class: 'ld-skel ld-skel-avatar' }),
+ el('div', { class: 'ld-skel-stack' }, [
+ el('div', { class: 'ld-skel', style: 'width:55%;height:26px' }),
+ el('div', { class: 'ld-skel', style: 'width:35%;height:16px' }),
+ ]),
+ ]),
+ el('div', { class: 'ld-hero-stats' }, Array.from({ length: 4 }, () => el('div', { class: 'ld-skel', style: 'height:46px' }))),
+ );
+ for (const id of ['ld-verdict', 'ld-chart', 'ld-agent']) {
+ $(id).replaceChildren(el('div', { class: 'ld-skel', style: 'height:120px' }));
+ }
+}
+
+function renderFatal(message) {
+ const shell = $('ld-shell');
+ shell.setAttribute('aria-busy', 'false');
+ shell.querySelectorAll('.ld-section, .ld-hero, .ld-body').forEach((n) => (n.hidden = true));
+ $('ld-state').replaceChildren(
+ el('div', { class: 'ld-fatal' }, [
+ el('h1', { text: message.title }),
+ el('p', { text: message.body }),
+ el('div', { class: 'ld-fatal-ctas' }, [
+ el('a', { class: 'ld-btn ld-btn-primary', href: '/launches', text: 'Browse all launches' }),
+ message.retry ? el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Retry', onclick: () => location.reload() }) : null,
+ ]),
+ ]),
+ );
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+// BOOT
+// ════════════════════════════════════════════════════════════════════════════
+
+async function boot() {
+ startParticleField();
+
+ state.mint = resolveMint();
+ if (!state.mint) {
+ renderFatal({
+ title: 'No coin selected',
+ body: 'This page needs a Solana mint address. Pick a coin from the launch feed to see its full profile.',
+ });
+ return;
+ }
+
+ renderSkeleton();
+
+ let detail;
+ try {
+ detail = await loadDetail();
+ } catch {
+ renderFatal({
+ title: "Couldn't load this coin",
+ body: 'The launch API did not respond. Check your connection and try again.',
+ retry: true,
+ });
+ return;
+ }
+ state.detail = detail;
+ state.coin = await loadCoin();
+
+ $('ld-shell').setAttribute('aria-busy', 'false');
+
+ // Paint everything. Each section owns its own empty/error state, so one
+ // missing data source never blanks the page.
+ renderHero();
+ renderVerdict();
+ renderChart();
+ renderDistribution();
+ renderEconomics();
+ renderAgent();
+ renderTape();
+ renderCommunity();
+ renderActions();
+
+ // Refresh the live market every 30s so price / mcap / graduation stay fresh.
+ state.priceTimer = setInterval(async () => {
+ if (document.hidden) return;
+ const fresh = await loadCoin();
+ if (fresh) {
+ state.coin = fresh;
+ renderHero();
+ }
+ }, 30_000);
+}
+
+window.addEventListener('beforeunload', () => {
+ state.tape?.destroy?.();
+ clearInterval(state.priceTimer);
+});
+
+boot();
diff --git a/src/launches.css b/src/launches.css
index 3c7cc5af7..504901345 100644
--- a/src/launches.css
+++ b/src/launches.css
@@ -519,6 +519,27 @@ body {
transform: none;
}
+/* Whole-card link to the coin's rich profile. Sits above the cursor-light
+ layer but below the genuinely-interactive children (agent chip, external
+ actions), which are raised in turn so they keep their own click targets. */
+.lx-card-link {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ border-radius: inherit;
+ cursor: pointer;
+}
+.lx-card-link:focus-visible {
+ outline: var(--focus-ring-width) solid var(--focus-ring-color);
+ outline-offset: -2px;
+}
+.lx-card .lx-agent-row,
+.lx-card .lx-card-actions,
+.lx-card .lx-mint {
+ position: relative;
+ z-index: 2;
+}
+
.lx-card::before {
content: '';
position: absolute;
diff --git a/src/launches.js b/src/launches.js
index 20171a058..5df15c96d 100644
--- a/src/launches.js
+++ b/src/launches.js
@@ -428,7 +428,17 @@ function launchCard(launch, index, { featured = false } = {}) {
);
}
+ // Whole-card stretched link to the coin's rich profile. Interactive children
+ // (agent chip, external actions) are raised above it in CSS so they keep
+ // their own targets; everything else opens the on-platform detail page.
+ const cardLink = el('a', {
+ class: 'lx-card-link',
+ href: isDevnet ? `/launches/${launch.mint}?network=devnet` : `/launches/${launch.mint}`,
+ 'aria-label': `Open ${launch.symbol ? `$${launch.symbol}` : launch.name || 'coin'} profile`,
+ });
+
const card = el('article', { class: `lx-card${featured ? ' lx-card-featured' : ''}` }, [
+ cardLink,
featured ? el('span', { class: 'lx-feat-tag', text: 'Latest' }) : null,
featured && launch.symbol
? el('span', { class: 'lx-feat-ghost', 'aria-hidden': 'true', text: `$${launch.symbol}` })
diff --git a/src/oracle.js b/src/oracle.js
new file mode 100644
index 000000000..572678a15
--- /dev/null
+++ b/src/oracle.js
@@ -0,0 +1,544 @@
+// Oracle — the fused pump.fun conviction war room.
+//
+// Reads /api/oracle/* (feed, coin, wallet, stream, watch). Every surface
+// degrades gracefully: if the backend isn't reachable yet (it deploys with the
+// migration), the page shows an honest "warming up" state instead of breaking.
+//
+// Views: live conviction feed (with SSE), wallet reputation leaderboard,
+// conviction-tier edge backtest, and the agent action-loop arm panel.
+
+const NETWORK = 'mainnet';
+const $ = (s, r = document) => r.querySelector(s);
+const $$ = (s, r = document) => [...r.querySelectorAll(s)];
+
+// ── tiny helpers ─────────────────────────────────────────────────────────────
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const shortAddr = (a) => (a && a.length > 10 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '');
+const fmtSol = (n) => (n == null ? '—' : `${Number(n) < 0.01 && Number(n) > 0 ? Number(n).toFixed(4) : Number(n).toFixed(2)}◎`);
+const fmtPct = (n) => (n == null ? '—' : `${Math.round(Number(n))}%`);
+const tierClass = (t) => `t-${t || 'avoid'}`;
+const tierPill = (t) => `tp-${t || 'avoid'}`;
+function ago(ts) {
+ if (!ts) return '—';
+ const s = Math.max(0, (Date.now() - new Date(ts).getTime()) / 1000);
+ if (s < 60) return `${Math.floor(s)}s`;
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
+ if (s < 86400) return `${Math.floor(s / 3600)}h`;
+ return `${Math.floor(s / 86400)}d`;
+}
+function solscan(addr) { return `https://solscan.io/account/${addr}`; }
+function pumpUrl(mint) { return `https://pump.fun/coin/${mint}`; }
+
+const CATEGORIES = ['meme', 'tech', 'ai', 'culture', 'community', 'political', 'news', 'animal', 'celebrity', 'utility', 'unknown'];
+const ARCH_TITLE = {
+ smart_money: 'Smart Money', sniper: 'Sniper', dumper: 'Dumper', rugger: 'Rugger',
+ fresh: 'Fresh', neutral: 'Neutral', unproven: 'Unproven',
+};
+
+async function api(path, opts = {}) {
+ const ctrl = new AbortController();
+ const to = setTimeout(() => ctrl.abort(), opts.timeout || 12000);
+ try {
+ const res = await fetch(path, { credentials: 'include', signal: ctrl.signal, ...opts });
+ const data = await res.json().catch(() => null);
+ return { ok: res.ok, status: res.status, data };
+ } catch {
+ return { ok: false, status: 0, data: null };
+ } finally {
+ clearTimeout(to);
+ }
+}
+
+// ── state ────────────────────────────────────────────────────────────────────
+const state = {
+ view: 'feed',
+ tier: '',
+ category: '',
+ minScore: 0,
+ label: '',
+ feed: new Map(), // mint -> item, preserves SSE + initial load
+ es: null,
+ agents: [],
+ agentId: null,
+ watch: null,
+};
+
+// ── boot ─────────────────────────────────────────────────────────────────────
+function boot() {
+ // populate category filter
+ const catSel = $('#catSel');
+ for (const c of CATEGORIES) {
+ const o = document.createElement('option');
+ o.value = c; o.textContent = c[0].toUpperCase() + c.slice(1);
+ catSel.appendChild(o);
+ }
+
+ // tabs
+ $$('.tab').forEach((t) => t.addEventListener('click', () => switchView(t.dataset.view)));
+ // filters
+ $('#tierSeg').addEventListener('click', (e) => {
+ const b = e.target.closest('button'); if (!b) return;
+ $$('#tierSeg button').forEach((x) => x.classList.toggle('on', x === b));
+ state.tier = b.dataset.tier; loadFeed();
+ });
+ $('#catSel').addEventListener('change', (e) => { state.category = e.target.value; loadFeed(); });
+ $('#minSel').addEventListener('change', (e) => { state.minScore = Number(e.target.value) || 0; loadFeed(); });
+ $('#labelSeg').addEventListener('click', (e) => {
+ const b = e.target.closest('button'); if (!b) return;
+ $$('#labelSeg button').forEach((x) => x.classList.toggle('on', x === b));
+ state.label = b.dataset.label; loadWallets();
+ });
+ // drawer close
+ $$('#drawer [data-close]').forEach((el) => el.addEventListener('click', closeDrawer));
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeDrawer(); });
+
+ loadFeed();
+ openStream();
+}
+
+function switchView(view) {
+ state.view = view;
+ $$('.tab').forEach((t) => t.classList.toggle('on', t.dataset.view === view));
+ $$('.view').forEach((v) => v.classList.toggle('on', v.id === `view-${view}`));
+ if (view === 'wallets' && !$('#walletWrap').dataset.loaded) loadWallets();
+ if (view === 'edge' && !$('#edgeWrap').dataset.loaded) loadEdge();
+ if (view === 'agent' && !$('#armBody').dataset.loaded) loadAgentPanel();
+}
+
+// ── feed ─────────────────────────────────────────────────────────────────────
+function feedSkeletons() {
+ $('#feedGrid').innerHTML = Array.from({ length: 6 }, () => '<div class="skel"></div>').join('');
+}
+
+async function loadFeed() {
+ feedSkeletons();
+ const q = new URLSearchParams({ network: NETWORK, limit: '60' });
+ if (state.tier) q.set('tier', state.tier);
+ if (state.category) q.set('category', state.category);
+ if (state.minScore) q.set('min_score', String(state.minScore));
+ const { ok, data } = await api(`/api/oracle/feed?${q}`);
+
+ if (!ok || !data) return renderFeedEmpty('warming');
+ state.feed = new Map((data.items || []).map((it) => [it.mint, it]));
+ setStats(data);
+ renderFeed();
+ if (Array.isArray(data.backtest)) cacheBacktest(data.backtest);
+}
+
+function renderFeed() {
+ const items = [...state.feed.values()].sort((a, b) => b.score - a.score);
+ $('#ctFeed').textContent = items.length ? items.length : '';
+ if (!items.length) return renderFeedEmpty('empty');
+ $('#feedGrid').innerHTML = items.map(coinCard).join('');
+ $$('#feedGrid .coin').forEach((c) => c.addEventListener('click', () => openCoin(c.dataset.mint)));
+}
+
+function renderFeedEmpty(kind) {
+ const msg = kind === 'warming'
+ ? { b: 'Oracle is warming up', p: 'The conviction engine ships with its backend — once the ingestion augmentor is live it scores every new pump.fun launch in real time. Check back shortly.' }
+ : { b: 'No launches clear this filter yet', p: 'Loosen the tier or score filter, or wait for the next wave — new coins are scored the moment they surface.' };
+ $('#feedGrid').innerHTML = `<div class="state" style="grid-column:1/-1"><b>${msg.b}</b>${esc(msg.p)}</div>`;
+ $('#ctFeed').textContent = '';
+}
+
+function pillar(kind, label, val) {
+ return `<div class="pil ${kind}"><div class="lab">${label}<b>${val ?? '—'}</b></div>
+ <div class="track"><div class="fill" style="width:${Math.max(0, Math.min(100, val || 0))}%"></div></div></div>`;
+}
+
+function coinCard(it) {
+ const p = it.pillars || {};
+ const img = it.image_uri
+ ? `<img class="coin-img" src="${esc(it.image_uri)}" alt="" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'coin-img',textContent:'${esc((it.symbol || '?')[0])}'}))">`
+ : `<div class="coin-img">${esc((it.symbol || '?')[0])}</div>`;
+ const badges = (it.badges || []).map((b) => {
+ const cls = b === 'smart-money' ? 'sm' : b === 'structure-flag' ? 'flag' : b === 'news' ? 'news' : '';
+ const txt = b === 'structure-flag' ? 'structure ⚑' : b;
+ return `<span class="chip ${cls}">${esc(txt)}</span>`;
+ }).join('');
+ return `<button class="coin ${tierClass(it.tier)}" data-mint="${esc(it.mint)}">
+ <div class="coin-top">
+ ${img}
+ <div class="coin-id">
+ <div class="coin-sym">${esc(it.symbol || '—')}</div>
+ <div class="coin-name">${esc(it.name || it.mint.slice(0, 8))}</div>
+ </div>
+ <div class="dial">
+ <b>${it.score}</b><span>conviction</span>
+ <div class="tierpill ${tierPill(it.tier)}">${esc(it.tier)}</div>
+ </div>
+ </div>
+ <div class="pillars">
+ ${pillar('ped', 'Who', p.pedigree)}
+ ${pillar('str', 'How', p.structure)}
+ ${pillar('nar', 'What', p.narrative)}
+ ${pillar('mom', 'Move', p.momentum)}
+ </div>
+ <div class="coin-meta">
+ ${it.category ? `<span class="chip cat">${esc(it.category)}</span>` : ''}
+ ${it.smart_wallet_count ? `<span class="chip sm"><b>${it.smart_wallet_count}</b> smart in</span>` : ''}
+ ${badges}
+ <span class="chip">${ago(it.scored_at)} ago</span>
+ </div>
+ </button>`;
+}
+
+function setStats(data) {
+ const items = data.items || [];
+ $('#stScored').textContent = data.count ?? items.length;
+ $('#stStrong').textContent = items.filter((i) => i.tier === 'strong' || i.tier === 'prime').length;
+ $('#stSmart').textContent = items.reduce((s, i) => s + (i.smart_wallet_count || 0), 0);
+ $('#stUpdated').textContent = 'now';
+}
+
+// ── live stream ──────────────────────────────────────────────────────────────
+function openStream() {
+ try {
+ const es = new EventSource(`/api/oracle/stream?network=${NETWORK}`);
+ state.es = es;
+ es.addEventListener('hello', () => { setLive(true); });
+ es.addEventListener('coin', (e) => {
+ let it; try { it = JSON.parse(e.data); } catch { return; }
+ onLiveCoin(it);
+ });
+ es.addEventListener('bye', () => { es.close(); setTimeout(openStream, 1500); });
+ es.onerror = () => { setLive(false); es.close(); setTimeout(openStream, 4000); };
+ } catch { setLive(false); }
+}
+
+function setLive(on) {
+ $('#liveDot').classList.toggle('off', !on);
+ $('#liveLabel').textContent = on ? 'Live · fused conviction' : 'Reconnecting…';
+}
+
+function onLiveCoin(it) {
+ // passes active filters?
+ if (state.tier && it.tier !== state.tier) return;
+ if (state.category && it.category !== state.category) return;
+ if (state.minScore && it.score < state.minScore) return;
+ const isNew = !state.feed.has(it.mint);
+ state.feed.set(it.mint, it);
+ if (state.view !== 'feed') return;
+ renderFeed();
+ if (isNew) {
+ const el = $(`#feedGrid .coin[data-mint="${CSS.escape(it.mint)}"]`);
+ if (el) { el.classList.add('flash'); setTimeout(() => el.classList.remove('flash'), 950); }
+ }
+}
+
+// ── wallets ──────────────────────────────────────────────────────────────────
+async function loadWallets() {
+ const wrap = $('#walletWrap');
+ wrap.innerHTML = '<div class="state">Loading the reputation graph…</div>';
+ const q = new URLSearchParams({ leaderboard: '1', network: NETWORK, limit: '60' });
+ if (state.label) q.set('label', state.label);
+ const { ok, data } = await api(`/api/oracle/wallet?${q}`);
+ wrap.dataset.loaded = '1';
+ if (!ok || !data || !(data.items || []).length) {
+ wrap.innerHTML = `<div class="state"><b>No wallets ranked yet</b>The reputation graph fills in as coins resolve to outcomes. Once the brain has judged enough launches, the proven money surfaces here.</div>`;
+ $('#ctWallets').textContent = '';
+ return;
+ }
+ $('#ctWallets').textContent = data.items.length;
+ wrap.innerHTML = `
+ <div class="lhead"><span>#</span><span>Wallet</span><span class="colhide">Win rate</span><span>Early win</span><span>Score</span></div>
+ ${data.items.map((w, i) => walletRow(w, i)).join('')}`;
+ $$('#walletWrap .lrow').forEach((r) => r.addEventListener('click', () => openWallet(r.dataset.wallet)));
+}
+
+function walletRow(w, i) {
+ const a = w.archetype || { label: w.label, title: ARCH_TITLE[w.label] || 'Unproven' };
+ return `<button class="lrow" data-wallet="${esc(w.wallet)}">
+ <span class="lrank ${i < 3 ? 'top' : ''}">${i + 1}</span>
+ <span class="lw"><span class="nlabel lb-${esc(w.label)}">${esc(a.title)}</span><span class="lw-addr">${esc(shortAddr(w.wallet))}</span></span>
+ <span class="lstat colhide"><b>${fmtPct(w.win_rate)}</b></span>
+ <span class="lstat"><b>${fmtPct(w.early_win_rate)}</b></span>
+ <span class="lscore">${Math.round(w.score)}</span>
+ </button>`;
+}
+
+// ── edge (backtest) ──────────────────────────────────────────────────────────
+let _backtest = null;
+function cacheBacktest(bt) { _backtest = bt; if ($('#edgeWrap').dataset.loaded) renderEdge(); }
+
+async function loadEdge() {
+ const wrap = $('#edgeWrap');
+ wrap.dataset.loaded = '1';
+ if (!_backtest) {
+ const { data } = await api(`/api/oracle/feed?network=${NETWORK}&limit=1`);
+ _backtest = data?.backtest || [];
+ }
+ renderEdge();
+}
+
+function renderEdge() {
+ const wrap = $('#edgeWrap');
+ const rows = (_backtest || []).filter((r) => r.scored > 0);
+ if (!rows.length) {
+ wrap.innerHTML = `<div class="state"><b>The edge is still proving itself</b>Win-rate by tier appears once Oracle has scored coins that have since resolved to an outcome (graduated or not). This is intentionally honest — no backfilled numbers.</div>`;
+ return;
+ }
+ wrap.innerHTML = `
+ <div class="ehead"><span>Tier</span><span>Graduation rate</span><span class="colhide">Resolved</span><span>Avg ATH×</span><span>Scored</span></div>
+ ${rows.map(edgeRow).join('')}`;
+}
+
+function edgeRow(r) {
+ const grad = r.grad_rate ?? 0;
+ return `<div class="erow">
+ <span><span class="tierpill ${tierPill(r.tier)}">${esc(r.tier)}</span></span>
+ <span><div class="gradbar"><i style="width:${grad}%"></i></div><span class="lstat" style="text-align:left"><b>${r.grad_rate == null ? '—' : grad + '%'}</b></span></span>
+ <span class="lstat colhide">${r.resolved}</span>
+ <span class="lstat"><b>${r.avg_ath_multiple ? r.avg_ath_multiple.toFixed(1) + '×' : '—'}</b></span>
+ <span class="lstat">${r.scored}</span>
+ </div>`;
+}
+
+// ── coin drawer ──────────────────────────────────────────────────────────────
+async function openCoin(mint) {
+ const dr = $('#drawer');
+ dr.classList.add('open'); dr.setAttribute('aria-hidden', 'false');
+ $('#drTitle').textContent = 'Loading…';
+ $('#drBody').innerHTML = '<div class="state">Reading the order book…</div>';
+ const { ok, data } = await api(`/api/oracle/coin?mint=${encodeURIComponent(mint)}&network=${NETWORK}`);
+ if (!ok || !data || !data.conviction) {
+ $('#drTitle').textContent = 'Not observed yet';
+ $('#drBody').innerHTML = `<div class="state"><b>This launch hasn't been scored</b>Oracle scores coins as they surface on pump.fun. If it's brand new, it'll appear here within moments.</div>`;
+ return;
+ }
+ renderDrawer(data);
+}
+
+function renderDrawer(d) {
+ const c = d.conviction; const p = c.pillars || {};
+ $('#drTitle').innerHTML = `${esc(c.symbol || '—')} <span style="color:var(--muted);font:600 13px var(--mono)">${esc(c.name || '')}</span>`;
+ const reasons = (d.reasons || []).map((r) => `<div class="reason"><span class="rdot ${esc(r.pillar)}"></span><span>${esc(r.text)}</span></div>`).join('') || '<div class="state">No breakdown available.</div>';
+ const narr = d.narrative;
+ const whos = (d.whos_in || []).map(whoRow).join('') || '<div class="state">No wallet footprint recorded yet.</div>';
+ const out = d.outcome;
+ $('#drBody').innerHTML = `
+ <div style="display:flex;align-items:center;gap:18px;margin-bottom:6px">
+ <div class="dial ${tierClass(c.tier)}" style="text-align:left">
+ <b style="font-size:40px">${c.score}</b>
+ <div class="tierpill ${tierPill(c.tier)}">${esc(c.tier)} conviction</div>
+ </div>
+ <div style="flex:1" class="pillars">
+ ${pillar('ped', 'Who', p.pedigree)}
+ ${pillar('str', 'How', p.structure)}
+ ${pillar('nar', 'What', p.narrative)}
+ ${pillar('mom', 'Move', p.momentum)}
+ </div>
+ </div>
+ <div style="display:flex;gap:14px;margin:14px 0 2px">
+ <a class="solscan" href="${pumpUrl(c.mint)}" target="_blank" rel="noopener">pump.fun ↗</a>
+ <a class="solscan" href="${solscan(c.mint)}" target="_blank" rel="noopener">solscan ↗</a>
+ ${c.structure_cap != null && c.structure_cap < 60 ? `<span class="note warn">structural cap ${c.structure_cap}</span>` : ''}
+ </div>
+ ${narr ? `<div class="dr-sec">Narrative</div><div style="font-size:13.5px;color:var(--ink)">${esc(narr.narrative || '')}</div>
+ <div class="coin-meta" style="margin-top:8px"><span class="chip cat">${esc(narr.category)}</span><span class="chip">virality <b>${narr.virality ?? '—'}</b></span><span class="chip">${esc(narr.source || '')}</span></div>` : ''}
+ <div class="dr-sec">Why this score</div>${reasons}
+ <div class="dr-sec">Who's in <span style="color:var(--faint)">(${(d.whos_in || []).length})</span></div>${whos}
+ ${out ? `<div class="dr-sec">Outcome</div><div class="coin-meta">
+ <span class="chip ${out.graduated ? 'sm' : out.rugged ? 'flag' : ''}">${out.graduated ? 'graduated ✓' : out.rugged ? 'rugged ✕' : 'live'}</span>
+ ${out.ath_multiple ? `<span class="chip">ATH <b>${Number(out.ath_multiple).toFixed(1)}×</b></span>` : ''}</div>` : ''}
+ `;
+}
+
+function whoRow(w) {
+ const title = ARCH_TITLE[w.label] || 'Unproven';
+ const sub = [
+ w.is_creator ? 'creator' : null,
+ w.score != null ? `rep ${Math.round(w.score)}` : null,
+ w.win_rate != null ? `${Math.round(w.win_rate)}% win` : null,
+ ].filter(Boolean).join(' · ');
+ return `<div class="nwallet">
+ <div class="nw-left">
+ <span class="nw-addr"><span class="nlabel lb-${esc(w.label)}">${esc(title)}</span><a class="solscan" href="${solscan(w.wallet)}" target="_blank" rel="noopener">${esc(shortAddr(w.wallet))}</a></span>
+ <span class="nw-sub">${esc(sub || '—')}</span>
+ </div>
+ <span class="nw-buy">${fmtSol(w.buy_sol)}</span>
+ </div>`;
+}
+
+function closeDrawer() {
+ const dr = $('#drawer'); dr.classList.remove('open'); dr.setAttribute('aria-hidden', 'true');
+}
+
+async function openWallet(wallet) {
+ switchView('feed'); // close any drawer context; wallets open in drawer too
+ const dr = $('#drawer');
+ dr.classList.add('open'); dr.setAttribute('aria-hidden', 'false');
+ $('#drTitle').textContent = shortAddr(wallet);
+ $('#drBody').innerHTML = '<div class="state">Pulling track record…</div>';
+ const { ok, data } = await api(`/api/oracle/wallet?address=${encodeURIComponent(wallet)}&network=${NETWORK}`);
+ if (!ok || !data) { $('#drBody').innerHTML = '<div class="state">Could not load this wallet.</div>'; return; }
+ const r = data.reputation; const a = data.archetype || {};
+ $('#drTitle').innerHTML = `<span class="nlabel lb-${esc(a.label)}">${esc(a.title || 'Unproven')}</span> ${esc(shortAddr(wallet))}`;
+ const recent = (data.recent || []).map((c) => `<div class="nwallet"><div class="nw-left"><span class="nw-addr">${esc(c.symbol || c.mint.slice(0, 6))} ${c.is_creator ? '<span class="nlabel lb-rugger">created</span>' : ''}</span><span class="nw-sub">${esc(c.category || '')}</span></div><span class="nw-buy">${fmtSol(c.buy_sol)}</span></div>`).join('') || '<div class="state">No recent coins recorded.</div>';
+ $('#drBody').innerHTML = `
+ <div style="font-size:13px;color:var(--muted);margin-bottom:14px">${esc(a.blurb || '')}</div>
+ ${r ? `<div class="pillars" style="grid-template-columns:repeat(2,1fr);gap:12px">
+ ${pillar('ped', 'Smart score', Math.round(r.score))}
+ ${pillar('str', 'Win rate', Math.round(r.win_rate))}
+ ${pillar('nar', 'Early win', Math.round(r.early_win_rate))}
+ ${pillar('mom', 'Dump rate', Math.round(r.dump_rate))}
+ </div>
+ <div class="coin-meta" style="margin-top:14px">
+ <span class="chip">coins <b>${r.coins_traded ?? 0}</b></span>
+ <span class="chip">early <b>${r.early_entries ?? 0}</b></span>
+ <span class="chip sm">wins <b>${r.wins ?? 0}</b></span>
+ <span class="chip flag">duds <b>${r.duds ?? 0}</b></span>
+ ${r.creator_count ? `<span class="chip">created <b>${r.creator_count}</b></span>` : ''}
+ </div>` : '<div class="state">This wallet has no judged history yet.</div>'}
+ <div class="dr-sec">Recent footprint</div>${recent}
+ <div style="margin-top:14px"><a class="solscan" href="${solscan(wallet)}" target="_blank" rel="noopener">View on solscan ↗</a></div>
+ `;
+}
+
+// ── agent arm panel ──────────────────────────────────────────────────────────
+async function loadAgentPanel() {
+ const body = $('#armBody');
+ body.dataset.loaded = '1';
+ body.innerHTML = '<div class="state">Loading your agents…</div>';
+ const { ok, data } = await api('/api/agents');
+ const agents = ok && data ? (data.agents || data.items || data || []) : [];
+ state.agents = Array.isArray(agents) ? agents : [];
+ if (!state.agents.length) {
+ body.innerHTML = `<div class="state"><b>Sign in and create a 3D agent</b>Your agent needs its own custodial Solana wallet to act on conviction. Create one in the studio, then come back to arm it.
+ <div style="margin-top:16px"><a class="btn" href="/create/studio">Create an agent →</a></div></div>`;
+ return;
+ }
+ renderArmForm();
+}
+
+function renderArmForm() {
+ const body = $('#armBody');
+ const opts = state.agents.map((a) => `<option value="${esc(a.id)}">${esc(a.name || a.id)}</option>`).join('');
+ body.innerHTML = `
+ <div class="field"><label>Agent</label><select id="agSel">${opts}</select></div>
+ <div class="row2">
+ <div class="field"><label>Min conviction</label><select id="agMin">
+ <option value="86">Prime only (≥86)</option>
+ <option value="72" selected>Strong+ (≥72)</option>
+ <option value="56">Lean+ (≥56)</option>
+ </select></div>
+ <div class="field"><label>Size / trade (SOL)</label><input id="agSize" type="number" min="0.001" step="0.01" value="0.05"></div>
+ </div>
+ <div class="row2">
+ <div class="field"><label>Max daily (SOL)</label><input id="agDaily" type="number" min="0.01" step="0.05" value="0.5"></div>
+ <div class="field"><label>Max open</label><input id="agOpen" type="number" min="1" step="1" value="5"></div>
+ </div>
+ <div class="field"><label>Only these narratives (none = any)</label>
+ <div class="chips" id="agCats">${CATEGORIES.map((c) => `<button type="button" class="cchip" data-cat="${c}">${c}</button>`).join('')}</div>
+ </div>
+ <div class="toggle">
+ <div class="t-lab"><b>Require smart money in</b><span>Only act if ≥1 proven wallet has bought</span></div>
+ <div class="sw on" id="agSmart" role="switch" aria-checked="true"></div>
+ </div>
+ <div class="toggle">
+ <div class="t-lab"><b>Mode</b><span id="agModeSub">Simulate — logs actions, spends nothing</span></div>
+ <div class="sw live" id="agLive" role="switch" aria-checked="false"></div>
+ </div>
+ <div class="toggle">
+ <div class="t-lab"><b id="agArmLab">Armed</b><span>Master switch for this agent</span></div>
+ <div class="sw" id="agArm" role="switch" aria-checked="false"></div>
+ </div>
+ <button class="btn primary" id="agSave" style="margin-top:8px">Save configuration</button>
+ <div class="note" id="agNote"></div>`;
+
+ // toggles
+ wireSwitch('#agSmart');
+ wireSwitch('#agLive', (on) => { $('#agModeSub').textContent = on ? 'Live — real SOL from the agent wallet (capped)' : 'Simulate — logs actions, spends nothing'; $('#agLive').classList.toggle('on', on); });
+ wireSwitch('#agArm');
+ $('#agCats').addEventListener('click', (e) => { const b = e.target.closest('.cchip'); if (b) b.classList.toggle('on'); });
+ $('#agSel').addEventListener('change', () => loadWatch($('#agSel').value));
+ $('#agSave').addEventListener('click', saveWatch);
+
+ state.agentId = state.agents[0].id;
+ loadWatch(state.agentId);
+}
+
+function wireSwitch(sel, cb) {
+ const el = $(sel);
+ el.addEventListener('click', () => {
+ const on = !el.classList.contains('on');
+ el.classList.toggle('on', on);
+ el.setAttribute('aria-checked', String(on));
+ if (cb) cb(on);
+ });
+}
+
+async function loadWatch(agentId) {
+ state.agentId = agentId;
+ const { ok, data } = await api(`/api/oracle/watch?agent_id=${encodeURIComponent(agentId)}&network=${NETWORK}`);
+ const w = ok && data ? data.watch : null;
+ state.watch = w;
+ if (w) {
+ $('#agMin').value = String(w.min_score >= 86 ? 86 : w.min_score >= 72 ? 72 : 56);
+ $('#agSize').value = w.per_trade_sol ?? 0.05;
+ $('#agDaily').value = w.max_daily_sol ?? 0.5;
+ $('#agOpen').value = w.max_open ?? 5;
+ setSwitch('#agSmart', w.require_smart_money !== false);
+ setSwitch('#agArm', !!w.armed);
+ const live = w.mode === 'live'; setSwitch('#agLive', live);
+ $('#agModeSub').textContent = live ? 'Live — real SOL from the agent wallet (capped)' : 'Simulate — logs actions, spends nothing';
+ const cats = new Set(w.categories || []);
+ $$('#agCats .cchip').forEach((b) => b.classList.toggle('on', cats.has(b.dataset.cat)));
+ }
+ loadActions(agentId);
+}
+
+function setSwitch(sel, on) { const el = $(sel); el.classList.toggle('on', on); el.setAttribute('aria-checked', String(on)); }
+
+async function saveWatch() {
+ const btn = $('#agSave'); btn.disabled = true; btn.textContent = 'Saving…';
+ const cats = $$('#agCats .cchip.on').map((b) => b.dataset.cat);
+ const min = Number($('#agMin').value);
+ const payload = {
+ agent_id: state.agentId, network: NETWORK,
+ armed: $('#agArm').classList.contains('on'),
+ mode: $('#agLive').classList.contains('on') ? 'live' : 'simulate',
+ min_score: min, min_tier: min >= 86 ? 'prime' : min >= 72 ? 'strong' : 'lean',
+ categories: cats,
+ per_trade_sol: Number($('#agSize').value) || 0.05,
+ max_daily_sol: Number($('#agDaily').value) || 0.5,
+ max_open: Number($('#agOpen').value) || 5,
+ require_smart_money: $('#agSmart').classList.contains('on'),
+ };
+ const { ok, data } = await api('/api/oracle/watch', {
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
+ });
+ btn.disabled = false; btn.textContent = 'Save configuration';
+ const note = $('#agNote');
+ if (ok && data?.watch) {
+ note.className = 'note'; note.textContent = data.watch.armed ? `Armed in ${data.watch.mode} mode. Your agent is watching the stream.` : 'Saved. Toggle "Armed" to start watching.';
+ loadActions(state.agentId);
+ } else {
+ note.className = 'note warn';
+ note.textContent = data?.error?.message || 'Could not save — sign in and make sure you own this agent.';
+ }
+}
+
+async function loadActions(agentId) {
+ const body = $('#actionsBody');
+ const { ok, data } = await api(`/api/oracle/watch?agent_id=${encodeURIComponent(agentId)}&network=${NETWORK}`);
+ const actions = ok && data ? (data.actions || []) : [];
+ if (!actions.length) {
+ body.innerHTML = '<div class="state">No actions yet. Once armed, your agent\'s moves will appear here and get graded against outcomes.</div>';
+ return;
+ }
+ body.innerHTML = `<div class="lwrap">${actions.map(actionRow).join('')}</div>`;
+}
+
+function actionRow(a) {
+ const cls = a.outcome === 'win' ? 'sm' : a.outcome === 'loss' ? 'flag' : '';
+ return `<div class="nwallet" style="padding:11px 14px">
+ <div class="nw-left">
+ <span class="nw-addr">${esc(a.symbol || a.mint.slice(0, 6))} <span class="tierpill ${tierPill(a.tier)}">${esc(a.tier || '')}</span> <span class="chip" style="padding:3px 6px">${esc(a.mode)}</span></span>
+ <span class="nw-sub">conviction ${a.conviction ?? '—'} · ${esc(a.status)} · ${ago(a.acted_at)} ago${a.reason ? ' · ' + esc(a.reason) : ''}</span>
+ </div>
+ <span class="nw-buy ${cls ? 'chip ' + cls : ''}">${a.peak_multiple ? Number(a.peak_multiple).toFixed(1) + '×' : fmtSol(a.size_sol)}</span>
+ </div>`;
+}
+
+document.addEventListener('DOMContentLoaded', boot);
diff --git a/src/play/arena.js b/src/play/arena.js
index ee39a36dd..3c81d5b04 100644
--- a/src/play/arena.js
+++ b/src/play/arena.js
@@ -78,7 +78,7 @@ async function loadAndPlace() {
const r = await fetch(`/api/sniper/leaderboard?network=${NETWORK}`);
if (!r.ok) throw new Error('http ' + r.status);
data = await r.json();
- } catch (e) {
+ } catch {
renderBoard([]);
setEmpty(true);
return;
@@ -177,7 +177,7 @@ function connectStream() {
es.addEventListener('buy', (m) => safe(() => onBuy(JSON.parse(m.data))));
es.addEventListener('sell', (m) => safe(() => onSell(JSON.parse(m.data))));
es.addEventListener('update', () => {});
- es.onerror = () => { setLive(false); try { es.close(); } catch {} setTimeout(connectStream, 2500); };
+ es.onerror = () => { setLive(false); try { es.close(); } catch { /* already closed */ } setTimeout(connectStream, 2500); };
}
const safe = (fn) => { try { fn(); } catch { /* one bad frame never breaks the stream */ } };
@@ -404,7 +404,7 @@ async function choose(url, btn) {
await world.spawnPlayer(url);
localStorage.setItem(PLAYER_KEY, url);
closePicker();
- } catch (e) {
+ } catch {
btn.classList.add('failed');
setTimeout(() => btn.classList.remove('failed'), 1500);
} finally {
@@ -428,5 +428,5 @@ async function mountJoystick() {
world.setJoystick(Math.cos(a) * Math.min(1, f), Math.sin(a) * Math.min(1, f));
});
stick.on('end', () => world.setJoystick(0, 0));
- } catch (e) { /* desktop / import failure — keyboard still works */ }
+ } catch { /* desktop / import failure — keyboard still works */ }
}
diff --git a/tests/oracle/agent-eval.test.js b/tests/oracle/agent-eval.test.js
new file mode 100644
index 000000000..3e5d770db
--- /dev/null
+++ b/tests/oracle/agent-eval.test.js
@@ -0,0 +1,62 @@
+// Oracle agent-eval — the rules that gate real money. Pinned hard.
+
+import { describe, it, expect } from 'vitest';
+import { evaluateWatch } from '../../api/_lib/oracle/agent-eval.js';
+
+const baseWatch = {
+ armed: true, mode: 'simulate', min_score: 72, min_tier: 'strong',
+ categories: [], per_trade_sol: 0.05, max_daily_sol: 0.5, max_open: 5, require_smart_money: true,
+};
+const goodCoin = { score: 88, tier: 'prime', category: 'ai', smart_wallet_count: 3 };
+
+describe('evaluateWatch', () => {
+ it('acts on a coin that clears every gate', () => {
+ const d = evaluateWatch({ watch: baseWatch, coin: goodCoin, openCount: 0, spentTodaySol: 0 });
+ expect(d.act).toBe(true);
+ expect(d.size).toBe(0.05);
+ });
+
+ it('never acts when not armed', () => {
+ expect(evaluateWatch({ watch: { ...baseWatch, armed: false }, coin: goodCoin }).act).toBe(false);
+ });
+
+ it('blocks below the score threshold', () => {
+ const d = evaluateWatch({ watch: baseWatch, coin: { ...goodCoin, score: 60, tier: 'lean' } });
+ expect(d.act).toBe(false);
+ expect(d.reason).toMatch(/below threshold/);
+ });
+
+ it('blocks below the tier floor even if score sneaks through', () => {
+ const d = evaluateWatch({ watch: { ...baseWatch, min_score: 0, min_tier: 'strong' }, coin: { ...goodCoin, tier: 'watch' } });
+ expect(d.act).toBe(false);
+ expect(d.reason).toMatch(/tier/);
+ });
+
+ it('respects the narrative watchlist', () => {
+ const only = { ...baseWatch, categories: ['news', 'culture'] };
+ expect(evaluateWatch({ watch: only, coin: goodCoin }).act).toBe(false);
+ expect(evaluateWatch({ watch: only, coin: { ...goodCoin, category: 'news' } }).act).toBe(true);
+ });
+
+ it('requires smart money when configured', () => {
+ expect(evaluateWatch({ watch: baseWatch, coin: { ...goodCoin, smart_wallet_count: 0 } }).act).toBe(false);
+ expect(evaluateWatch({ watch: { ...baseWatch, require_smart_money: false }, coin: { ...goodCoin, smart_wallet_count: 0 } }).act).toBe(true);
+ });
+
+ it('enforces the open-position cap', () => {
+ const d = evaluateWatch({ watch: baseWatch, coin: goodCoin, openCount: 5 });
+ expect(d.act).toBe(false);
+ expect(d.reason).toMatch(/max open/);
+ });
+
+ it('enforces the daily budget', () => {
+ const d = evaluateWatch({ watch: baseWatch, coin: goodCoin, openCount: 0, spentTodaySol: 0.48 });
+ expect(d.act).toBe(false);
+ expect(d.reason).toMatch(/daily budget/);
+ });
+
+ it('allows the exact last trade that fits the budget', () => {
+ const d = evaluateWatch({ watch: baseWatch, coin: goodCoin, openCount: 0, spentTodaySol: 0.45 });
+ expect(d.act).toBe(true);
+ });
+});
diff --git a/tests/oracle/conviction.test.js b/tests/oracle/conviction.test.js
new file mode 100644
index 000000000..dfecf1abd
--- /dev/null
+++ b/tests/oracle/conviction.test.js
@@ -0,0 +1,201 @@
+// Oracle conviction engine — unit tests.
+//
+// The engine is the product's brain, so its behavior is pinned here: pedigree
+// leads, structural red flags cap the final score no matter how good the
+// pedigree, flagged wallets drag, and the tiers fall on the documented bounds.
+
+import { describe, it, expect } from 'vitest';
+import {
+ convict,
+ pedigreeScore,
+ structureScore,
+ narrativeScore,
+ momentumScore,
+ WEIGHTS,
+ tierTone,
+} from '../../api/_lib/oracle/conviction.js';
+import { archetypeFor, isProven, isFlagged } from '../../api/_lib/oracle/archetype.js';
+
+describe('weights', () => {
+ it('pillar weights sum to 1', () => {
+ const sum = WEIGHTS.pedigree + WEIGHTS.structure + WEIGHTS.narrative + WEIGHTS.momentum;
+ expect(sum).toBeCloseTo(1, 6);
+ });
+});
+
+describe('pedigreeScore', () => {
+ it('rewards proven wallets and proven-money share', () => {
+ const out = pedigreeScore({
+ score: 60,
+ smartWalletCount: 3,
+ provenBuyLamports: 5e9,
+ totalBuyLamports: 1e10,
+ notable: [{ wallet: 'a', label: 'smart_money', score: 88 }],
+ });
+ expect(out.score).toBeGreaterThan(60);
+ expect(out.reasons.join(' ')).toMatch(/smart-money/);
+ });
+
+ it('drags hard on flagged (rugger/dumper) wallets', () => {
+ const clean = pedigreeScore({ score: 70, smartWalletCount: 0, notable: [] });
+ const dirty = pedigreeScore({
+ score: 70,
+ smartWalletCount: 0,
+ notable: [
+ { wallet: 'r', label: 'rugger', score: 10 },
+ { wallet: 'd', label: 'dumper', score: 20 },
+ ],
+ });
+ expect(dirty.score).toBeLessThan(clean.score);
+ expect(dirty.reasons.join(' ')).toMatch(/flagged/);
+ });
+
+ it('derives a base from notable wallets when no composite score is given', () => {
+ const out = pedigreeScore({
+ notable: [
+ { wallet: 'a', label: 'smart_money', score: 80 },
+ { wallet: 'b', label: 'neutral', score: 40 },
+ ],
+ });
+ expect(out.score).toBeGreaterThan(0);
+ });
+});
+
+describe('structureScore', () => {
+ it('caps the final score on a bundle launch', () => {
+ const out = structureScore({ bundleFlag: true, uniqueBuyers: 4, funderClusterPct: 55 });
+ expect(out.cap).toBeLessThan(50);
+ expect(out.reasons.join(' ')).toMatch(/bundle/);
+ });
+
+ it('rewards a wide, distributed base', () => {
+ const wide = structureScore({ uniqueBuyers: 70, topHolderPct: 8 });
+ const thin = structureScore({ uniqueBuyers: 5, topHolderPct: 8 });
+ expect(wide.score).toBeGreaterThan(thin.score);
+ });
+
+ it('caps hard when the dev is already dumping', () => {
+ const out = structureScore({ devSoldPct: 60 });
+ expect(out.cap).toBeLessThanOrEqual(38);
+ });
+});
+
+describe('narrativeScore', () => {
+ it('blends classifier virality with the category prior, weighted by confidence', () => {
+ const high = narrativeScore({ category: 'news', virality: 90, confidence: 0.9 });
+ const low = narrativeScore({ category: 'unknown', virality: 10, confidence: 0.9 });
+ expect(high.score).toBeGreaterThan(low.score);
+ });
+
+ it('falls back to the category prior when virality is absent', () => {
+ const out = narrativeScore({ category: 'culture' });
+ expect(out.score).toBeGreaterThan(0);
+ expect(out.reasons.join(' ')).toMatch(/no virality/);
+ });
+});
+
+describe('momentumScore', () => {
+ it('rewards strong buy inflow and penalizes distribution', () => {
+ const inflow = momentumScore({ buyCount: 40, sellCount: 3 });
+ const dist = momentumScore({ buyCount: 5, sellCount: 30 });
+ expect(inflow.score).toBeGreaterThan(dist.score);
+ });
+
+ it('rewards a reasonable dev buy and penalizes an oversized one', () => {
+ const good = momentumScore({ devBuySol: 1.0, buyCount: 12, sellCount: 1 });
+ const huge = momentumScore({ devBuySol: 9.0, buyCount: 12, sellCount: 1 });
+ expect(good.score).toBeGreaterThan(huge.score);
+ });
+});
+
+describe('convict (fusion)', () => {
+ const primeIntel = {
+ smartMoney: {
+ score: 88, smartWalletCount: 5, provenBuyLamports: 8e9, totalBuyLamports: 1e10,
+ notable: [
+ { wallet: 'a', label: 'smart_money', score: 90 },
+ { wallet: 'b', label: 'smart_money', score: 82 },
+ ],
+ },
+ structure: { uniqueBuyers: 70, topHolderPct: 7, funderClusterPct: 5 },
+ narrative: { category: 'news', virality: 85, confidence: 0.85 },
+ behavior: { buyCount: 45, sellCount: 3, earlyBuyerCount: 50, devBuySol: 1.2 },
+ };
+
+ it('a clean, smart-money, high-narrative launch scores strong/prime', () => {
+ const v = convict(primeIntel);
+ expect(v.score).toBeGreaterThanOrEqual(72);
+ expect(['strong', 'prime']).toContain(v.tier);
+ expect(v.badges).toContain('smart-money');
+ expect(v.pillars.pedigree).toBeGreaterThan(70);
+ });
+
+ it('structure cap overrides great pedigree — a bundle can never read strong', () => {
+ const bundled = {
+ ...primeIntel,
+ structure: { uniqueBuyers: 6, topHolderPct: 55, funderClusterPct: 60, bundleFlag: true, devSoldPct: 55 },
+ };
+ const v = convict(bundled);
+ expect(v.score).toBeLessThan(50);
+ expect(v.tier === 'avoid' || v.tier === 'watch').toBe(true);
+ expect(v.badges).toContain('structure-flag');
+ });
+
+ it('flagged wallets pull a mediocre coin further down', () => {
+ const withRuggers = {
+ ...primeIntel,
+ smartMoney: {
+ score: 45, smartWalletCount: 0, notable: [
+ { wallet: 'r', label: 'rugger', score: 8 },
+ { wallet: 'd', label: 'dumper', score: 15 },
+ ],
+ },
+ };
+ const v = convict(withRuggers);
+ expect(v.pillars.pedigree).toBeLessThan(45);
+ });
+
+ it('returns a transparent, ordered breakdown and valid tier', () => {
+ const v = convict(primeIntel);
+ expect(v.reasons[0]).toHaveProperty('pillar');
+ expect(v.reasons[0]).toHaveProperty('text');
+ expect(['avoid', 'watch', 'lean', 'strong', 'prime']).toContain(v.tier);
+ expect(v.score).toBeGreaterThanOrEqual(0);
+ expect(v.score).toBeLessThanOrEqual(100);
+ });
+
+ it('is deterministic — same input, same score', () => {
+ expect(convict(primeIntel).score).toBe(convict(primeIntel).score);
+ });
+
+ it('an empty intel object does not throw and reads low', () => {
+ const v = convict({});
+ expect(v.score).toBeGreaterThanOrEqual(0);
+ expect(v.tier).toBeDefined();
+ });
+});
+
+describe('tierTone', () => {
+ it('maps tiers to UI tones', () => {
+ expect(tierTone('prime')).toBe('good');
+ expect(tierTone('avoid')).toBe('bad');
+ expect(tierTone('lean')).toBe('warn');
+ });
+});
+
+describe('archetypes', () => {
+ it('resolves known labels and tolerates unknowns', () => {
+ expect(archetypeFor('smart_money').tone).toBe('good');
+ expect(archetypeFor('rugger').tone).toBe('bad');
+ expect(archetypeFor(null).label).toBe('unproven');
+ expect(archetypeFor('nonsense').title).toBe('Unproven');
+ });
+
+ it('isProven / isFlagged gate correctly', () => {
+ expect(isProven('smart_money')).toBe(true);
+ expect(isProven('neutral', 75)).toBe(true);
+ expect(isProven('neutral', 10)).toBe(false);
+ expect(isFlagged('rugger')).toBe(true);
+ expect(isFlagged('smart_money')).toBe(false);
+ });
+});
diff --git a/tests/oracle/narrative.test.js b/tests/oracle/narrative.test.js
new file mode 100644
index 000000000..fe5dd9007
--- /dev/null
+++ b/tests/oracle/narrative.test.js
@@ -0,0 +1,40 @@
+// Oracle narrative classifier — fallback path tests.
+//
+// The LLM path needs live providers, so here we pin the deterministic heuristic
+// (the real fallback) and the parsing/validation guards that keep a malformed
+// model response from poisoning the pipeline.
+
+import { describe, it, expect } from 'vitest';
+import { heuristicNarrative, CATEGORIES } from '../../api/_lib/oracle/narrative.js';
+
+describe('heuristicNarrative', () => {
+ it('always returns a valid category from the taxonomy', () => {
+ const out = heuristicNarrative({ name: 'random thing', symbol: 'RND' });
+ expect(CATEGORIES).toContain(out.category);
+ expect(out.source).toBe('heuristic');
+ });
+
+ it('classifies an AI coin', () => {
+ const out = heuristicNarrative({ name: 'Autonomous Agent', symbol: 'AGENT', description: 'an agentic AI llm on-chain' });
+ expect(out.category).toBe('ai');
+ expect(out.tags.length).toBeGreaterThan(0);
+ });
+
+ it('classifies an animal meme', () => {
+ const out = heuristicNarrative({ name: 'Doge Hat Wif', symbol: 'WIF', description: 'dog wif hat' });
+ expect(out.category).toBe('animal');
+ });
+
+ it('rewards virality for links + punchy ticker', () => {
+ const rich = heuristicNarrative({ name: 'Pepe', symbol: 'PEPE', description: 'the frog returns to glory', twitter: 'x.com/p', telegram: 't.me/p', website: 'p.fun' });
+ const bare = heuristicNarrative({ name: 'thing', symbol: 'LONGTICKERNAME' });
+ expect(rich.virality).toBeGreaterThan(bare.virality);
+ expect(rich.virality).toBeLessThanOrEqual(100);
+ });
+
+ it('returns low confidence + unknown on empty signal', () => {
+ const out = heuristicNarrative({});
+ expect(out.confidence).toBeLessThan(0.3);
+ expect(out.category).toBe('unknown');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 549e3bf05..f1a325f43 100644
--- a/vercel.json
+++ b/vercel.json
@@ -113,6 +113,10 @@
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
},
+ "api/pump/launch-detail.js": {
+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
+ "maxDuration": 30
+ },
"api/**/*.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 30
@@ -517,6 +521,10 @@
"src": "/pump-live/?",
"dest": "/pump-live.html"
},
+ {
+ "src": "/launches/([1-9A-HJ-NP-Za-km-z]{32,44})/?",
+ "dest": "/launch-detail.html"
+ },
{
"src": "/launches/?",
"dest": "/launches.html"
@@ -1671,6 +1679,10 @@
"src": "/api/onboarding/link-avatar",
"dest": "/api/onboarding/[action]?action=link-avatar"
},
+ {
+ "src": "/api/pump/launch-detail",
+ "dest": "/api/pump/launch-detail.js"
+ },
{
"src": "/api/pump/build-metadata",
"dest": "/api/pump/[action]?action=build-metadata"
diff --git a/vite.config.js b/vite.config.js
index d6389151d..7142dba7e 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -213,6 +213,7 @@ const appConfig = {
reportCompressedSize: false,
rollupOptions: {
external: [
+ '/launch/launch.js',
'/studio/launch-panel.js',
'/studio/fees-panel.js',
'./fees-panel.js',
@@ -311,6 +312,7 @@ const appConfig = {
'agent-embed': resolve(__dirname, 'pages/agent-embed.html'),
'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),
launches: resolve(__dirname, 'pages/launches.html'),
+ 'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),
leaderboard: resolve(__dirname, 'pages/leaderboard.html'),
trader: resolve(__dirname, 'pages/trader.html'),
'avatar-embed': resolve(__dirname, 'pages/avatar-embed.html'),
@@ -334,6 +336,7 @@ const appConfig = {
bounty: resolve(__dirname, 'pages/bounty.html'),
'pump-live': resolve(__dirname, 'pages/pump-live.html'),
radar: resolve(__dirname, 'pages/radar.html'),
+ oracle: resolve(__dirname, 'pages/oracle.html'),
'bulk-launch': resolve(__dirname, 'pages/bulk-launch.html'),
'pump-dashboard': resolve(__dirname, 'pages/pump-dashboard.html'),
autopilot: resolve(__dirname, 'pages/autopilot.html'),
@@ -672,6 +675,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/pump-live/': resolve(root, 'pages/pump-live.html'),
'/radar': resolve(root, 'pages/radar.html'),
'/radar/': resolve(root, 'pages/radar.html'),
+ '/oracle': resolve(root, 'pages/oracle.html'),
+ '/oracle/': resolve(root, 'pages/oracle.html'),
'/pump-dashboard': resolve(root, 'pages/pump-dashboard.html'),
'/pump-dashboard/': resolve(root, 'pages/pump-dashboard.html'),
'/autopilot': resolve(root, 'pages/autopilot.html'),
@@ -1004,6 +1009,12 @@ support: resolve(__dirname, 'pages/support.html'),
/^\/communities\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path)
)
filePath = resolve(root, 'pages/communities.html');
+ // /launches/:mint → rich coin detail page
+ else if (
+ !filePath &&
+ /^\/launches\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path)
+ )
+ filePath = resolve(root, 'pages/launch-detail.html');
// /@<handle> → public live profile page
else if (!filePath && /^\/@[a-z0-9_-]{3,30}\/?$/i.test(path))
filePath = resolve(root, 'pages/handle.html');
diff --git a/workers/oracle/README.md b/workers/oracle/README.md
new file mode 100644
index 000000000..168d64644
--- /dev/null
+++ b/workers/oracle/README.md
@@ -0,0 +1,51 @@
+# Oracle worker
+
+A long-lived Node process that powers the **Oracle** product (`/oracle`,
+`/api/oracle/*`). It does **not** ingest raw pump.fun data — the platform's data
+brain (`pump_coin_intel`, `pump_coin_wallets`, `wallet_reputation`,
+`coin_smart_money`, `pump_coin_outcomes`) already has full coverage. Oracle adds
+the **fusion** and the **action loop** on top.
+
+## What it does
+
+1. **Score loop** (`score-loop.js`) — every `ORACLE_SCORE_INTERVAL_MS`, finds
+ recent brain coins missing or stale in `oracle_conviction`, classifies their
+ cultural narrative (LLM free-first, heuristic fallback), fuses the four-pillar
+ conviction score, and caches it. Keeps the live feed + SSE warm.
+
+2. **Agent loop** (`agent-loop.js`) — every `ORACLE_AGENT_INTERVAL_MS`, runs the
+ pure decision (`api/_lib/oracle/agent-eval.js`) for every armed
+ `oracle_agent_watch` against each freshly-scored coin and executes when a coin
+ clears the owner's bar. Each (agent, mint) acts at most once.
+
+## Modes
+
+- `ORACLE_MODE=simulate` (default) — logs realistic actions to
+ `oracle_watch_actions`, spends nothing. Safe to run anywhere.
+- `ORACLE_MODE=live` — loads each agent's own custodial Solana keypair
+ (decrypted via the audited `recoverSolanaAgentKeypair`) and broadcasts a
+ pump.fun buy via the same `PumpTradeClient` the production trade path uses.
+ Requires `JWT_SECRET`. Every live action is hard-capped at
+ `ORACLE_MAX_TRADE_SOL` regardless of a watch's config.
+
+## Env
+
+| var | default | meaning |
+|-----|---------|---------|
+| `DATABASE_URL` | — (required) | Neon Postgres |
+| `JWT_SECRET` | — (required for live) | decrypts agent wallets |
+| `ORACLE_MODE` | `simulate` | `simulate` \| `live` |
+| `ORACLE_NETWORK` | `mainnet` | `mainnet` \| `devnet` |
+| `ORACLE_GLOBAL_KILL` | `0` | `1` halts all agent actions (scoring continues) |
+| `ORACLE_SCORE_INTERVAL_MS` | `15000` | score-pass cadence |
+| `ORACLE_AGENT_INTERVAL_MS` | `3000` | agent-pass cadence |
+| `ORACLE_SCORE_BATCH` | `20` | coins scored per pass |
+| `ORACLE_RESCORE_AFTER_SEC` | `180` | re-score a coin after this staleness |
+| `ORACLE_MAX_TRADE_SOL` | `0.25` | hard per-trade cap (live) |
+
+## Run
+
+```bash
+npm run db:migrate # applies api/_lib/migrations/20260616120000_oracle.sql
+npm run worker:oracle # simulate by default
+```
diff --git a/workers/oracle/agent-loop.js b/workers/oracle/agent-loop.js
new file mode 100644
index 000000000..b23a8b42b
--- /dev/null
+++ b/workers/oracle/agent-loop.js
@@ -0,0 +1,67 @@
+// Oracle worker — agent action loop.
+//
+// Polls newly-scored coins and, for every armed agent watch, runs the pure
+// decision (agent-eval) against each coin and executes when it clears the bar.
+// Each (agent, mint) acts at most once. Simulate-default; live is gated by the
+// worker's mode + a hard per-trade cap in the executor.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+import { evaluateWatch } from '../../api/_lib/oracle/agent-eval.js';
+import { executeAction, agentBudget } from './executor.js';
+
+// Module cursor — only consider verdicts scored since the last pass.
+let cursor = new Date(Date.now() - 60_000).toISOString();
+
+async function armedWatches(network) {
+ return sql`
+ select w.agent_id, w.user_id, w.network, w.armed, w.mode, w.min_score, w.min_tier,
+ w.categories, w.per_trade_sol, w.max_daily_sol, w.max_open, w.require_smart_money
+ from oracle_agent_watch w
+ join agent_identities a on a.id = w.agent_id and a.deleted_at is null
+ where w.armed = true and w.network = ${network}
+ `.catch(() => []);
+}
+
+async function freshlyScored(network, sinceIso, limit = 60) {
+ return sql`
+ select mint, symbol, score, tier, category, smart_wallet_count, scored_at
+ from oracle_conviction
+ where network = ${network} and scored_at > ${sinceIso}::timestamptz
+ order by scored_at asc
+ limit ${limit}
+ `.catch(() => []);
+}
+
+async function alreadyActed(agentId, mint, network) {
+ const r = await sql`
+ select 1 from oracle_watch_actions
+ where agent_id = ${agentId} and mint = ${mint} and network = ${network} limit 1
+ `.catch(() => []);
+ return r.length > 0;
+}
+
+export async function runAgentPass(cfg) {
+ if (cfg.globalKill) return 0;
+ const watches = await armedWatches(cfg.network);
+ if (!watches.length) return 0;
+
+ const coins = await freshlyScored(cfg.network, cursor);
+ if (coins.length) cursor = coins[coins.length - 1].scored_at;
+ if (!coins.length) return 0;
+
+ let acted = 0;
+ for (const watch of watches) {
+ const { openCount, spentTodaySol } = await agentBudget(watch.agent_id, cfg.network);
+ let open = openCount, spent = spentTodaySol;
+ for (const coin of coins) {
+ const decision = evaluateWatch({ watch, coin, openCount: open, spentTodaySol: spent });
+ if (!decision.act) continue;
+ if (await alreadyActed(watch.agent_id, coin.mint, cfg.network)) continue;
+ const res = await executeAction({ cfg, watch, coin, size: decision.size, reason: decision.reason });
+ if (res.status === 'filled') { acted += 1; open += 1; spent += decision.size; }
+ }
+ }
+ if (acted) log.info(`agent loop: ${acted} action(s) across ${watches.length} armed agent(s)`);
+ return acted;
+}
diff --git a/workers/oracle/config.js b/workers/oracle/config.js
new file mode 100644
index 000000000..294e9ad28
--- /dev/null
+++ b/workers/oracle/config.js
@@ -0,0 +1,31 @@
+// Oracle worker — config. Validated once at boot; live mode demands the secrets
+// needed to load agent wallets and sign, so a misconfigured live deploy fails
+// loud instead of silently never trading.
+
+import { env } from '../../api/_lib/env.js';
+
+const num = (v, d) => (Number.isFinite(Number(v)) ? Number(v) : d);
+
+export function loadConfig() {
+ const mode = (process.env.ORACLE_MODE || 'simulate').toLowerCase() === 'live' ? 'live' : 'simulate';
+ const network = (process.env.ORACLE_NETWORK || 'mainnet').toLowerCase() === 'devnet' ? 'devnet' : 'mainnet';
+
+ const cfg = {
+ mode,
+ network,
+ globalKill: process.env.ORACLE_GLOBAL_KILL === '1',
+ scoreIntervalMs: num(process.env.ORACLE_SCORE_INTERVAL_MS, 15_000),
+ agentIntervalMs: num(process.env.ORACLE_AGENT_INTERVAL_MS, 3_000),
+ scoreBatch: num(process.env.ORACLE_SCORE_BATCH, 20),
+ rescoreAfterSec: num(process.env.ORACLE_RESCORE_AFTER_SEC, 180),
+ // Hard ceiling on any single live action, regardless of a watch's config —
+ // a server-side backstop the owner UI can't exceed.
+ maxTradeSolHardCap: num(process.env.ORACLE_MAX_TRADE_SOL, 0.25),
+ };
+
+ if (!env.DATABASE_URL) throw new Error('[oracle] DATABASE_URL is required');
+ if (cfg.mode === 'live' && !env.JWT_SECRET) {
+ throw new Error('[oracle] live mode requires JWT_SECRET (to decrypt agent wallets)');
+ }
+ return cfg;
+}
diff --git a/workers/oracle/executor.js b/workers/oracle/executor.js
new file mode 100644
index 000000000..960880734
--- /dev/null
+++ b/workers/oracle/executor.js
@@ -0,0 +1,121 @@
+// Oracle worker — action executor.
+//
+// Turns an approved decision into a logged action. Simulate mode (the default)
+// records a realistic action row — entry market cap, conviction, size — and
+// spends nothing, so an owner can watch their agent work risk-free. Live mode
+// loads the agent's own custodial keypair, builds a pump.fun buy via the same
+// PumpTradeClient the production sniper uses, signs, and broadcasts — guarded by
+// a hard per-trade SOL cap and full error capture so a bad fill logs 'failed'
+// rather than crashing the loop.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+import { loadAgentKeypair } from './keys.js';
+
+const LAMPORTS = 1e9;
+
+/**
+ * @param {object} args
+ * @param {object} args.cfg worker config
+ * @param {object} args.watch armed watch row (agent_id, user_id, mode, ...)
+ * @param {object} args.coin scored coin { mint, symbol, score, tier }
+ * @param {number} args.size SOL to commit
+ * @param {string} args.reason decision reason
+ * @returns {Promise<{status:string, sig?:string}>}
+ */
+export async function executeAction({ cfg, watch, coin, size, reason }) {
+ const liveRequested = watch.mode === 'live' && cfg.mode === 'live';
+ const cappedSize = Math.min(size, cfg.maxTradeSolHardCap);
+ const entryMc = await entryMarketCap(coin.mint, cfg.network);
+
+ // Claim the slot first (idempotent-ish): one action row per attempt.
+ const base = {
+ agent_id: watch.agent_id, user_id: watch.user_id || null, network: cfg.network,
+ mint: coin.mint, symbol: coin.symbol || null,
+ conviction: coin.score, tier: coin.tier,
+ mode: liveRequested ? 'live' : 'simulate', size_sol: cappedSize,
+ reason, entry_mc_usd: entryMc,
+ };
+
+ if (!liveRequested) {
+ await insertAction({ ...base, status: 'filled', tx_signature: null });
+ log.info(`SIMULATE buy ${coin.symbol || coin.mint.slice(0, 6)} @ conviction ${coin.score} (${cappedSize} SOL)`);
+ return { status: 'filled' };
+ }
+
+ // ── live ─────────────────────────────────────────────────────────────────
+ try {
+ const keys = await loadAgentKeypair(watch.agent_id, watch.user_id, 'oracle_buy');
+ if (!keys) {
+ await insertAction({ ...base, status: 'skipped', tx_signature: null, reason: 'agent has no Solana wallet' });
+ return { status: 'skipped' };
+ }
+ const sig = await buyOnPump({ network: cfg.network, mint: coin.mint, solAmount: cappedSize, payer: keys.keypair });
+ await insertAction({ ...base, status: 'filled', tx_signature: sig });
+ log.info(`LIVE buy ${coin.symbol || coin.mint.slice(0, 6)} ${sig}`);
+ return { status: 'filled', sig };
+ } catch (err) {
+ await insertAction({ ...base, status: 'failed', tx_signature: null, reason: `${reason} | exec: ${err.message}`.slice(0, 300) });
+ log.warn(`LIVE buy failed ${coin.mint}: ${err.message}`);
+ return { status: 'failed' };
+ }
+}
+
+async function insertAction(a) {
+ await sql`
+ insert into oracle_watch_actions
+ (agent_id, user_id, network, mint, symbol, conviction, tier, mode, size_sol, status, reason, entry_mc_usd, tx_signature, outcome)
+ values
+ (${a.agent_id}, ${a.user_id}, ${a.network}, ${a.mint}, ${a.symbol}, ${a.conviction}, ${a.tier},
+ ${a.mode}, ${a.size_sol}, ${a.status}, ${a.reason || null}, ${a.entry_mc_usd || null}, ${a.tx_signature || null}, 'open')
+ `;
+}
+
+async function entryMarketCap(mint, network) {
+ try {
+ const r = await sql`select last_market_cap_usd from pump_coin_outcomes where mint = ${mint} limit 1`;
+ if (r[0]?.last_market_cap_usd) return Number(r[0].last_market_cap_usd);
+ } catch { /* table may be absent */ }
+ return null;
+}
+
+/**
+ * Build + sign + send a pump.fun buy from the agent's keypair. Uses the same
+ * PumpTradeClient the production trade path uses. Lazy-imports the heavy SDK so
+ * the worker boots fast and simulate-only deploys never load it.
+ */
+async function buyOnPump({ network, mint, solAmount, payer }) {
+ const { getPumpTradeClient } = await import('../../api/_lib/pump.js');
+ const { client, connection, BN, web3 } = await getPumpTradeClient({ network });
+ const { PublicKey, VersionedTransaction, TransactionMessage } = web3;
+
+ const user = payer.publicKey;
+ const quoteAmount = new BN(Math.round(solAmount * LAMPORTS));
+ const ixs = await client.buildBuyInstructions({
+ mint: new PublicKey(mint),
+ user,
+ quoteAmount,
+ slippagePct: 10,
+ });
+
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ const msg = new TransactionMessage({ payerKey: user, recentBlockhash: blockhash, instructions: ixs }).compileToV0Message();
+ const tx = new VersionedTransaction(msg);
+ tx.sign([payer]);
+ const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });
+ await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+ return sig;
+}
+
+/** Open positions + today's committed SOL for an agent — feeds the decision caps. */
+export async function agentBudget(agentId, network) {
+ const rows = await sql`
+ select
+ count(*) filter (where outcome = 'open' and status in ('filled','taken'))::int as open_count,
+ coalesce(sum(size_sol) filter (where acted_at > now() - interval '24 hours' and status in ('filled','taken')), 0)::numeric as spent_today
+ from oracle_watch_actions
+ where agent_id = ${agentId} and network = ${network}
+ `.catch(() => [{ open_count: 0, spent_today: 0 }]);
+ const r = rows[0] || {};
+ return { openCount: Number(r.open_count) || 0, spentTodaySol: Number(r.spent_today) || 0 };
+}
diff --git a/workers/oracle/index.js b/workers/oracle/index.js
new file mode 100644
index 000000000..6e87faae2
--- /dev/null
+++ b/workers/oracle/index.js
@@ -0,0 +1,43 @@
+// Oracle worker — entry point.
+//
+// A long-lived Node process (deploy alongside the other workers, NOT a Vercel
+// function). Two cooperating loops:
+// 1. score loop — keeps oracle_conviction warm from the data brain.
+// 2. agent loop — acts on fresh verdicts for every armed agent watch.
+//
+// ORACLE_MODE=simulate|live (default simulate — no real spend)
+// ORACLE_NETWORK=mainnet|devnet
+// ORACLE_GLOBAL_KILL=1 halts all agent actions (scoring continues)
+//
+// Run: node workers/oracle/index.js (or `npm run worker:oracle`)
+
+import { loadConfig } from './config.js';
+import { log } from './log.js';
+import { runScorePass } from './score-loop.js';
+import { runAgentPass } from './agent-loop.js';
+
+async function main() {
+ const cfg = loadConfig();
+ log.info(`starting — mode=${cfg.mode} network=${cfg.network} score=${cfg.scoreIntervalMs}ms agent=${cfg.agentIntervalMs}ms${cfg.globalKill ? ' [KILL]' : ''}`);
+
+ let stopped = false;
+ const stop = (sig) => { log.info(`${sig} — shutting down`); stopped = true; setTimeout(() => process.exit(0), 200); };
+ process.on('SIGINT', () => stop('SIGINT'));
+ process.on('SIGTERM', () => stop('SIGTERM'));
+ process.on('unhandledRejection', (e) => log.error('unhandledRejection:', e?.message || e));
+
+ // Independent self-scheduling loops so a slow score pass never blocks acting.
+ const loop = (name, fn, interval) => {
+ const tick = async () => {
+ if (stopped) return;
+ try { await fn(cfg); } catch (e) { log.error(`${name} pass threw:`, e?.message || e); }
+ if (!stopped) setTimeout(tick, interval);
+ };
+ tick();
+ };
+
+ loop('score', runScorePass, cfg.scoreIntervalMs);
+ loop('agent', runAgentPass, cfg.agentIntervalMs);
+}
+
+main().catch((e) => { log.error('fatal:', e?.message || e); process.exit(1); });
diff --git a/workers/oracle/keys.js b/workers/oracle/keys.js
new file mode 100644
index 000000000..75c7eacbb
--- /dev/null
+++ b/workers/oracle/keys.js
@@ -0,0 +1,43 @@
+// Oracle worker — agent keypair loading for live execution.
+//
+// Mirrors the sniper's approach: an agent's Solana secret is stored encrypted in
+// agent_identities.meta and only decrypted at trade time via the audited
+// recoverSolanaAgentKeypair. Cached briefly so a burst of actions for the same
+// agent doesn't re-decrypt on every fill.
+
+import { sql } from '../../api/_lib/db.js';
+import { recoverSolanaAgentKeypair } from '../../api/_lib/agent-wallet.js';
+
+const CACHE_TTL_MS = 60_000;
+const cache = new Map(); // agentId -> { keypair, address, at }
+
+/**
+ * Load (and briefly cache) an agent's Solana keypair. Returns null when the
+ * agent has no wallet provisioned.
+ * @param {string} agentId
+ * @param {string|null} userId
+ * @param {string} reason audit reason
+ */
+export async function loadAgentKeypair(agentId, userId, reason = 'oracle_buy') {
+ const hit = cache.get(agentId);
+ if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit;
+
+ const rows = await sql`
+ select meta, user_id from agent_identities where id = ${agentId} and deleted_at is null limit 1
+ `;
+ const row = rows[0];
+ if (!row) return null;
+ const meta = row.meta || {};
+ if (!meta.encrypted_solana_secret) return null;
+
+ const keypair = await recoverSolanaAgentKeypair(meta.encrypted_solana_secret, {
+ agentId,
+ userId: userId || row.user_id,
+ reason,
+ });
+ const entry = { keypair, address: meta.solana_address || keypair.publicKey?.toBase58?.(), at: Date.now() };
+ cache.set(agentId, entry);
+ return entry;
+}
+
+export function clearKeyCache() { cache.clear(); }
diff --git a/workers/oracle/log.js b/workers/oracle/log.js
new file mode 100644
index 000000000..c779708ed
--- /dev/null
+++ b/workers/oracle/log.js
@@ -0,0 +1,7 @@
+// Oracle worker — minimal structured logger. No deps; timestamps + level prefix.
+const ts = () => new Date().toISOString();
+export const log = {
+ info: (...a) => console.log(`[oracle ${ts()}]`, ...a),
+ warn: (...a) => console.warn(`[oracle ${ts()}] WARN`, ...a),
+ error: (...a) => console.error(`[oracle ${ts()}] ERROR`, ...a),
+};
diff --git a/workers/oracle/score-loop.js b/workers/oracle/score-loop.js
new file mode 100644
index 000000000..63b7bd6ea
--- /dev/null
+++ b/workers/oracle/score-loop.js
@@ -0,0 +1,42 @@
+// Oracle worker — scoring augmentor.
+//
+// Walks the data brain's recent coins and ensures each has a fresh fused
+// conviction verdict cached in oracle_conviction (classifying its narrative on
+// first sight). This is what keeps the live feed warm and the agent loop fed.
+// It does NOT ingest raw pump.fun data — the brain already has full coverage; it
+// only adds the fusion + cultural read on top.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+import { scoreCoin } from '../../api/_lib/oracle/store.js';
+
+/** Mints that need (re)scoring: recent brain coins missing or stale in our cache. */
+async function pendingMints(cfg) {
+ const rows = await sql`
+ select i.mint
+ from pump_coin_intel i
+ left join oracle_conviction c on c.mint = i.mint and c.network = ${cfg.network}
+ where i.network = ${cfg.network}
+ and i.first_seen_at > now() - interval '12 hours'
+ and (c.mint is null or c.scored_at < now() - (${cfg.rescoreAfterSec} || ' seconds')::interval)
+ order by i.first_seen_at desc
+ limit ${cfg.scoreBatch}
+ `.catch((e) => { log.warn('pendingMints query failed:', e.message); return []; });
+ return rows.map((r) => r.mint);
+}
+
+export async function runScorePass(cfg) {
+ const mints = await pendingMints(cfg);
+ if (!mints.length) return 0;
+ let ok = 0;
+ for (const mint of mints) {
+ try {
+ const r = await scoreCoin(mint, { network: cfg.network, classify: true, persist: true });
+ if (r) ok += 1;
+ } catch (e) {
+ log.warn(`score ${mint} failed:`, e.message);
+ }
+ }
+ if (ok) log.info(`scored ${ok}/${mints.length} coins`);
+ return ok;
+}