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 trader leaderboard + arena play page, coin-intel API; fold detectors into intel

nirholasf9217770a84c
diff --git a/api/pump/intel.js b/api/pump/intel.js
new file mode 100644
index 000000000..6e4e84a8e
--- /dev/null
+++ b/api/pump/intel.js
@@ -0,0 +1,474 @@
+// GET /api/pump/intel
+// --------------------
+// Read surface for the Coin Intelligence engine. The engine
+// (workers/agent-sniper/intel) watches every pump.fun launch, classifies it,
+// aggregates its opening trades into per-wallet stats, derives organic-vs-bundle
+// signals + a 0..100 quality score, and labels outcomes after the fact. It WRITES
+// pump_coin_intel / pump_coin_wallets / pump_coin_outcomes / pump_intel_weights.
+// This endpoint READS them for the /coin-intel dashboard and any agent that wants
+// the same intelligence the sniper trades on — nothing here writes.
+//
+// Views (query param `view`, default `feed`):
+// ?mint=<mint> one coin: classification + signals + outcome + top wallets (bubble-map)
+// ?view=feed recent observed coins, newest first (filters: category, minQuality, verdict, q)
+// ?view=leaderboard highest-quality recent coins + confirmed winners (graduated/pumped)
+// ?view=learning learned per-signal weights + outcome distribution (what the model learned)
+//
+// Public, cacheable briefly. No auth — this is read-only market intelligence.
+// Degrades gracefully (200 with degraded:true) if the engine tables don't exist
+// yet, so the dashboard can render its "engine warming up" state instead of 500ing.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+
+const num = (v) => {
+ if (v == null) return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+};
+const sol = (lamports) => {
+ const n = num(lamports);
+ return n == null ? null : n / LAMPORTS_PER_SOL;
+};
+const round = (x, p = 4) => {
+ if (x == null || !Number.isFinite(x)) return null;
+ const f = 10 ** p;
+ return Math.round(x * f) / f;
+};
+
+// Human verdict derived from the transparent quality score + hard risk flags.
+// Hard flags (a coordinated launch, a dev dump, a single whale owning the float)
+// force "avoid" regardless of score — those are the ones that lose money.
+const HARD_FLAGS = ['bundle_launch', 'dev_dumped', 'single_whale'];
+function deriveVerdict(qualityScore, riskFlags) {
+ const flags = Array.isArray(riskFlags) ? riskFlags : [];
+ const q = num(qualityScore) ?? 0;
+ const hard = flags.some((f) => HARD_FLAGS.includes(f));
+ if (hard || q < 25) return { key: 'avoid', label: 'Avoid', tone: 'danger' };
+ if (q < 50 || flags.length) return { key: 'caution', label: 'Caution', tone: 'warn' };
+ if (q < 72) return { key: 'watch', label: 'Watch', tone: 'neutral' };
+ return { key: 'strong', label: 'Strong', tone: 'success' };
+}
+
+// Classify one trader within a single coin's order book / holder list, from its
+// footprint on that coin. Labels stack — a wallet can be both a sniper and a whale.
+// creator — the coin's deployer
+// bundled — shares a SOL funder with ≥1 other buyer (coordinated launch wallet)
+// sniper — first trade landed within seconds of the coin appearing
+// whale — captured a large share of buy volume
+// dumped — sold ~all of what it bought (paper hands / exit)
+// holding — bought and never sold (diamond)
+// flipped — bought and partially sold
+function classifyWalletInCoin(w, { coinSeenMs, bundledClusters }) {
+ const labels = [];
+ if (w.is_creator) labels.push('creator');
+ if (w.cluster != null && bundledClusters.has(w.cluster)) labels.push('bundled');
+ if (coinSeenMs && w.first_seen_at && (w.buy_count || 0) > 0) {
+ const delta = new Date(w.first_seen_at).getTime() - coinSeenMs;
+ if (delta >= -2000 && delta <= 6000) labels.push('sniper');
+ }
+ if ((w.share || 0) >= 0.15) labels.push('whale');
+ const buy = w.buy_sol || 0;
+ const sellv = w.sell_sol || 0;
+ if ((w.sell_count || 0) === 0 && (w.buy_count || 0) > 0) labels.push('holding');
+ else if ((w.sell_count || 0) > 0 && sellv >= buy * 0.8) labels.push('dumped');
+ else if ((w.sell_count || 0) > 0) labels.push('flipped');
+ return labels;
+}
+
+// Shape a pump_coin_intel row into a stable JSON record for the UI/agents.
+function shapeCoin(r) {
+ const signals = r.signals && typeof r.signals === 'object' ? r.signals : {};
+ const riskFlags = Array.isArray(r.risk_flags) ? r.risk_flags : [];
+ const tags = Array.isArray(r.tags) ? r.tags : [];
+ const qualityScore = num(r.quality_score);
+ const firstSeenMs = r.first_seen_at ? new Date(r.first_seen_at).getTime() : null;
+ return {
+ mint: r.mint,
+ network: r.network || 'mainnet',
+ symbol: r.symbol || null,
+ name: r.name || null,
+ creator: r.creator || null,
+ image_uri: r.image_uri || null,
+ description: r.description || null,
+ twitter: r.twitter || null,
+ telegram: r.telegram || null,
+ website: r.website || null,
+ has_socials: !!(r.twitter || r.telegram || r.website),
+
+ // classification — the "what kind of coin is this" answer
+ category: r.category || 'unknown',
+ tags,
+ narrative: r.narrative || null,
+ is_news_meme: tags.includes('news') || r.category === 'news',
+ classify_confidence: num(r.classify_confidence),
+ classify_source: r.classify_source || null,
+
+ // scores
+ quality_score: qualityScore,
+ verdict: deriveVerdict(qualityScore, riskFlags),
+ risk_flags: riskFlags,
+
+ // headline signals (0..1) the UI charts directly
+ organic_score: round(num(r.organic_score)),
+ bundle_score: round(num(r.bundle_score)),
+ snipe_ratio: round(num(r.snipe_ratio)),
+ concentration_top10: round(num(r.concentration_top10)),
+ concentration_top1: round(num(signals.concentration_top1)),
+ coordination_score: round(num(signals.coordination_score)),
+ timing_entropy: round(num(signals.timing_entropy)),
+ fresh_wallet_ratio: round(num(r.fresh_wallet_ratio)),
+ bubblemap_connectivity: round(num(r.bubblemap_connectivity)),
+
+ // trade footprint
+ dev_buy_sol: round(sol(r.dev_buy_lamports)),
+ dev_sold: !!r.dev_sold,
+ unique_buyers: num(r.unique_buyers) ?? 0,
+ unique_sellers: num(r.unique_sellers) ?? 0,
+ buy_count: num(r.buy_count) ?? 0,
+ sell_count: num(r.sell_count) ?? 0,
+ buy_volume_sol: round(sol(r.buy_volume_lamports)),
+ sell_volume_sol: round(sol(r.sell_volume_lamports)),
+ largest_buy_sol: round(sol(r.largest_buy_lamports)),
+ buy_sell_ratio: num(signals.buy_sell_ratio),
+
+ observation_seconds: num(r.observation_seconds),
+ first_seen_at: r.first_seen_at || null,
+ first_seen_at_ms: firstSeenMs,
+ created_at: r.created_at || null,
+
+ // full structured signals for the detail drawer (already JSON)
+ signals,
+ };
+}
+
+// Stable column projection — explicit so added engine columns never break us and
+// missing ones surface as a clean error we can degrade on.
+const COIN_COLS = sql`
+ mint, network, symbol, name, creator, image_uri, description, twitter, telegram, website,
+ created_at, first_seen_at, observation_seconds,
+ dev_buy_lamports, dev_sold, buy_count, sell_count,
+ buy_volume_lamports, sell_volume_lamports, unique_buyers, unique_sellers, largest_buy_lamports,
+ signals, bundle_score, organic_score, snipe_ratio, concentration_top10,
+ fresh_wallet_ratio, bubblemap_connectivity, quality_score, risk_flags,
+ category, tags, narrative, classify_confidence, classify_source
+`;
+
+// ── one coin: full intel + outcome + wallet bubble-map ───────────────────────
+async function getCoin(mint, network) {
+ const [row] = await sql`
+ select ${COIN_COLS} from pump_coin_intel
+ where mint = ${mint} and network = ${network} limit 1
+ `;
+ if (!row) return { found: false };
+
+ const coin = shapeCoin(row);
+
+ // Outcome (labeled after the fact — may not exist yet).
+ let outcome = null;
+ try {
+ const [o] = await sql`
+ select outcome, graduated, rugged, ath_market_cap_usd, ath_multiple, last_market_cap_usd, labeled_at
+ from pump_coin_outcomes where mint = ${mint} limit 1
+ `;
+ if (o) {
+ outcome = {
+ outcome: o.outcome || 'unknown',
+ graduated: o.graduated,
+ rugged: o.rugged,
+ ath_market_cap_usd: num(o.ath_market_cap_usd),
+ ath_multiple: round(num(o.ath_multiple), 2),
+ last_market_cap_usd: num(o.last_market_cap_usd),
+ labeled_at: o.labeled_at || null,
+ };
+ }
+ } catch { /* outcomes table absent — fine */ }
+
+ // Top wallets → classified order-book/holder list + bubble-map. Cluster by
+ // shared SOL funder (bubblemaps-lite) and label each trader by behavior.
+ let wallets = [];
+ let clusters = [];
+ try {
+ const rows = await sql`
+ select wallet, buy_count, sell_count, buy_lamports, sell_lamports, is_creator, funder, first_seen_at
+ from pump_coin_wallets where mint = ${mint}
+ order by buy_lamports desc limit 80
+ `;
+ const funderToCluster = new Map();
+ wallets = rows.map((w) => {
+ const buySol = sol(w.buy_lamports) ?? 0;
+ const sellSol = sol(w.sell_lamports) ?? 0;
+ const netSol = Math.max(0, buySol - sellSol);
+ let cluster = null;
+ if (w.funder) {
+ if (!funderToCluster.has(w.funder)) funderToCluster.set(w.funder, funderToCluster.size);
+ cluster = funderToCluster.get(w.funder);
+ }
+ return {
+ wallet: w.wallet,
+ is_creator: !!w.is_creator,
+ buy_sol: round(buySol),
+ sell_sol: round(sellSol),
+ net_sol: round(netSol),
+ buy_count: num(w.buy_count) ?? 0,
+ sell_count: num(w.sell_count) ?? 0,
+ funder: w.funder || null,
+ cluster,
+ first_seen_at: w.first_seen_at || null,
+ };
+ });
+ // Summarize multi-wallet funder clusters (the bundle tell, visualized).
+ const byCluster = new Map();
+ for (const w of wallets) {
+ if (w.cluster == null) continue;
+ const c = byCluster.get(w.cluster) || { cluster: w.cluster, funder: w.funder, wallets: 0, net_sol: 0 };
+ c.wallets++;
+ c.net_sol = round((c.net_sol || 0) + (w.net_sol || 0));
+ byCluster.set(w.cluster, c);
+ }
+ clusters = [...byCluster.values()].filter((c) => c.wallets >= 2).sort((a, b) => b.wallets - a.wallets);
+
+ // Classify each trader in this coin's book/holder list.
+ const bundledClusters = new Set(clusters.map((c) => c.cluster));
+ const totalBuy = wallets.reduce((s, w) => s + (w.buy_sol || 0), 0) || 1;
+ const coinSeenMs = coin.first_seen_at_ms;
+ for (const w of wallets) {
+ w.share = round((w.buy_sol || 0) / totalBuy);
+ w.labels = classifyWalletInCoin(w, { coinSeenMs, bundledClusters });
+ }
+ } catch { /* wallets table absent — fine */ }
+
+ return { found: true, coin, outcome, wallets, clusters };
+}
+
+// ── recent feed (the live radar) ─────────────────────────────────────────────
+async function getFeed({ network, limit, category, minQuality, verdict, q }) {
+ const cap = Math.max(1, Math.min(120, limit || 60));
+ const rows = await sql`
+ select ${COIN_COLS} from pump_coin_intel
+ where network = ${network}
+ and (${category}::text is null or category = ${category})
+ and (${minQuality}::int is null or quality_score >= ${minQuality})
+ order by first_seen_at desc
+ limit ${cap}
+ `;
+ let coins = rows.map(shapeCoin);
+ if (verdict) coins = coins.filter((c) => c.verdict.key === verdict);
+ if (q) {
+ const needle = q.toLowerCase();
+ coins = coins.filter((c) =>
+ (c.name || '').toLowerCase().includes(needle) ||
+ (c.symbol || '').toLowerCase().includes(needle) ||
+ (c.mint || '').toLowerCase().includes(needle));
+ }
+ return { coins };
+}
+
+// ── leaderboard: best-quality recent + confirmed winners ─────────────────────
+async function getLeaderboard({ network, limit }) {
+ const cap = Math.max(1, Math.min(50, limit || 20));
+ const topRows = await sql`
+ select ${COIN_COLS} from pump_coin_intel
+ where network = ${network} and quality_score is not null
+ and first_seen_at >= now() - interval '24 hours'
+ order by quality_score desc, first_seen_at desc
+ limit ${cap}
+ `;
+ let winners = [];
+ try {
+ const winRows = await sql`
+ select ${sql`i.mint, i.network, i.symbol, i.name, i.creator, i.image_uri, i.description,
+ i.twitter, i.telegram, i.website, i.created_at, i.first_seen_at, i.observation_seconds,
+ i.dev_buy_lamports, i.dev_sold, i.buy_count, i.sell_count, i.buy_volume_lamports,
+ i.sell_volume_lamports, i.unique_buyers, i.unique_sellers, i.largest_buy_lamports,
+ i.signals, i.bundle_score, i.organic_score, i.snipe_ratio, i.concentration_top10,
+ i.fresh_wallet_ratio, i.bubblemap_connectivity, i.quality_score, i.risk_flags,
+ i.category, i.tags, i.narrative, i.classify_confidence, i.classify_source`}
+ from pump_coin_intel i
+ join pump_coin_outcomes o on o.mint = i.mint
+ where i.network = ${network} and o.outcome in ('graduated','pumped')
+ order by o.ath_multiple desc nulls last, o.labeled_at desc
+ limit ${cap}
+ `;
+ winners = winRows.map(shapeCoin);
+ } catch { /* outcomes absent — no winners yet */ }
+ return { top: topRows.map(shapeCoin), winners };
+}
+
+// ── traders: classify external wallets across every observed coin ────────────
+// Aggregates the per-coin wallet ledger into a cross-coin reputation per trader,
+// then labels it. win_rate is real: of the coins this wallet bought, the share
+// that graduated or pumped (only counted once ≥3 of its coins are labeled).
+// smart_money — proven win-rate across enough labeled coins
+// whale — large lifetime buy volume
+// serial — trades a high number of distinct coins
+// creator — has deployed at least one observed coin
+async function getTraders({ network, limit }) {
+ const cap = Math.max(1, Math.min(100, limit || 40));
+ let traders = [];
+ try {
+ const rows = await sql`
+ select w.wallet,
+ count(distinct w.mint)::int as coins,
+ sum(w.buy_lamports)::numeric as buy_lamports,
+ sum(w.sell_lamports)::numeric as sell_lamports,
+ sum(w.buy_count)::int as buys,
+ sum(w.sell_count)::int as sells,
+ bool_or(w.is_creator) as ever_creator,
+ count(distinct w.mint) filter (where o.outcome in ('graduated','pumped'))::int as wins,
+ count(distinct w.mint) filter (where o.outcome is not null and o.outcome <> 'unknown')::int as labeled
+ from pump_coin_wallets w
+ join pump_coin_intel i on i.mint = w.mint and i.network = ${network}
+ left join pump_coin_outcomes o on o.mint = w.mint
+ where w.buy_count > 0
+ group by w.wallet
+ having count(distinct w.mint) >= 2
+ order by sum(w.buy_lamports) desc
+ limit ${cap}
+ `;
+ traders = rows.map((r) => {
+ const buySol = sol(r.buy_lamports) ?? 0;
+ const sellSol = sol(r.sell_lamports) ?? 0;
+ const labeled = num(r.labeled) ?? 0;
+ const wins = num(r.wins) ?? 0;
+ const coins = num(r.coins) ?? 0;
+ const winRate = labeled >= 1 ? round(wins / labeled, 3) : null;
+ const labels = [];
+ if (r.ever_creator) labels.push('creator');
+ if (labeled >= 3 && winRate != null && winRate >= 0.5) labels.push('smart_money');
+ if (buySol >= 50) labels.push('whale');
+ if (coins >= 10) labels.push('serial');
+ if (!labels.length) labels.push('active');
+ return {
+ wallet: r.wallet,
+ coins,
+ buy_sol: round(buySol),
+ sell_sol: round(sellSol),
+ net_sol: round(Math.max(0, buySol - sellSol)),
+ buys: num(r.buys) ?? 0,
+ sells: num(r.sells) ?? 0,
+ wins,
+ labeled,
+ win_rate: winRate,
+ labels,
+ };
+ });
+ } catch { /* wallets/intel absent — fine */ }
+ return { traders };
+}
+
+// ── learning: weights + outcome distribution + coverage ──────────────────────
+async function getLearning({ network }) {
+ let weights = null;
+ let sampleSize = 0;
+ let trainedAt = null;
+ try {
+ const [w] = await sql`
+ select weights, sample_size, trained_at from pump_intel_weights
+ where network = ${network} order by trained_at desc limit 1
+ `;
+ if (w) {
+ weights = w.weights || null;
+ sampleSize = num(w.sample_size) ?? 0;
+ trainedAt = w.trained_at || null;
+ }
+ } catch { /* weights absent */ }
+
+ let outcomes = [];
+ try {
+ const rows = await sql`
+ select outcome, count(*)::int as n,
+ round(avg(ath_multiple)::numeric, 2) as avg_multiple
+ from pump_coin_outcomes group by outcome
+ `;
+ outcomes = rows.map((r) => ({ outcome: r.outcome, count: num(r.n) ?? 0, avg_multiple: num(r.avg_multiple) }));
+ } catch { /* outcomes absent */ }
+
+ let coverage = { observed: 0, classified: 0, labeled: 0, by_category: [] };
+ try {
+ const [c] = await sql`
+ select
+ count(*)::int as observed,
+ count(*) filter (where classify_source is not null)::int as classified,
+ (select count(*)::int from pump_coin_outcomes) as labeled
+ from pump_coin_intel where network = ${network}
+ `;
+ const cats = await sql`
+ select category, count(*)::int as n from pump_coin_intel
+ where network = ${network} and category is not null
+ group by category order by n desc
+ `;
+ coverage = {
+ observed: num(c?.observed) ?? 0,
+ classified: num(c?.classified) ?? 0,
+ labeled: num(c?.labeled) ?? 0,
+ by_category: cats.map((r) => ({ category: r.category, count: num(r.n) ?? 0 })),
+ };
+ } catch { /* intel absent */ }
+
+ // Present weights as a sorted, signed list the UI can bar-chart directly.
+ let weightList = [];
+ if (weights && typeof weights === 'object') {
+ weightList = Object.entries(weights)
+ .map(([signal, weight]) => ({ signal, weight: round(num(weight), 4) }))
+ .filter((w) => w.weight != null)
+ .sort((a, b) => Math.abs(b.weight) - Math.abs(a.weight));
+ }
+
+ return { weights: weightList, sample_size: sampleSize, trained_at: trainedAt, outcomes, coverage };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://localhost');
+ const params = url.searchParams;
+ const network = params.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const mint = (params.get('mint') || '').trim();
+ const view = mint ? 'coin' : (params.get('view') || 'feed');
+
+ try {
+ let payload;
+ switch (view) {
+ case 'coin':
+ payload = await getCoin(mint, network);
+ break;
+ case 'leaderboard':
+ payload = await getLeaderboard({ network, limit: parseInt(params.get('limit') || '20', 10) });
+ break;
+ case 'learning':
+ payload = await getLearning({ network });
+ break;
+ case 'traders':
+ payload = await getTraders({ network, limit: parseInt(params.get('limit') || '40', 10) });
+ break;
+ case 'feed':
+ default:
+ payload = await getFeed({
+ network,
+ limit: parseInt(params.get('limit') || '60', 10),
+ category: params.get('category') || null,
+ minQuality: params.get('minQuality') ? parseInt(params.get('minQuality'), 10) : null,
+ verdict: params.get('verdict') || null,
+ q: (params.get('q') || '').trim() || null,
+ });
+ break;
+ }
+ return json(res, 200, { view, network, ...payload, ts: Date.now() },
+ { 'cache-control': 'public, max-age=5, stale-while-revalidate=20' });
+ } catch (err) {
+ // The engine tables may not be migrated in this environment yet. Tell the
+ // dashboard so it shows its "warming up" state rather than a hard failure.
+ const missing = /relation .* does not exist|column .* does not exist/i.test(String(err?.message || ''));
+ if (missing) {
+ return json(res, 200, { view, network, degraded: true, reason: 'engine_tables_pending', ts: Date.now() },
+ { 'cache-control': 'no-store' });
+ }
+ console.error('[pump/intel] query failed', err);
+ return json(res, 200, { view, network, degraded: true, reason: 'query_failed', ts: Date.now() },
+ { 'cache-control': 'no-store' });
+ }
+});
diff --git a/pages/club.html b/pages/club.html
index dd2ab3236..b3de6c6de 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -31,6 +31,14 @@
/>
<meta property="og:url" content="https://three.ws/club" />
+ <!-- Design tokens + canonical button styles so the shared on-chain primer
+ modal (src/shared/onchain-primer.js → Modal) renders on-brand here.
+ This bespoke 3D page skips the global style.css; tokens.css is
+ variables-only and buttons.css targets only `.btn`, so neither touches
+ the club's own UI (it uses `.club-*` classes and no design tokens). -->
+ <link rel="stylesheet" href="/tokens.css" />
+ <link rel="stylesheet" href="/buttons.css" />
+
<style>
:root {
--bg: #060606;
diff --git a/pages/leaderboard.html b/pages/leaderboard.html
new file mode 100644
index 000000000..561a3d736
--- /dev/null
+++ b/pages/leaderboard.html
@@ -0,0 +1,167 @@
+<!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>Trader Leaderboard · three.ws</title>
+ <meta
+ name="description"
+ content="The provable pump.fun trader leaderboard. Every agent ranked by a verifiable on-chain track record — realized P&L, win rate, drawdown — with each number traceable to its transaction. Find the best, copy the best."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/leaderboard" />
+ <meta property="og:title" content="Trader Leaderboard · three.ws" />
+ <meta
+ property="og:description"
+ content="Pump.fun traders ranked by a provable, on-chain track record. Realized P&L, win rate, drawdown — every number traceable to its transaction."
+ />
+ <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="Trader Leaderboard · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Pump.fun traders ranked by a provable, on-chain track record. Find the best, copy the best."
+ />
+ <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/leaderboard.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <link rel="canonical" href="https://three.ws/leaderboard" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Trader Leaderboard","description":"Pump.fun traders ranked by a provable, on-chain track record.","url":"https://three.ws/leaderboard","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <canvas id="lb-field" aria-hidden="true"></canvas>
+
+ <main class="lb-shell" aria-labelledby="lb-title">
+ <section class="lb-hero">
+ <p class="lb-kicker">
+ <span class="lb-live-dot" aria-hidden="true"></span>
+ Provable track records · live on-chain
+ </p>
+ <h1 id="lb-title" class="lb-title">Trader Leaderboard</h1>
+ <p class="lb-sub">
+ Every agent ranked by a track record you can <strong>verify</strong>, not trust — realized P&amp;L,
+ win rate and drawdown, each number traceable to the transaction that made it. Find the best.
+ Copy the best.
+ </p>
+ <dl class="lb-summary" aria-label="Leaderboard summary">
+ <div class="lb-summary-cell">
+ <dt>Ranked traders</dt>
+ <dd id="lb-sum-traders">—</dd>
+ </div>
+ <div class="lb-summary-cell">
+ <dt>Verified</dt>
+ <dd id="lb-sum-verified">—</dd>
+ </div>
+ <div class="lb-summary-cell">
+ <dt>Top realized P&amp;L</dt>
+ <dd id="lb-sum-top">—</dd>
+ </div>
+ <div class="lb-summary-cell">
+ <dt>SOL price</dt>
+ <dd id="lb-sum-sol">—</dd>
+ </div>
+ </dl>
+ </section>
+
+ <section class="lb-controls" aria-label="Leaderboard filters">
+ <div class="lb-seg" role="tablist" aria-label="Time window" id="lb-window">
+ <button class="lb-seg-btn" data-window="24h" role="tab">24h</button>
+ <button class="lb-seg-btn" data-window="7d" role="tab">7d</button>
+ <button class="lb-seg-btn is-active" data-window="30d" role="tab" aria-selected="true">30d</button>
+ <button class="lb-seg-btn" data-window="all" role="tab">All-time</button>
+ </div>
+
+ <div class="lb-control-group">
+ <label class="lb-select-wrap">
+ <span class="lb-select-label">Rank by</span>
+ <select id="lb-sort" class="lb-select" aria-label="Rank by">
+ <option value="score">Trader Score</option>
+ <option value="pnl">Realized P&amp;L</option>
+ <option value="winrate">Win rate</option>
+ <option value="roi">ROI</option>
+ </select>
+ </label>
+
+ <label class="lb-toggle" title="Show only traders who meet the verified track-record bar">
+ <input type="checkbox" id="lb-verified" />
+ <span class="lb-toggle-track" aria-hidden="true"><span class="lb-toggle-thumb"></span></span>
+ <span class="lb-toggle-text">Verified only</span>
+ </label>
+
+ <div class="lb-seg lb-seg-sm" role="tablist" aria-label="Network" id="lb-network">
+ <button class="lb-seg-btn is-active" data-network="mainnet" role="tab" aria-selected="true">Mainnet</button>
+ <button class="lb-seg-btn" data-network="devnet" role="tab">Devnet</button>
+ </div>
+ </div>
+ </section>
+
+ <button type="button" class="lb-howto" id="lb-howto-toggle" aria-expanded="false" aria-controls="lb-howto-body">
+ <span>How the Trader Score works</span>
+ <span class="lb-howto-chev" aria-hidden="true">▾</span>
+ </button>
+ <div class="lb-howto-body" id="lb-howto-body" hidden>
+ <p>
+ A single 0–100 score blends <strong>win rate</strong>, <strong>profit factor</strong>,
+ signed <strong>realized P&amp;L</strong>, <strong>consistency</strong> (return per unit of
+ variance) and <strong>max drawdown</strong> — then regresses toward neutral until a trader has
+ enough closed trades to trust. Fast in-and-out churn is penalized, never rewarded. Losers are
+ counted, never hidden. Open any trader to follow each number to its on-chain transaction.
+ </p>
+ </div>
+
+ <section class="lb-board" aria-label="Ranked traders" aria-busy="true">
+ <div class="lb-board-head" role="row" aria-hidden="true">
+ <span class="lb-col-rank">#</span>
+ <span class="lb-col-trader">Trader</span>
+ <span class="lb-col-num">Score</span>
+ <span class="lb-col-num">Realized P&amp;L</span>
+ <span class="lb-col-num lb-winrate">Win rate</span>
+ <span class="lb-col-num lb-hide-sm">ROI</span>
+ <span class="lb-col-num lb-hide-sm">Max DD</span>
+ <span class="lb-col-num lb-hide-md">Trades</span>
+ <span class="lb-col-act"></span>
+ </div>
+ <div id="lb-rows" class="lb-rows"></div>
+ </section>
+
+ <div id="lb-state" class="lb-state" aria-live="polite"></div>
+
+ <aside class="lb-ticker-wrap" aria-label="Recent closed trades">
+ <h2 class="lb-ticker-title">Latest closes</h2>
+ <div id="lb-ticker" class="lb-ticker"></div>
+ </aside>
+
+ <section class="lb-cta">
+ <div class="lb-cta-inner">
+ <h2>Watch the agents trade live</h2>
+ <p>The Sniper Arena streams every entry and exit as it lands on-chain. The leaderboard is the scoreboard — the arena is the match.</p>
+ <div class="lb-cta-row">
+ <a class="lb-btn lb-btn-primary" href="/play/arena">Open the Arena →</a>
+ <a class="lb-btn" href="/create-agent">Launch your own trader</a>
+ </div>
+ </div>
+ </section>
+ </main>
+
+ <script type="module" src="/src/leaderboard.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/pages/play/arena.html b/pages/play/arena.html
index 545eb2f29..6bfab46ee 100644
--- a/pages/play/arena.html
+++ b/pages/play/arena.html
@@ -2,270 +2,296 @@
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
- <script>/* no-flash theme boot */(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>
- <title>Sniper Arena — autonomous AI agents trading live · three.ws</title>
- <meta name="description" content="Watch three.ws AI agents trade pump.fun autonomously in real time — live P&L leaderboard, every trade verifiable on-chain." />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=1" />
+ <title>Sniper Arena — a live 3D world of AI agents trading pump.fun · three.ws</title>
+ <meta name="description" content="Step into a live 3D world where autonomous AI agents trade pump.fun in real time. Pick your avatar, walk the floor, and watch every trade land on-chain — agents cheer their wins and slump their losses as it happens." />
<meta property="og:title" content="Sniper Arena · three.ws" />
- <meta property="og:description" content="Autonomous 3D AI agents trading pump.fun live. Real wallets, real trades, on-chain proof." />
+ <meta property="og:description" content="A live 3D world of autonomous AI agents trading pump.fun. Pick an avatar, walk in, watch real trades happen — verifiable on-chain." />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/play/arena" />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Sniper Arena — a live 3D world of AI agents trading pump.fun" />
+ <meta name="twitter:description" content="Pick your avatar, walk into a live 3D arena, and watch autonomous AI agents trade pump.fun in real time. Every trade verifiable on-chain." />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+ <link rel="canonical" href="https://three.ws/play/arena" />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="preload" href="/animations/manifest.json" as="fetch" crossorigin />
+ <link rel="preload" href="/avatars/default.glb" as="fetch" crossorigin />
<style>
:root {
- --bg: #07080c; --panel: #0e1018; --panel-2: #141826; --line: #1e2333;
- --ink: #e9edf6; --muted: #8b93a7; --accent: #6ee7ff; --up: #34d399; --down: #f87171;
- --gold: #fbbf24; --radius: 14px;
+ --bg: #06070d; --panel: rgba(14,16,24,0.72); --panel-solid: #0d0f17; --line: rgba(255,255,255,0.09);
+ --ink: #e9edf6; --muted: #8b93a7; --faint: rgba(255,255,255,0.45);
+ --cyan: #6ee7ff; --violet: #9a7bff; --gold: #fbbf24; --up: #34d399; --down: #f87171;
+ --r: 14px; --r-sm: 10px;
+ --mono: ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, monospace;
+ --shadow: 0 18px 50px -20px rgba(0,0,0,0.8), 0 1px 0 rgba(255,255,255,0.05) inset;
+ --blur: saturate(160%) blur(18px);
}
- [data-theme="light"] { --bg:#f6f7fb; --panel:#fff; --panel-2:#f0f2f8; --line:#e3e7f0; --ink:#0d1220; --muted:#5a6478; }
* { box-sizing: border-box; }
- html, body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
- a { color: inherit; }
- .wrap { max-width: 1240px; margin: 0 auto; padding: 20px 18px 80px; }
+ html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--ink);
+ font: 14px/1.5 Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ -webkit-font-smoothing: antialiased; overscroll-behavior: none; }
+ a { color: inherit; text-decoration: none; }
+ button { font: inherit; color: inherit; cursor: pointer; }
+ #scene { position: fixed; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; z-index: 0; }
- /* header */
- .top { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin-bottom: 14px; }
- .brand { font-weight: 700; letter-spacing: -0.02em; font-size: 15px; text-decoration: none; opacity: .85; }
- .brand:hover { opacity: 1; }
- h1 { font-size: clamp(26px, 4vw, 40px); letter-spacing: -0.03em; margin: 6px 0 4px; }
- .sub { color: var(--muted); margin: 0 0 18px; max-width: 60ch; }
- .live-dot { display: inline-flex; align-items: center; gap: 7px; font-size: 12px; color: var(--muted); padding: 5px 10px; border: 1px solid var(--line); border-radius: 999px; }
- .live-dot i { width: 8px; height: 8px; border-radius: 50%; background: var(--down); transition: background .3s; }
- .live-dot.on i { background: var(--up); box-shadow: 0 0 0 0 rgba(52,211,153,.6); animation: pulse 1.8s infinite; }
- @keyframes pulse { 0%{box-shadow:0 0 0 0 rgba(52,211,153,.55)} 70%{box-shadow:0 0 0 7px rgba(52,211,153,0)} 100%{box-shadow:0 0 0 0 rgba(52,211,153,0)} }
+ /* vignette + grain over the canvas for depth */
+ .vignette { position: fixed; inset: 0; z-index: 1; pointer-events: none;
+ background: radial-gradient(130% 100% at 50% 18%, transparent 52%, rgba(0,0,0,0.55) 100%); }
- .disclosure { display: flex; gap: 10px; align-items: flex-start; background: color-mix(in srgb, var(--gold) 9%, var(--panel)); border: 1px solid color-mix(in srgb, var(--gold) 35%, var(--line)); color: var(--ink); padding: 11px 14px; border-radius: 12px; font-size: 13px; margin-bottom: 22px; }
- .disclosure b { color: var(--gold); }
+ /* ── label layer ─────────────────────────────────── */
+ #labels { position: fixed; inset: 0; z-index: 4; pointer-events: none; }
+ .agent-label { position: absolute; top: 0; left: 0; pointer-events: auto;
+ display: inline-flex; align-items: center; gap: 8px; padding: 5px 10px 5px 6px;
+ background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ border: 1px solid var(--line); border-radius: 999px; box-shadow: var(--shadow);
+ white-space: nowrap; transition: opacity .25s, transform .05s linear, border-color .2s;
+ font-size: 12px; will-change: transform; }
+ .agent-label.leader { border-color: color-mix(in srgb, var(--gold) 55%, var(--line)); }
+ .agent-label.active { border-color: var(--cyan); box-shadow: 0 0 0 2px color-mix(in srgb, var(--cyan) 35%, transparent), var(--shadow); transform: translate(-50%,-100%) scale(1.04); }
+ .lbl-rank { font: 600 11px/1 var(--mono); color: var(--faint); min-width: 18px; text-align: center; }
+ .agent-label.leader .lbl-rank { color: var(--gold); }
+ .lbl-av { width: 22px; height: 22px; border-radius: 50%; object-fit: cover; background: #1a1e2c; border: 1px solid var(--line); }
+ .lbl-meta { display: flex; flex-direction: column; line-height: 1.15; text-align: left; }
+ .lbl-name { font-weight: 600; font-size: 12px; max-width: 130px; overflow: hidden; text-overflow: ellipsis; }
+ .lbl-pnl { font: 600 11px/1 var(--mono); }
+ .lbl-pnl.up { color: var(--up); } .lbl-pnl.down { color: var(--down); }
- .grid { display: grid; grid-template-columns: 1.15fr 0.85fr; gap: 18px; align-items: start; }
- @media (max-width: 920px) { .grid { grid-template-columns: 1fr; } }
- .panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; }
- .panel h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 0; padding: 14px 16px; border-bottom: 1px solid var(--line); }
+ /* ── top bar ─────────────────────────────────────── */
+ .bar { position: fixed; top: 0; left: 0; right: 0; z-index: 6; display: flex; align-items: center;
+ gap: 14px; padding: 14px 18px; pointer-events: none;
+ background: linear-gradient(180deg, rgba(6,7,13,0.85), transparent); }
+ .bar > * { pointer-events: auto; }
+ .brand { display: inline-flex; align-items: center; gap: 9px; font-weight: 700; letter-spacing: -0.02em; }
+ .brand img { width: 22px; height: 22px; border-radius: 6px; }
+ .brand small { color: var(--faint); font-weight: 500; }
+ .spacer { flex: 1; }
+ .pill { display: inline-flex; align-items: center; gap: 8px; padding: 7px 13px; border-radius: 999px;
+ border: 1px solid var(--line); background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ font-size: 12.5px; color: var(--muted); transition: border-color .2s, color .2s, background .2s; }
+ .live i { width: 8px; height: 8px; border-radius: 50%; background: var(--down); transition: background .3s; }
+ .live.on i { background: var(--up); box-shadow: 0 0 0 0 rgba(52,211,153,.6); animation: pulse 1.8s infinite; }
+ @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)} }
+ .btn { display: inline-flex; align-items: center; gap: 8px; padding: 9px 15px; border-radius: 999px;
+ border: 1px solid var(--line); background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ font-weight: 600; font-size: 13px; transition: transform .12s, border-color .2s, background .2s; }
+ .btn:hover { transform: translateY(-1px); border-color: color-mix(in srgb, var(--cyan) 50%, var(--line)); }
+ .btn:active { transform: translateY(0) scale(.97); }
+ .btn.primary { background: linear-gradient(135deg, color-mix(in srgb, var(--cyan) 22%, var(--panel)), color-mix(in srgb, var(--violet) 22%, var(--panel))); border-color: color-mix(in srgb, var(--cyan) 40%, var(--line)); color: #fff; }
+ .btn svg { width: 16px; height: 16px; }
- /* hero */
- .hero { display: grid; grid-template-columns: 200px 1fr; gap: 16px; padding: 16px; align-items: center; }
- @media (max-width: 560px) { .hero { grid-template-columns: 1fr; } }
- .hero agent-3d { width: 100%; height: 230px; background: radial-gradient(120% 90% at 50% 10%, #1a2030 0%, var(--panel-2) 70%); border-radius: 12px; display: block; }
- .hero-meta .crown { color: var(--gold); font-size: 12px; letter-spacing: .08em; text-transform: uppercase; }
- .hero-meta h3 { margin: 4px 0 10px; font-size: 22px; letter-spacing: -0.02em; }
- .hero-stat { display: flex; gap: 20px; flex-wrap: wrap; }
- .hero-stat div span { display: block; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .06em; }
- .hero-stat div b { font-size: 20px; font-variant-numeric: tabular-nums; }
+ /* ── side panels ─────────────────────────────────── */
+ .panel { position: fixed; z-index: 5; width: 326px; max-width: calc(100vw - 28px);
+ background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ border: 1px solid var(--line); border-radius: var(--r); box-shadow: var(--shadow); overflow: hidden; }
+ .panel-l { left: 18px; top: 74px; }
+ .panel-r { right: 18px; top: 74px; width: 320px; }
+ .panel h2 { margin: 0; padding: 13px 15px; font-size: 11px; text-transform: uppercase; letter-spacing: .1em;
+ color: var(--faint); border-bottom: 1px solid var(--line); display: flex; align-items: center; justify-content: space-between; }
+
+ /* top agent card */
+ .topcard { display: grid; grid-template-columns: 56px 1fr; gap: 12px; padding: 14px 15px; align-items: center; border-bottom: 1px solid var(--line); }
+ .topcard .crown { grid-column: 1 / -1; font-size: 10.5px; letter-spacing: .1em; text-transform: uppercase; color: var(--gold); display: flex; align-items: center; gap: 6px; }
+ .topcard img { width: 56px; height: 56px; border-radius: 12px; object-fit: cover; background: #161a27; border: 1px solid var(--line); }
+ .topcard .tc-name { font-size: 17px; font-weight: 700; letter-spacing: -0.01em; margin-bottom: 6px; }
+ .topcard .tc-stats { display: flex; gap: 14px; flex-wrap: wrap; }
+ .topcard .tc-stats div span { display: block; font-size: 9.5px; text-transform: uppercase; letter-spacing: .07em; color: var(--faint); }
+ .topcard .tc-stats div b { font: 700 15px/1.2 var(--mono); }
+ .big { font: 800 22px/1 var(--mono); }
+ .up { color: var(--up); } .down { color: var(--down); }
/* leaderboard */
- table { width: 100%; border-collapse: collapse; }
- th, td { text-align: left; padding: 11px 16px; font-variant-numeric: tabular-nums; }
- th { font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); border-bottom: 1px solid var(--line); }
- tbody tr { border-bottom: 1px solid var(--line); transition: background .25s; }
- tbody tr:hover { background: var(--panel-2); }
- .rank { color: var(--muted); width: 28px; }
- .agent-cell { display: flex; align-items: center; gap: 10px; }
- .av { width: 28px; height: 28px; border-radius: 8px; object-fit: cover; background: var(--panel-2); border: 1px solid var(--line); }
- .num.up { color: var(--up); } .num.down { color: var(--down); }
- .tag { font-size: 11px; color: var(--muted); }
+ .board { max-height: min(46vh, 420px); overflow: auto; }
+ .row { display: grid; grid-template-columns: 22px 26px 1fr auto; gap: 9px; align-items: center; width: 100%;
+ padding: 9px 15px; background: none; border: none; border-bottom: 1px solid var(--line); text-align: left; transition: background .18s; }
+ .row:hover { background: rgba(255,255,255,0.04); }
+ .r-rank { font: 600 12px/1 var(--mono); color: var(--faint); }
+ .r-av { width: 26px; height: 26px; border-radius: 8px; object-fit: cover; background: #161a27; border: 1px solid var(--line); }
+ .r-name { font-size: 13px; font-weight: 600; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .r-name small { display: block; font-weight: 400; font-size: 11px; color: var(--faint); }
+ .r-pnl { font: 700 13px/1 var(--mono); }
- /* ticker */
- .ticker { max-height: 540px; overflow: auto; }
- .ev { display: flex; gap: 12px; align-items: center; padding: 11px 16px; border-bottom: 1px solid var(--line); animation: slidein .35s ease; }
- @keyframes slidein { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: none; } }
- .ev .side { font-size: 11px; font-weight: 700; padding: 3px 8px; border-radius: 6px; letter-spacing: .04em; }
- .ev .buy { background: color-mix(in srgb, var(--accent) 16%, transparent); color: var(--accent); }
- .ev .sellw { background: color-mix(in srgb, var(--up) 18%, transparent); color: var(--up); }
- .ev .selll { background: color-mix(in srgb, var(--down) 18%, transparent); color: var(--down); }
- .ev .body { flex: 1; min-width: 0; }
- .ev .body .l1 { display: flex; gap: 8px; align-items: baseline; }
- .ev .body .name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
- .ev .body .l2 { color: var(--muted); font-size: 12px; }
- .ev .pnl { font-variant-numeric: tabular-nums; font-weight: 700; white-space: nowrap; }
- .ev a.proof { font-size: 11px; color: var(--accent); text-decoration: none; opacity: .85; }
- .ev a.proof:hover { opacity: 1; text-decoration: underline; }
+ /* tape */
+ .tape { max-height: min(64vh, 560px); overflow: auto; }
+ .tape-ev { display: flex; gap: 11px; align-items: center; padding: 11px 15px; border-bottom: 1px solid var(--line); }
+ .tape-ev.fresh { animation: slidein .4s cubic-bezier(.22,1,.36,1); }
+ @keyframes slidein { from { opacity: 0; transform: translateX(12px); } to { opacity: 1; transform: none; } }
+ .t-side { font: 700 10.5px/1 var(--mono); padding: 4px 8px; border-radius: 7px; letter-spacing: .03em; white-space: nowrap; }
+ .t-side.buy { background: color-mix(in srgb, var(--cyan) 18%, transparent); color: var(--cyan); }
+ .t-side.win { background: color-mix(in srgb, var(--up) 20%, transparent); color: var(--up); }
+ .t-side.loss { background: color-mix(in srgb, var(--down) 20%, transparent); color: var(--down); }
+ .t-body { flex: 1; min-width: 0; display: flex; flex-direction: column; }
+ .t-l1 { display: flex; gap: 7px; align-items: baseline; min-width: 0; }
+ .t-l1 b { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .t-sym { font-size: 11px; color: var(--faint); }
+ .t-l2 { font-size: 11.5px; color: var(--muted); }
+ .t-l2 a { color: var(--cyan); }
+ .t-pnl { font: 700 12.5px/1 var(--mono); white-space: nowrap; }
- .empty { padding: 40px 20px; text-align: center; color: var(--muted); }
- .empty b { color: var(--ink); display: block; margin-bottom: 6px; }
- .empty a { color: var(--accent); text-decoration: none; }
- .skeleton { height: 14px; border-radius: 6px; background: linear-gradient(90deg, var(--panel-2) 25%, var(--line) 37%, var(--panel-2) 63%); background-size: 400% 100%; animation: sh 1.3s infinite; }
- @keyframes sh { 0%{background-position:100% 0} 100%{background-position:-100% 0} }
+ .empty { padding: 26px 18px; text-align: center; color: var(--muted); font-size: 13px; }
+ .empty b { color: var(--ink); display: block; margin-bottom: 5px; }
+ .empty .btn { margin-top: 12px; }
- .section-gap { margin-top: 18px; }
- </style>
+ /* big-win banner */
+ .banner { position: fixed; left: 50%; bottom: 26px; transform: translate(-50%, 24px); z-index: 7;
+ padding: 12px 20px; border-radius: 999px; background: linear-gradient(135deg, rgba(52,211,153,0.16), rgba(110,231,255,0.14));
+ border: 1px solid color-mix(in srgb, var(--up) 45%, var(--line)); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ box-shadow: var(--shadow); font-size: 14px; opacity: 0; pointer-events: none; max-width: calc(100vw - 36px);
+ transition: opacity .4s, transform .4s cubic-bezier(.22,1,.36,1); }
+ .banner.show { opacity: 1; transform: translate(-50%, 0); pointer-events: auto; }
+ .banner a { color: var(--cyan); }
+
+ /* controls hint */
+ .hint { position: fixed; left: 18px; bottom: 18px; z-index: 5; display: flex; gap: 8px; align-items: center;
+ padding: 8px 13px; border-radius: 999px; background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ border: 1px solid var(--line); color: var(--muted); font-size: 12px; }
+ .hint kbd { font: 600 10.5px/1 var(--mono); background: rgba(255,255,255,0.08); border: 1px solid var(--line); border-radius: 5px; padding: 3px 5px; color: var(--ink); }
+
+ /* loading */
+ .loading { position: fixed; inset: 0; z-index: 9; display: flex; flex-direction: column; gap: 16px; align-items: center; justify-content: center;
+ background: radial-gradient(80% 60% at 50% 40%, #0a0d18, #06070d); color: var(--muted); font-size: 14px; }
+ .loading .ring { width: 38px; height: 38px; border-radius: 50%; border: 3px solid rgba(255,255,255,0.12); border-top-color: var(--cyan); animation: spin .9s linear infinite; }
+ @keyframes spin { to { transform: rotate(360deg); } }
+
+ /* disclosure */
+ .disc { position: fixed; left: 50%; top: 64px; transform: translateX(-50%); z-index: 5;
+ font-size: 11.5px; color: var(--faint); display: flex; gap: 6px; align-items: center; pointer-events: none; }
+ .disc b { color: color-mix(in srgb, var(--gold) 80%, #fff); }
- <link rel="canonical" href="https://three.ws/play/arena">
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="three.ws">
- <meta property="og:url" content="https://three.ws/play/arena">
- <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:title" content="Sniper Arena — autonomous AI agents trading live · three.ws">
- <meta name="twitter:description" content="Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&amp;L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.">
- <meta name="twitter:image" content="https://three.ws/og-image.png">
- <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>
+ /* avatar picker */
+ .picker { position: fixed; inset: 0; z-index: 20; display: none; }
+ .picker.open { display: block; }
+ .pick-backdrop { position: absolute; inset: 0; background: rgba(4,5,9,0.72); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); animation: fade .25s; }
+ @keyframes fade { from { opacity: 0; } }
+ .pick-modal { position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);
+ width: min(760px, calc(100vw - 32px)); max-height: min(80vh, 680px); display: flex; flex-direction: column;
+ background: var(--panel-solid); border: 1px solid var(--line); border-radius: 18px; box-shadow: var(--shadow);
+ animation: rise .3s cubic-bezier(.22,1,.36,1); overflow: hidden; }
+ @keyframes rise { from { opacity: 0; transform: translate(-50%,-46%) scale(.97); } }
+ .pick-head { display: flex; align-items: center; justify-content: space-between; padding: 18px 20px; border-bottom: 1px solid var(--line); }
+ .pick-head h3 { margin: 0; font-size: 18px; letter-spacing: -0.01em; }
+ .pick-head p { margin: 3px 0 0; font-size: 12.5px; color: var(--muted); }
+ .pick-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; }
+ .pick-x:hover { border-color: var(--cyan); }
+ .pick-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); gap: 12px; padding: 18px 20px; overflow: auto; }
+ .pick-sep, .pick-loading { grid-column: 1 / -1; font-size: 11px; text-transform: uppercase; letter-spacing: .1em; color: var(--faint); padding: 8px 2px 2px; }
+ .pick-loading { text-align: center; padding: 18px; }
+ .pick-tile { position: relative; display: flex; flex-direction: column; gap: 8px; padding: 10px; border-radius: 13px;
+ border: 1px solid var(--line); background: rgba(255,255,255,0.02); transition: transform .12s, border-color .15s, background .15s; }
+ .pick-tile:hover { transform: translateY(-2px); border-color: color-mix(in srgb, var(--cyan) 50%, var(--line)); background: rgba(255,255,255,0.05); }
+ .pick-tile.selected { border-color: var(--cyan); box-shadow: 0 0 0 2px color-mix(in srgb, var(--cyan) 30%, transparent); }
+ .pick-tile.busy { opacity: .6; pointer-events: none; }
+ .pick-tile.failed { border-color: var(--down); }
+ .pick-thumb { aspect-ratio: 1; border-radius: 9px; overflow: hidden; background: radial-gradient(120% 100% at 50% 0%, #1b2233, #0d1018); display: grid; place-items: center; }
+ .pick-thumb img { width: 100%; height: 100%; object-fit: cover; }
+ .pick-mono { font: 700 26px/1 var(--mono); color: var(--faint); }
+ .pick-name { font-size: 12.5px; font-weight: 600; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .pick-badge { position: absolute; top: 8px; right: 8px; font: 600 9px/1 var(--mono); text-transform: uppercase; letter-spacing: .06em;
+ padding: 3px 6px; border-radius: 6px; background: color-mix(in srgb, var(--cyan) 20%, transparent); color: var(--cyan); }
+
+ #joystick { display: none; position: fixed; left: 0; bottom: 0; width: 180px; height: 180px; z-index: 8; }
+
+ .toggle-panels { display: none; }
+
+ /* ── responsive ──────────────────────────────────── */
+ @media (max-width: 900px) {
+ .panel-l, .panel-r { top: auto; bottom: 0; left: 0; right: 0; width: 100%; max-width: none; border-radius: 16px 16px 0 0;
+ transform: translateY(calc(100% - 46px)); transition: transform .32s cubic-bezier(.22,1,.36,1); }
+ .panel-r { z-index: 5; }
+ .panel-l { z-index: 6; }
+ body.panels-open .panel-l { transform: translateY(0); }
+ .panel h2 { cursor: pointer; }
+ .board { max-height: 40vh; } .tape { max-height: 32vh; }
+ .disc { display: none; }
+ .hint { display: none; }
+ .toggle-panels { display: inline-flex; }
+ .panel-r { transform: translateY(calc(100% - 46px)); }
+ body.tape-open .panel-r { transform: translateY(0); }
+ }
+ @media (prefers-reduced-motion: reduce) { * { animation-duration: .01ms !important; } }
+ </style>
</head>
<body>
- <div class="wrap">
- <div class="top">
- <a class="brand" href="/play">← three.ws / play</a>
- <span class="live-dot" id="liveDot"><i></i> connecting…</span>
- </div>
-
- <h1>Sniper Arena</h1>
- <p class="sub">Autonomous 3D AI agents trading pump.fun in real time. Every trade is signed by the agent's own wallet and settled on-chain — the leaderboard is the proof.</p>
+ <canvas id="scene"></canvas>
+ <div class="vignette"></div>
+ <div id="labels"></div>
- <div class="disclosure">
- <span>⚠️</span>
- <div><b>Experimental.</b> Agents trade real funds autonomously on a live market. Outcomes are volatile and you can lose the entire balance. Arming an agent is opt-in and capped — nothing here is financial advice.</div>
- </div>
+ <div class="loading" id="loading"><div class="ring"></div><span>Entering the arena…</span></div>
- <div class="grid">
- <div>
- <div class="panel">
- <h2>Top agent — live</h2>
- <div class="hero" id="hero">
- <agent-3d id="heroAvatar" src="/avatars/mannequin.glb" name-plate="" background="transparent" responsive></agent-3d>
- <div class="hero-meta">
- <div class="crown">👑 #1 by realized P&amp;L</div>
- <h3 id="heroName">—</h3>
- <div class="hero-stat">
- <div><span>Realized P&amp;L</span><b id="heroPnl" class="num">—</b></div>
- <div><span>Wins</span><b id="heroWins">—</b></div>
- <div><span>Open</span><b id="heroOpen">—</b></div>
- </div>
- </div>
- </div>
- </div>
+ <!-- top bar -->
+ <div class="bar">
+ <a class="brand" href="/play"><img src="/favicon.ico" alt="" />three.ws <small>/ arena</small></a>
+ <span class="pill live" id="liveDot"><i></i> <span>connecting…</span></span>
+ <div class="spacer"></div>
+ <button class="btn primary" id="pickBtn">
+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="6.5" r="3.2"/><path d="M4 17a6 6 0 0 1 12 0"/></svg>
+ Choose your avatar
+ </button>
+ </div>
- <div class="panel section-gap">
- <h2>Leaderboard</h2>
- <table>
- <thead>
- <tr><th class="rank">#</th><th>Agent</th><th>Realized P&amp;L</th><th>Win rate</th><th>Trades</th></tr>
- </thead>
- <tbody id="board">
- <tr><td colspan="5"><div class="skeleton" style="margin:6px 0"></div></td></tr>
- </tbody>
- </table>
- <div id="boardEmpty" class="empty" hidden>
- <b>No armed agents yet.</b>
- Arm an agent from your <a href="/dashboard">dashboard</a> to enter the arena.
- </div>
- </div>
- </div>
+ <div class="disc">⚠️ <span><b>Experimental.</b> Agents trade real funds autonomously — outcomes are volatile. Not financial advice.</span></div>
- <div class="panel">
- <h2>Live trades</h2>
- <div class="ticker" id="ticker">
- <div class="empty" id="tickerEmpty">Waiting for the next trade…</div>
+ <!-- left: top agent + leaderboard -->
+ <section class="panel panel-l" aria-label="Leaderboard">
+ <h2 id="togglePanels">Live leaderboard <span class="toggle-panels btn" style="padding:3px 9px;font-size:11px">tap ▲</span></h2>
+ <div class="topcard">
+ <div class="crown">👑 #1 by realized P&amp;L</div>
+ <img id="topAv" src="" alt="" style="display:none" />
+ <div>
+ <div class="tc-name" id="topName">—</div>
+ <div class="tc-stats">
+ <div><span>P&amp;L</span><b id="topPnl" class="big">—</b></div>
+ <div><span>Win rate</span><b id="topWr">—</b></div>
+ <div><span>Wins</span><b id="topWins">—</b></div>
+ <div><span>Open</span><b id="topOpen">—</b></div>
</div>
</div>
</div>
- </div>
+ <div class="board" id="board">
+ <div class="empty">Loading agents…</div>
+ </div>
+ <div class="empty" id="emptyState" hidden>
+ <b>No agents are live yet.</b>
+ Be the first — arm a trader and enter the arena.
+ <button class="btn primary" id="emptyPick" style="margin:12px auto 0">Pick an avatar &amp; watch</button>
+ </div>
+ </section>
- <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
- <script type="module">
- const NETWORK = new URLSearchParams(location.search).get('network') || 'mainnet';
- const fmtSol = (n) => (n == null ? '—' : `${n >= 0 ? '+' : ''}${n.toFixed(3)} SOL`);
- const fmtPct = (n) => (n == null ? '' : `${n >= 0 ? '+' : ''}${n.toFixed(1)}%`);
- const cls = (n) => (n == null ? '' : n >= 0 ? 'up' : 'down');
- const esc = (s) => String(s ?? '').replace(/[<>&]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' }[c]));
+ <!-- right: live tape -->
+ <section class="panel panel-r" aria-label="Live trades">
+ <h2>Live trades</h2>
+ <div class="tape" id="tape">
+ <div class="empty" id="tapeEmpty">Waiting for the next trade…</div>
+ </div>
+ </section>
- const el = (id) => document.getElementById(id);
- const heroAvatar = el('heroAvatar');
- let topAgentId = null;
+ <div class="banner" id="banner"></div>
- function renderHero(top) {
- if (!top) return;
- el('heroName').textContent = top.agent_name || 'Agent';
- const pnl = el('heroPnl');
- pnl.textContent = fmtSol(top.realized_pnl_sol);
- pnl.className = 'num ' + cls(top.realized_pnl_sol);
- el('heroWins').textContent = top.wins;
- el('heroOpen').textContent = top.open_positions;
- if (top.agent_id && top.agent_id !== topAgentId) {
- topAgentId = top.agent_id;
- heroAvatar.setAttribute('agent-id', top.agent_id);
- heroAvatar.setAttribute('name-plate', top.agent_name || '');
- }
- }
+ <div class="hint">
+ <kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> move · drag to look · scroll to zoom
+ </div>
- function renderBoard(rows) {
- const body = el('board'), empty = el('boardEmpty');
- if (!rows.length) { body.innerHTML = ''; empty.hidden = false; return; }
- empty.hidden = true;
- body.innerHTML = rows.map((r) => {
- const wr = r.closed ? Math.round((r.wins / r.closed) * 100) : 0;
- return `<tr>
- <td class="rank">${r.rank}</td>
- <td><div class="agent-cell"><img class="av" src="${esc(r.image || '/avatars/mannequin-thumb.png')}" alt="" onerror="this.style.visibility='hidden'"/><div><div>${esc(r.agent_name || 'Agent')}</div><div class="tag">${r.open_positions} open</div></div></div></td>
- <td class="num ${cls(r.realized_pnl_sol)}">${fmtSol(r.realized_pnl_sol)}</td>
- <td>${r.closed ? wr + '%' : '—'}</td>
- <td>${r.closed}</td>
- </tr>`;
- }).join('');
- }
+ <div id="joystick"></div>
- const ticker = el('ticker');
- let tickerCount = 0;
- function pushEvent(kind, p) {
- el('tickerEmpty')?.remove();
- const isSell = kind === 'sell';
- const win = isSell && (p.pnl_sol ?? 0) >= 0;
- const sideCls = !isSell ? 'buy' : win ? 'sellw' : 'selll';
- const sideTxt = !isSell ? 'BUY' : win ? 'SELL ▲' : 'SELL ▼';
- const proofUrl = isSell ? p.sell_url : p.buy_url;
- const pnl = isSell ? `<div class="pnl ${cls(p.pnl_sol)}">${fmtSol(p.pnl_sol)} ${fmtPct(p.pnl_pct)}</div>` : '';
- const row = document.createElement('div');
- row.className = 'ev';
- row.innerHTML = `
- <span class="side ${sideCls}">${sideTxt}</span>
- <div class="body">
- <div class="l1"><span class="name">${esc(p.agent_name || 'Agent')}</span> <span class="tag">${esc(p.symbol || p.name || p.mint?.slice(0, 6))}</span></div>
- <div class="l2">${isSell ? esc(p.exit_reason || 'closed') : `entry ${fmtSol(p.entry_sol)}`} ${proofUrl ? `· <a class="proof" href="${proofUrl}" target="_blank" rel="noopener">on-chain ↗</a>` : '· simulated'}</div>
+ <!-- avatar picker -->
+ <div class="picker" id="picker">
+ <div class="pick-backdrop" id="pickBackdrop"></div>
+ <div class="pick-modal" role="dialog" aria-modal="true" aria-label="Choose your avatar">
+ <div class="pick-head">
+ <div>
+ <h3>Choose your avatar</h3>
+ <p>This is you on the floor — walk it through the arena and watch the agents trade.</p>
</div>
- ${pnl}`;
- ticker.prepend(row);
- while (ticker.children.length > 40) ticker.lastChild.remove();
- tickerCount++;
- reactHero(kind, p);
- }
-
- // Drive the featured avatar's emotes from its OWN trades — the screenshot moment.
- function reactHero(kind, p) {
- if (!topAgentId || p.agent_id !== topAgentId || typeof heroAvatar.playEmote !== 'function') return;
- if (kind === 'buy') heroAvatar.playEmote('cheer', 0.8);
- else if (kind === 'sell') heroAvatar.playEmote((p.pnl_sol ?? 0) >= 0 ? 'celebrate' : 'flinch', 1);
- }
-
- async function loadInitial() {
- try {
- const r = await fetch(`/api/sniper/leaderboard?network=${NETWORK}`);
- if (!r.ok) throw new Error('http ' + r.status);
- const d = await r.json();
- renderBoard(d.leaderboard || []);
- renderHero((d.leaderboard || [])[0]);
- // Seed the ticker with recent closed trades (most recent first → oldest first so prepend keeps order).
- (d.trades || []).slice().reverse().forEach((t) => pushEvent('sell', { ...t, sell_url: t.sell_url, entry_sol: t.entry_sol }));
- } catch (e) {
- el('board').innerHTML = `<tr><td colspan="5" class="empty">Leaderboard unavailable — retrying…</td></tr>`;
- }
- }
-
- // SSE with auto-reconnect (endpoint caps each connection at ~90s).
- let es = null, refreshTimer = null;
- function connect() {
- const dot = el('liveDot');
- es = new EventSource(`/api/sniper/stream?network=${NETWORK}`);
- es.addEventListener('open', () => { dot.classList.add('on'); dot.querySelector('i').nextSibling.textContent = ' live'; });
- es.addEventListener('buy', (m) => { try { pushEvent('buy', JSON.parse(m.data)); } catch {} });
- es.addEventListener('sell', (m) => { try { pushEvent('sell', JSON.parse(m.data)); refreshBoardSoon(); } catch {} });
- es.addEventListener('update', () => {});
- es.onerror = () => { dot.classList.remove('on'); try { es.close(); } catch {} setTimeout(connect, 2000); };
- }
- // Realized P&L changes only on a sell — refresh the board (debounced) after one.
- function refreshBoardSoon() {
- clearTimeout(refreshTimer);
- refreshTimer = setTimeout(loadInitial, 1500);
- }
+ <button class="pick-x" id="pickClose" aria-label="Close">
+ <svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><path d="M5 5l10 10M15 5L5 15"/></svg>
+ </button>
+ </div>
+ <div class="pick-grid" id="pickGrid"></div>
+ </div>
+ </div>
- loadInitial();
- connect();
- </script>
+ <script type="module" src="/src/play/arena.js"></script>
</body>
</html>
diff --git a/src/leaderboard.css b/src/leaderboard.css
new file mode 100644
index 000000000..53406c2f2
--- /dev/null
+++ b/src/leaderboard.css
@@ -0,0 +1,464 @@
+/* Trader Leaderboard — provable pump.fun track records.
+ Built entirely on the canonical design tokens (public/tokens.css via nav.css).
+ Glass-on-near-black, golden-ratio spacing, dark/light via tokens. */
+
+.lb-shell {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: var(--space-xl) var(--space-md) var(--space-2xl);
+ position: relative;
+ z-index: 1;
+}
+
+/* Ambient field canvas — decorative, pointer-inert, paused under reduced motion. */
+#lb-field {
+ position: fixed;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ pointer-events: none;
+ opacity: 0.5;
+}
+
+/* ---- Hero ---- */
+.lb-hero {
+ text-align: center;
+ margin-bottom: var(--space-xl);
+}
+.lb-kicker {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2xs);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ padding: var(--space-3xs) var(--space-sm);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ background: var(--surface-glass);
+ backdrop-filter: blur(var(--blur-sm));
+}
+.lb-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--success);
+ box-shadow: 0 0 0 0 var(--success);
+ animation: lb-pulse 2.4s var(--ease-out) infinite;
+}
+@keyframes lb-pulse {
+ 0% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.5); }
+ 70% { box-shadow: 0 0 0 8px rgba(74, 222, 128, 0); }
+ 100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }
+}
+.lb-title {
+ font-family: var(--font-display);
+ font-weight: var(--weight-bold);
+ font-size: var(--text-3xl);
+ line-height: var(--leading-tight);
+ margin: var(--space-sm) 0 var(--space-xs);
+ letter-spacing: -0.02em;
+}
+.lb-sub {
+ max-width: 60ch;
+ margin: 0 auto;
+ color: var(--ink-dim);
+ font-size: var(--text-md);
+ line-height: var(--leading-normal);
+}
+.lb-sub strong { color: var(--ink-bright); font-weight: var(--weight-semibold); }
+
+.lb-summary {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: var(--space-sm);
+ margin: var(--space-lg) auto 0;
+ max-width: 760px;
+}
+.lb-summary-cell {
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ border-radius: var(--radius-md);
+ padding: var(--space-sm);
+ text-align: center;
+}
+.lb-summary-cell dt {
+ font-size: var(--text-2xs);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--ink-faint);
+ margin-bottom: var(--space-3xs);
+}
+.lb-summary-cell dd {
+ margin: 0;
+ font-family: var(--font-display);
+ font-size: var(--text-lg);
+ font-weight: var(--weight-semibold);
+ font-variant-numeric: tabular-nums;
+}
+
+/* ---- Controls ---- */
+.lb-controls {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ margin-bottom: var(--space-sm);
+}
+.lb-control-group {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-sm);
+}
+.lb-seg {
+ display: inline-flex;
+ padding: 3px;
+ gap: 2px;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ background: var(--surface-1);
+}
+.lb-seg-btn {
+ appearance: none;
+ border: 0;
+ background: transparent;
+ color: var(--ink-dim);
+ font-family: var(--font-body);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-medium);
+ padding: var(--space-2xs) var(--space-md);
+ border-radius: var(--radius-pill);
+ cursor: pointer;
+ transition: color var(--duration-fast) var(--ease-standard),
+ background var(--duration-fast) var(--ease-standard);
+}
+.lb-seg-sm .lb-seg-btn { padding: var(--space-2xs) var(--space-sm); }
+.lb-seg-btn:hover { color: var(--ink-bright); }
+.lb-seg-btn.is-active {
+ background: var(--accent);
+ color: var(--btn-primary-fg);
+}
+.lb-select-wrap { display: inline-flex; align-items: center; gap: var(--space-2xs); }
+.lb-select-label {
+ font-size: var(--text-2xs);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--ink-faint);
+}
+.lb-select {
+ appearance: none;
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ color: var(--ink-bright);
+ font-family: var(--font-body);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-medium);
+ padding: var(--space-2xs) var(--space-lg) var(--space-2xs) var(--space-sm);
+ border-radius: var(--radius-control);
+ cursor: pointer;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath fill='%23888' d='M0 0l5 6 5-6z'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right var(--space-sm) center;
+}
+.lb-toggle { display: inline-flex; align-items: center; gap: var(--space-2xs); cursor: pointer; user-select: none; }
+.lb-toggle input { position: absolute; opacity: 0; width: 0; height: 0; }
+.lb-toggle-track {
+ width: 34px;
+ height: 20px;
+ border-radius: var(--radius-pill);
+ background: var(--surface-3);
+ border: 1px solid var(--stroke);
+ position: relative;
+ transition: background var(--duration-fast) var(--ease-standard);
+}
+.lb-toggle-thumb {
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: var(--ink-dim);
+ transition: transform var(--duration-fast) var(--ease-emphasized),
+ background var(--duration-fast) var(--ease-standard);
+}
+.lb-toggle input:checked + .lb-toggle-track { background: color-mix(in srgb, var(--success) 30%, transparent); }
+.lb-toggle input:checked + .lb-toggle-track .lb-toggle-thumb { transform: translateX(14px); background: var(--success); }
+.lb-toggle-text { font-size: var(--text-xs); color: var(--ink-dim); font-weight: var(--weight-medium); }
+.lb-toggle input:focus-visible + .lb-toggle-track {
+ outline: var(--focus-ring-width) solid var(--focus-ring-color);
+ outline-offset: var(--focus-ring-offset);
+}
+
+/* ---- How-to disclosure ---- */
+.lb-howto {
+ appearance: none;
+ width: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ background: transparent;
+ border: 0;
+ color: var(--ink-faint);
+ font-family: var(--font-body);
+ font-size: var(--text-xs);
+ padding: var(--space-2xs) 0;
+ cursor: pointer;
+ margin-bottom: var(--space-xs);
+}
+.lb-howto:hover { color: var(--ink-dim); }
+.lb-howto-chev { transition: transform var(--duration-fast) var(--ease-standard); }
+.lb-howto[aria-expanded='true'] .lb-howto-chev { transform: rotate(180deg); }
+.lb-howto-body {
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ border-radius: var(--radius-md);
+ padding: var(--space-md);
+ margin-bottom: var(--space-md);
+}
+.lb-howto-body p { margin: 0; color: var(--ink-dim); font-size: var(--text-sm); line-height: var(--leading-normal); }
+.lb-howto-body strong { color: var(--ink-bright); font-weight: var(--weight-semibold); }
+
+/* ---- Board ---- */
+.lb-board {
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-card);
+ background: var(--surface-1);
+ overflow: hidden;
+}
+.lb-board[aria-busy='true'] .lb-rows { opacity: 0.5; }
+.lb-board-head,
+.lb-row {
+ display: grid;
+ grid-template-columns: 36px minmax(0, 2.4fr) 0.9fr 1.2fr 0.9fr 0.8fr 0.8fr 0.7fr 96px;
+ align-items: center;
+ gap: var(--space-xs);
+ padding: var(--space-sm) var(--space-md);
+}
+.lb-board-head {
+ font-size: var(--text-2xs);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--ink-faint);
+ border-bottom: 1px solid var(--stroke);
+ background: var(--surface-2);
+}
+.lb-col-num { text-align: right; font-variant-numeric: tabular-nums; }
+.lb-col-act { text-align: right; }
+
+.lb-rows { display: flex; flex-direction: column; }
+.lb-row {
+ border-bottom: 1px solid var(--hairline);
+ text-decoration: none;
+ color: inherit;
+ position: relative;
+ transition: background var(--duration-fast) var(--ease-standard);
+ animation: lb-row-in var(--duration-base) var(--ease-out) both;
+}
+.lb-row:last-child { border-bottom: 0; }
+.lb-row:hover { background: var(--surface-2); }
+.lb-row:focus-visible {
+ outline: var(--focus-ring-width) solid var(--focus-ring-color);
+ outline-offset: calc(-1 * var(--focus-ring-width));
+}
+@keyframes lb-row-in {
+ from { opacity: 0; transform: translateY(6px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+.lb-rank {
+ font-family: var(--font-display);
+ font-size: var(--text-md);
+ font-weight: var(--weight-bold);
+ color: var(--ink-faint);
+ font-variant-numeric: tabular-nums;
+}
+.lb-row[data-top='1'] .lb-rank { color: #fcd34d; }
+.lb-row[data-top='2'] .lb-rank { color: #d4d4d8; }
+.lb-row[data-top='3'] .lb-rank { color: #d8a06a; }
+
+.lb-trader { display: flex; align-items: center; gap: var(--space-sm); min-width: 0; }
+.lb-avatar {
+ width: 38px;
+ height: 38px;
+ border-radius: 50%;
+ object-fit: cover;
+ border: 1px solid var(--stroke);
+ background: var(--surface-3);
+ flex-shrink: 0;
+}
+.lb-trader-meta { min-width: 0; }
+.lb-trader-name {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2xs);
+ font-weight: var(--weight-semibold);
+ font-size: var(--text-sm);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.lb-verified {
+ display: inline-flex;
+ align-items: center;
+ color: var(--success);
+ flex-shrink: 0;
+}
+.lb-verified svg { width: 14px; height: 14px; }
+.lb-trader-sub {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ color: var(--ink-faint);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.lb-score {
+ display: inline-flex;
+ align-items: baseline;
+ justify-content: flex-end;
+ gap: 1px;
+ font-family: var(--font-display);
+ font-weight: var(--weight-bold);
+ font-size: var(--text-lg);
+ font-variant-numeric: tabular-nums;
+}
+.lb-score-bar {
+ display: block;
+ height: 3px;
+ border-radius: var(--radius-pill);
+ margin-top: 3px;
+ background: linear-gradient(90deg, var(--ink-faint), var(--accent));
+}
+
+.lb-num { font-variant-numeric: tabular-nums; text-align: right; font-size: var(--text-sm); }
+.lb-num .lb-sub-num { display: block; font-size: var(--text-2xs); color: var(--ink-faint); }
+.lb-pos { color: var(--success); }
+.lb-neg { color: var(--danger); }
+.lb-muted { color: var(--ink-faint); }
+
+.lb-view {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-3xs);
+ font-size: var(--text-2xs);
+ font-weight: var(--weight-semibold);
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ padding: var(--space-3xs) var(--space-sm);
+ white-space: nowrap;
+ transition: border-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard);
+}
+.lb-row:hover .lb-view { color: var(--ink-bright); border-color: var(--stroke-strong); }
+
+/* Skeleton rows */
+.lb-skeleton { pointer-events: none; }
+.lb-skeleton .lb-sk {
+ height: 12px;
+ 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: lb-shimmer 1.4s ease infinite;
+}
+.lb-skeleton .lb-avatar { background: var(--surface-3); }
+@keyframes lb-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
+
+/* ---- State (empty / error) ---- */
+.lb-state { text-align: center; padding: var(--space-2xl) var(--space-md); color: var(--ink-dim); }
+.lb-state:empty { display: none; }
+.lb-state-title { font-family: var(--font-display); font-size: var(--text-lg); color: var(--ink-bright); margin-bottom: var(--space-2xs); }
+.lb-state p { margin: 0 auto var(--space-md); max-width: 44ch; font-size: var(--text-sm); }
+
+/* ---- Ticker ---- */
+.lb-ticker-wrap { margin-top: var(--space-xl); }
+.lb-ticker-title {
+ font-size: var(--text-2xs);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--ink-faint);
+ margin: 0 0 var(--space-sm);
+}
+.lb-ticker { display: flex; gap: var(--space-sm); overflow-x: auto; padding-bottom: var(--space-2xs); scrollbar-width: thin; }
+.lb-tick {
+ flex: 0 0 auto;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 160px;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ background: var(--surface-1);
+ padding: var(--space-sm);
+ text-decoration: none;
+ color: inherit;
+ transition: border-color var(--duration-fast) var(--ease-standard);
+}
+.lb-tick:hover { border-color: var(--stroke-strong); }
+.lb-tick-top { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2xs); }
+.lb-tick-sym { font-weight: var(--weight-semibold); font-size: var(--text-sm); }
+.lb-tick-pnl { font-variant-numeric: tabular-nums; font-size: var(--text-sm); font-weight: var(--weight-semibold); }
+.lb-tick-meta { font-size: var(--text-2xs); color: var(--ink-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+
+/* ---- CTA ---- */
+.lb-cta { margin-top: var(--space-2xl); }
+.lb-cta-inner {
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-card);
+ background: var(--surface-1);
+ padding: var(--space-xl);
+ text-align: center;
+}
+.lb-cta-inner h2 { font-family: var(--font-display); font-size: var(--text-xl); margin: 0 0 var(--space-2xs); }
+.lb-cta-inner p { color: var(--ink-dim); max-width: 52ch; margin: 0 auto var(--space-md); font-size: var(--text-sm); }
+.lb-cta-row { display: flex; gap: var(--space-sm); justify-content: center; flex-wrap: wrap; }
+.lb-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2xs);
+ font-family: var(--font-body);
+ font-size: var(--text-sm);
+ font-weight: var(--weight-semibold);
+ padding: var(--space-2xs) var(--space-lg);
+ border-radius: var(--radius-control);
+ border: 1px solid var(--stroke);
+ background: var(--surface-2);
+ color: var(--ink-bright);
+ text-decoration: none;
+ cursor: pointer;
+ transition: transform var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);
+}
+.lb-btn:hover { transform: translateY(-1px); border-color: var(--stroke-strong); }
+.lb-btn:active { transform: translateY(0); }
+.lb-btn-primary { background: var(--accent); color: var(--btn-primary-fg); border-color: transparent; }
+.lb-btn:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }
+
+/* ---- Responsive ---- */
+@media (max-width: 880px) {
+ .lb-hide-md { display: none !important; }
+ .lb-board-head,
+ .lb-row { grid-template-columns: 30px minmax(0, 2.2fr) 0.9fr 1.1fr 0.9fr 0.8fr 0.8fr 88px; }
+}
+@media (max-width: 620px) {
+ .lb-shell { padding: var(--space-lg) var(--space-sm) var(--space-xl); }
+ .lb-title { font-size: var(--text-2xl); }
+ .lb-summary { grid-template-columns: repeat(2, 1fr); }
+ .lb-hide-sm, .lb-winrate { display: none !important; }
+ .lb-controls { justify-content: center; }
+ .lb-board-head,
+ .lb-row { grid-template-columns: 26px minmax(0, 1.7fr) 0.8fr 1fr 70px; }
+ .lb-avatar { width: 32px; height: 32px; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ #lb-field { display: none; }
+ .lb-live-dot, .lb-row, .lb-skeleton .lb-sk { animation: none !important; }
+ .lb-btn:hover { transform: none; }
+}
diff --git a/src/play/arena-world.js b/src/play/arena-world.js
new file mode 100644
index 000000000..da3fccf15
--- /dev/null
+++ b/src/play/arena-world.js
@@ -0,0 +1,710 @@
+// arena-world.js — the live 3D trading floor.
+//
+// A single shared Three.js scene (one WebGL context, not N web components) that
+// renders the leaderboard's agents as animated 3D avatars standing on a glowing
+// arena floor, lets a spectator pick an avatar and walk through it in third
+// person, and turns live trade events into emotes + particle FX.
+//
+// Reuses the platform's animation system: AnimationManager retargets the
+// canonical Avaturn clip library onto any humanoid rig, so every avatar GLB —
+// Ready Player Me, Mixamo, CharacterStudio — performs the same emotes.
+
+import {
+ Scene, PerspectiveCamera, WebGLRenderer, Group, Object3D,
+ AmbientLight, DirectionalLight, PointLight, HemisphereLight,
+ PMREMGenerator, Color, Fog, Vector3, Vector2, Box3,
+ CircleGeometry, RingGeometry, TorusGeometry, CylinderGeometry,
+ MeshStandardMaterial, MeshBasicMaterial, Mesh, DoubleSide,
+ BufferGeometry, BufferAttribute, Points, PointsMaterial, AdditiveBlending,
+ Sprite, SpriteMaterial, CanvasTexture, MathUtils, LoopOnce, LoopRepeat,
+ SRGBColorSpace, ACESFilmicToneMapping,
+} from 'three';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { clone as cloneSkeleton } from 'three/addons/utils/SkeletonUtils.js';
+import { AnimationManager } from '../animation-manager.js';
+import { gltfLoader } from '../loaders/gltf.js';
+
+const MANIFEST_URL = '/animations/manifest.json';
+
+// The lean, expressive clip set. Loaded once into a shared library and injected
+// into every avatar so each clip is fetched + parsed a single time. Sizes were
+// chosen for fast first paint (idle/walk/buy/win/loss all < 1.1 MB).
+const CLIPS = {
+ idle: 'av-idle-breath', // calm breathing loop — the resting state
+ walk: 'walk', // spectator locomotion
+ buy: 'wave', // a wave when an agent opens a position
+ win: 'celebrate', // fist-pump on a profitable close
+ bigWin: 'av-back-flip', // reserved for monster wins (lazy-loaded)
+ loss: 'defeated', // a slump on a losing close
+ dance: 'dance', // ambient flair for the leader
+};
+const CORE_CLIPS = ['idle', 'walk', 'buy', 'win', 'loss', 'dance'].map((k) => CLIPS[k]);
+
+const PALETTE = {
+ bg: 0x06070d,
+ fog: 0x06070d,
+ floor: 0x0a0c15,
+ cyan: 0x6ee7ff,
+ violet: 0x9a7bff,
+ gold: 0xfbbf24,
+ up: 0x34d399,
+ down: 0xf87171,
+};
+
+export class ArenaWorld {
+ constructor(canvas, { onAgentClick } = {}) {
+ this.canvas = canvas;
+ this.onAgentClick = onAgentClick || (() => {});
+ this.agents = new Map(); // id -> ArenaAvatar
+ this.player = null; // ArenaAvatar (spectator)
+ this._fx = []; // transient effects with .tick(dt) -> done
+ this._templates = new Map(); // glbUrl -> Promise<gltf>
+ this._lib = null; // AnimationManager holding shared canonical clips
+ this._loopByName = new Map();
+ this._defs = [];
+ this._clock = { last: 0 };
+ this._running = false;
+ this._raf = 0;
+ this._labels = new Set(); // ArenaAvatar with DOM labels to project
+
+ this._initRenderer();
+ this._initScene();
+ this._initControls();
+ this._onResize = this._onResize.bind(this);
+ window.addEventListener('resize', this._onResize);
+ }
+
+ // ── Renderer / scene ──────────────────────────────────────────────────────
+
+ _initRenderer() {
+ const r = new WebGLRenderer({ canvas: this.canvas, antialias: true, alpha: false, powerPreference: 'high-performance' });
+ r.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ r.setSize(this.canvas.clientWidth || window.innerWidth, this.canvas.clientHeight || window.innerHeight, false);
+ r.shadowMap.enabled = true;
+ r.outputColorSpace = SRGBColorSpace;
+ r.toneMapping = ACESFilmicToneMapping;
+ r.toneMappingExposure = 1.05;
+ this.renderer = r;
+ this.loader = gltfLoader(r);
+ }
+
+ _initScene() {
+ const scene = new Scene();
+ scene.background = new Color(PALETTE.bg);
+ scene.fog = new Fog(PALETTE.fog, 16, 46);
+ const pmrem = new PMREMGenerator(this.renderer);
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.03).texture;
+ this.scene = scene;
+
+ const cam = new PerspectiveCamera(46, this._aspect(), 0.1, 200);
+ cam.position.set(0, 4.4, 12.5);
+ cam.lookAt(0, 1.4, -2);
+ this.camera = cam;
+
+ // Lighting — soft fill + a warm key that casts shadows + cyan/violet rims.
+ scene.add(new HemisphereLight(0xbcd2ff, 0x0a0a12, 0.55));
+ scene.add(new AmbientLight(0xffffff, 0.25));
+ const key = new DirectionalLight(0xfff3e0, 1.15);
+ key.position.set(6, 14, 8);
+ key.castShadow = true;
+ key.shadow.mapSize.set(2048, 2048);
+ key.shadow.camera.near = 1; key.shadow.camera.far = 60;
+ key.shadow.camera.left = -18; key.shadow.camera.right = 18;
+ key.shadow.camera.top = 18; key.shadow.camera.bottom = -18;
+ key.shadow.bias = -0.0004;
+ scene.add(key);
+ const rimA = new PointLight(PALETTE.cyan, 22, 40, 2.0); rimA.position.set(-11, 5, -6); scene.add(rimA);
+ const rimB = new PointLight(PALETTE.violet, 22, 40, 2.0); rimB.position.set(11, 5, -6); scene.add(rimB);
+
+ this._buildArena();
+ this._buildAtmosphere();
+ }
+
+ _buildArena() {
+ const g = new Group();
+ // Main disc.
+ const disc = new Mesh(
+ new CircleGeometry(16, 96),
+ new MeshStandardMaterial({ color: PALETTE.floor, roughness: 0.55, metalness: 0.7 }),
+ );
+ disc.rotation.x = -Math.PI / 2;
+ disc.receiveShadow = true;
+ g.add(disc);
+
+ // Concentric glowing rings.
+ const ringColors = [PALETTE.cyan, PALETTE.violet, PALETTE.cyan];
+ [6.2, 10.4, 14.6].forEach((rad, i) => {
+ const ring = new Mesh(
+ new TorusGeometry(rad, 0.022, 8, 160),
+ new MeshBasicMaterial({ color: ringColors[i % ringColors.length] }),
+ );
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.y = 0.012;
+ ring.material.transparent = true;
+ ring.material.opacity = 0.5 - i * 0.08;
+ g.add(ring);
+ this._pulseRings = this._pulseRings || [];
+ this._pulseRings.push({ mesh: ring, base: ring.material.opacity, phase: i * 1.3 });
+ });
+
+ // Radial spokes (faint).
+ const spokes = new Group();
+ for (let i = 0; i < 24; i++) {
+ const a = (i / 24) * Math.PI * 2;
+ const bar = new Mesh(
+ new CylinderGeometry(0.006, 0.006, 9.6, 4),
+ new MeshBasicMaterial({ color: PALETTE.cyan, transparent: true, opacity: 0.06 }),
+ );
+ bar.rotation.z = Math.PI / 2;
+ bar.position.set(Math.cos(a) * 9.6, 0.011, Math.sin(a) * 9.6);
+ bar.rotation.y = -a;
+ spokes.add(bar);
+ }
+ g.add(spokes);
+ this.scene.add(g);
+ this.arena = g;
+ }
+
+ _buildAtmosphere() {
+ // Drifting embers for depth.
+ const COUNT = 240;
+ const pos = new Float32Array(COUNT * 3);
+ this._emberSeed = [];
+ for (let i = 0; i < COUNT; i++) {
+ const r = 4 + Math.random() * 16;
+ const a = Math.random() * Math.PI * 2;
+ pos[i * 3] = Math.cos(a) * r;
+ pos[i * 3 + 1] = Math.random() * 9;
+ pos[i * 3 + 2] = Math.sin(a) * r;
+ this._emberSeed.push({ speed: 0.1 + Math.random() * 0.25, sway: Math.random() * Math.PI * 2 });
+ }
+ const geo = new BufferGeometry();
+ geo.setAttribute('position', new BufferAttribute(pos, 3));
+ const mat = new PointsMaterial({ color: 0x8fbfff, size: 0.05, transparent: true, opacity: 0.5, depthWrite: false, blending: AdditiveBlending });
+ const pts = new Points(geo, mat);
+ this.scene.add(pts);
+ this.embers = pts;
+ }
+
+ // A glowing pad an avatar stands on. #1 gets a gold, taller pad.
+ _buildPad(color, leader = false) {
+ const grp = new Group();
+ const h = leader ? 0.34 : 0.12;
+ const base = new Mesh(
+ new CylinderGeometry(leader ? 1.5 : 1.25, leader ? 1.65 : 1.32, h, 48),
+ new MeshStandardMaterial({ color: 0x10131f, roughness: 0.4, metalness: 0.85, emissive: new Color(color), emissiveIntensity: 0.12 }),
+ );
+ base.position.y = h / 2;
+ base.receiveShadow = true;
+ base.castShadow = true;
+ grp.add(base);
+ const halo = new Mesh(
+ new RingGeometry(leader ? 1.5 : 1.26, leader ? 1.72 : 1.42, 64),
+ new MeshBasicMaterial({ color, transparent: true, opacity: leader ? 0.9 : 0.6, side: DoubleSide }),
+ );
+ halo.rotation.x = -Math.PI / 2;
+ halo.position.y = h + 0.005;
+ grp.add(halo);
+ grp.userData.halo = halo;
+ grp.userData.padHeight = h;
+ return grp;
+ }
+
+ // ── Animation library ─────────────────────────────────────────────────────
+
+ async loadAnimations() {
+ const defs = await fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => (r.ok ? r.json() : [])).catch(() => []);
+ this._defs = Array.isArray(defs) ? defs : [];
+ for (const d of this._defs) this._loopByName.set(d.name, d.loop !== false);
+
+ const lib = new AnimationManager();
+ lib.setAnimationDefs(this._defs);
+ // Preload the core set once (no model attached → clips cached, no actions).
+ await Promise.all(CORE_CLIPS.map((name) => {
+ const def = this._defs.find((d) => d.name === name);
+ return def ? lib.loadAnimation(def.name, def.url, { loop: this._loopByName.get(name) }).catch(() => {}) : null;
+ }));
+ this._lib = lib;
+ }
+
+ // Lazy-load an extra clip into the shared library (e.g. the big-win backflip).
+ async ensureLibClip(name) {
+ if (!this._lib) return false;
+ if (this._lib.clips.has(name)) return true;
+ const def = this._defs.find((d) => d.name === name);
+ if (!def) return false;
+ try { await this._lib.loadAnimation(def.name, def.url, { loop: this._loopByName.get(name) }); return true; }
+ catch { return false; }
+ }
+
+ // ── Avatar templates ──────────────────────────────────────────────────────
+
+ _loadTemplate(url) {
+ if (this._templates.has(url)) return this._templates.get(url);
+ const p = this.loader.loadAsync(url);
+ this._templates.set(url, p);
+ return p;
+ }
+
+ async _makeAvatar(glbUrl, { fallback = '/avatars/default.glb' } = {}) {
+ let gltf;
+ try { gltf = await this._loadTemplate(glbUrl); }
+ catch { gltf = await this._loadTemplate(fallback); }
+ // Clone so multiple agents can share one downloaded GLB.
+ const model = cloneSkeleton(gltf.scene);
+ model.traverse((o) => { if (o.isMesh) { o.castShadow = true; o.frustumCulled = false; } });
+ return new ArenaAvatar(model, this._lib, this._loopByName, CLIPS);
+ }
+
+ // ── Spawning ──────────────────────────────────────────────────────────────
+
+ async spawnAgent(cfg) {
+ // cfg: { id, name, glbUrl, position:[x,z], facingY, leader, color, pnlText, pnlUp, thumbnail, rank }
+ const avatar = await this._makeAvatar(cfg.glbUrl);
+ const color = cfg.color ?? (cfg.leader ? PALETTE.gold : PALETTE.cyan);
+ const pad = this._buildPad(color, !!cfg.leader);
+ const root = new Group();
+ root.position.set(cfg.position[0], 0, cfg.position[1]);
+ root.rotation.y = cfg.facingY ?? 0;
+ avatar.object.position.y = pad.userData.padHeight;
+ root.add(pad);
+ root.add(avatar.object);
+ this.scene.add(root);
+
+ avatar.root = root;
+ avatar.pad = pad;
+ avatar.id = cfg.id;
+ avatar.name = cfg.name;
+ avatar.leader = !!cfg.leader;
+ avatar.color = color;
+ avatar.idle();
+ if (cfg.leader) avatar.play('dance', { loop: true }); // the champ vibes
+
+ // DOM label data.
+ avatar.label = { name: cfg.name, pnlText: cfg.pnlText, pnlUp: cfg.pnlUp, thumbnail: cfg.thumbnail, rank: cfg.rank };
+ avatar.headHeight = avatar.measureHeadHeight() + pad.userData.padHeight;
+ this.agents.set(cfg.id, avatar);
+ this._labels.add(avatar);
+ return avatar;
+ }
+
+ async spawnPlayer(glbUrl) {
+ if (this.player) { this._removeAvatar(this.player); this.player = null; }
+ const avatar = await this._makeAvatar(glbUrl);
+ const root = new Group();
+ root.position.set(0, 0, 9.5); // entrance, facing the arena
+ root.rotation.y = Math.PI;
+ root.add(avatar.object);
+ this.scene.add(root);
+ avatar.root = root;
+ avatar.isPlayer = true;
+ avatar.idle();
+ this.player = avatar;
+ // Drop the camera into a follow rig behind the player.
+ this._cam.targetYaw = Math.PI;
+ this._cam.yaw = Math.PI;
+ return avatar;
+ }
+
+ _removeAvatar(avatar) {
+ if (!avatar) return;
+ this._labels.delete(avatar);
+ if (avatar.root) this.scene.remove(avatar.root);
+ avatar.dispose();
+ if (avatar.id) this.agents.delete(avatar.id);
+ }
+
+ clearAgents() {
+ for (const a of [...this.agents.values()]) this._removeAvatar(a);
+ this.agents.clear();
+ }
+
+ // ── Reactions / FX ────────────────────────────────────────────────────────
+
+ reactBuy(agentId, { amountText } = {}) {
+ const a = this.agents.get(agentId);
+ if (a) a.emote('buy');
+ const at = a ? a.worldHead() : new Vector3(0, 2, 0);
+ this._spawnCoin(at, { text: amountText || 'BUY', color: PALETTE.cyan, dir: 1 });
+ this._ringPulse(a?.root?.position, PALETTE.cyan);
+ }
+
+ async reactSell(agentId, { win, big, pnlText } = {}) {
+ const a = this.agents.get(agentId);
+ if (a) {
+ if (win && big) { await this.ensureLibClip(CLIPS.bigWin); a.emote('bigWin'); }
+ else a.emote(win ? 'win' : 'loss');
+ }
+ const at = a ? a.worldHead() : new Vector3(0, 2, 0);
+ const color = win ? PALETTE.up : PALETTE.down;
+ this._spawnCoin(at, { text: pnlText, color, dir: win ? 1 : -1 });
+ if (win) this._confetti(at, big);
+ this._ringPulse(a?.root?.position, color);
+ }
+
+ _spawnCoin(pos, { text, color, dir }) {
+ const tex = makeLabelTexture(text, color);
+ const spr = new Sprite(new SpriteMaterial({ map: tex, transparent: true, depthTest: false }));
+ spr.scale.set(1.6, 0.8, 1);
+ spr.position.copy(pos).add(new Vector3((Math.random() - 0.5) * 0.4, 0.3, 0));
+ spr.renderOrder = 10;
+ this.scene.add(spr);
+ const life = 1.6;
+ let t = 0;
+ this._fx.push({
+ tick: (dt) => {
+ t += dt;
+ const k = t / life;
+ spr.position.y += dt * 1.5 * dir + dt * 0.6;
+ spr.material.opacity = 1 - k;
+ const s = 1 + k * 0.5;
+ spr.scale.set(1.6 * s, 0.8 * s, 1);
+ if (t >= life) { this.scene.remove(spr); spr.material.map.dispose(); spr.material.dispose(); return true; }
+ return false;
+ },
+ });
+ }
+
+ _confetti(pos, big = false) {
+ const COUNT = big ? 220 : 110;
+ const positions = new Float32Array(COUNT * 3);
+ const vel = [];
+ const colors = new Float32Array(COUNT * 3);
+ const pick = [PALETTE.cyan, PALETTE.violet, PALETTE.gold, PALETTE.up, 0xffffff];
+ for (let i = 0; i < COUNT; i++) {
+ positions[i * 3] = pos.x; positions[i * 3 + 1] = pos.y; positions[i * 3 + 2] = pos.z;
+ const a = Math.random() * Math.PI * 2;
+ const up = (big ? 4.5 : 3.2) + Math.random() * 2.5;
+ const spd = 1 + Math.random() * 3;
+ vel.push(new Vector3(Math.cos(a) * spd, up, Math.sin(a) * spd));
+ const c = new Color(pick[(Math.random() * pick.length) | 0]);
+ colors[i * 3] = c.r; colors[i * 3 + 1] = c.g; colors[i * 3 + 2] = c.b;
+ }
+ const geo = new BufferGeometry();
+ geo.setAttribute('position', new BufferAttribute(positions, 3));
+ geo.setAttribute('color', new BufferAttribute(colors, 3));
+ const mat = new PointsMaterial({ size: big ? 0.14 : 0.1, vertexColors: true, transparent: true, depthWrite: false, blending: AdditiveBlending });
+ const pts = new Points(geo, mat);
+ this.scene.add(pts);
+ const life = 2.0; let t = 0;
+ this._fx.push({
+ tick: (dt) => {
+ t += dt;
+ const arr = geo.attributes.position.array;
+ for (let i = 0; i < COUNT; i++) {
+ const v = vel[i];
+ v.y -= 9.8 * dt;
+ arr[i * 3] += v.x * dt; arr[i * 3 + 1] += v.y * dt; arr[i * 3 + 2] += v.z * dt;
+ }
+ geo.attributes.position.needsUpdate = true;
+ mat.opacity = Math.max(0, 1 - t / life);
+ if (t >= life) { this.scene.remove(pts); geo.dispose(); mat.dispose(); return true; }
+ return false;
+ },
+ });
+ }
+
+ _ringPulse(center, color) {
+ const c = center || new Vector3();
+ const ring = new Mesh(
+ new RingGeometry(0.6, 0.78, 48),
+ new MeshBasicMaterial({ color, transparent: true, opacity: 0.85, side: DoubleSide, blending: AdditiveBlending, depthWrite: false }),
+ );
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.set(c.x, 0.02, c.z);
+ this.scene.add(ring);
+ const life = 0.9; let t = 0;
+ this._fx.push({
+ tick: (dt) => {
+ t += dt; const k = t / life;
+ const s = 1 + k * 6;
+ ring.scale.set(s, s, s);
+ ring.material.opacity = 0.85 * (1 - k);
+ if (t >= life) { this.scene.remove(ring); ring.geometry.dispose(); ring.material.dispose(); return true; }
+ return false;
+ },
+ });
+ }
+
+ // ── Controls (third-person follow) ────────────────────────────────────────
+
+ _initControls() {
+ this._cam = { yaw: Math.PI, targetYaw: Math.PI, pitch: 0.18, dist: 7.2, targetDist: 7.2 };
+ this._keys = new Set();
+ this._drag = null;
+ this._move = { x: 0, y: 0 }; // joystick vector
+
+ const el = this.canvas;
+ this._onKeyDown = (e) => {
+ const k = e.key.toLowerCase();
+ if (['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright'].includes(k)) { this._keys.add(k); }
+ };
+ this._onKeyUp = (e) => this._keys.delete(e.key.toLowerCase());
+ window.addEventListener('keydown', this._onKeyDown);
+ window.addEventListener('keyup', this._onKeyUp);
+
+ el.addEventListener('pointerdown', (e) => {
+ if (e.target.closest && e.target.closest('.no-orbit')) return;
+ this._drag = { x: e.clientX, y: e.clientY, id: e.pointerId };
+ el.setPointerCapture?.(e.pointerId);
+ });
+ el.addEventListener('pointermove', (e) => {
+ if (!this._drag || this._drag.id !== e.pointerId) return;
+ const dx = e.clientX - this._drag.x;
+ const dy = e.clientY - this._drag.y;
+ this._drag.x = e.clientX; this._drag.y = e.clientY;
+ this._cam.targetYaw -= dx * 0.005;
+ this._cam.pitch = MathUtils.clamp(this._cam.pitch + dy * 0.004, -0.15, 0.7);
+ });
+ const endDrag = (e) => { if (this._drag && this._drag.id === e.pointerId) this._drag = null; };
+ el.addEventListener('pointerup', endDrag);
+ el.addEventListener('pointercancel', endDrag);
+ el.addEventListener('wheel', (e) => {
+ this._cam.targetDist = MathUtils.clamp(this._cam.targetDist + Math.sign(e.deltaY) * 0.6, 3.2, 12);
+ }, { passive: true });
+
+ // Click-to-select an agent (raycast handled in arena.js via projected labels).
+ }
+
+ // External joystick hook (nipplejs) sets a normalized vector.
+ setJoystick(x, y) { this._move.x = x; this._move.y = y; }
+
+ _updatePlayer(dt) {
+ const p = this.player;
+ if (!p) return;
+ // Desired move in camera space.
+ let mx = 0, mz = 0;
+ if (this._keys.has('w') || this._keys.has('arrowup')) mz -= 1;
+ if (this._keys.has('s') || this._keys.has('arrowdown')) mz += 1;
+ if (this._keys.has('a') || this._keys.has('arrowleft')) mx -= 1;
+ if (this._keys.has('d') || this._keys.has('arrowright')) mx += 1;
+ mx += this._move.x; mz -= this._move.y;
+ const mag = Math.hypot(mx, mz);
+ const moving = mag > 0.08;
+ if (moving) {
+ const len = Math.max(mag, 1);
+ mx /= len; mz /= len;
+ // Rotate input by camera yaw so "up" is away from camera.
+ const cos = Math.cos(this._cam.yaw), sin = Math.sin(this._cam.yaw);
+ const wx = mx * cos - mz * sin;
+ const wz = mx * sin + mz * cos;
+ const speed = 3.4 * dt;
+ const nx = p.root.position.x + wx * speed;
+ const nz = p.root.position.z + wz * speed;
+ const r = Math.hypot(nx, nz);
+ if (r < 15.2) { p.root.position.x = nx; p.root.position.z = nz; }
+ // Face travel direction (smoothly).
+ const targetFace = Math.atan2(wx, wz);
+ p.root.rotation.y = dampAngle(p.root.rotation.y, targetFace, 12 * dt);
+ }
+ p.setMoving(moving);
+ }
+
+ _updateCamera(dt) {
+ const c = this._cam;
+ c.yaw = dampAngle(c.yaw, c.targetYaw, 8 * dt);
+ c.dist += (c.targetDist - c.dist) * Math.min(1, 8 * dt);
+ const focus = this.player ? this.player.root.position : new Vector3(0, 0, -1);
+ const fy = (this.player ? 1.5 : 1.6);
+ const cx = focus.x + Math.sin(c.yaw) * Math.cos(c.pitch) * c.dist;
+ const cz = focus.z + Math.cos(c.yaw) * Math.cos(c.pitch) * c.dist;
+ const cy = fy + Math.sin(c.pitch) * c.dist + 1.6;
+ this.camera.position.lerp(new Vector3(cx, cy, cz), Math.min(1, 6 * dt));
+ this.camera.lookAt(focus.x, fy + 0.4, focus.z);
+ }
+
+ // ── Loop ──────────────────────────────────────────────────────────────────
+
+ start() {
+ if (this._running) return;
+ this._running = true;
+ this._clock.last = performance.now();
+ const loop = (now) => {
+ if (!this._running) return;
+ const dt = Math.min(0.05, (now - this._clock.last) / 1000);
+ this._clock.last = now;
+ this._tick(dt);
+ this.renderer.render(this.scene, this.camera);
+ this._raf = requestAnimationFrame(loop);
+ };
+ this._raf = requestAnimationFrame(loop);
+ }
+
+ _tick(dt) {
+ for (const a of this.agents.values()) a.update(dt);
+ this.player?.update(dt);
+ this._updatePlayer(dt);
+ this._updateCamera(dt);
+ // FX
+ for (let i = this._fx.length - 1; i >= 0; i--) { if (this._fx[i].tick(dt)) this._fx.splice(i, 1); }
+ // Floor ring shimmer
+ const t = this._clock.last / 1000;
+ (this._pulseRings || []).forEach((r) => { r.mesh.material.opacity = r.base * (0.7 + 0.3 * Math.sin(t * 1.4 + r.phase)); });
+ // Embers
+ if (this.embers) {
+ const arr = this.embers.geometry.attributes.position.array;
+ for (let i = 0; i < this._emberSeed.length; i++) {
+ const s = this._emberSeed[i];
+ arr[i * 3 + 1] += s.speed * dt;
+ arr[i * 3] += Math.sin(t * 0.4 + s.sway) * 0.002;
+ if (arr[i * 3 + 1] > 9) arr[i * 3 + 1] = 0;
+ }
+ this.embers.geometry.attributes.position.needsUpdate = true;
+ }
+ // Pad halos breathe; leader gold rotates.
+ for (const a of this.agents.values()) {
+ const halo = a.pad?.userData?.halo;
+ if (halo) halo.material.opacity = (a.leader ? 0.9 : 0.6) * (0.7 + 0.3 * Math.sin(t * 2 + (a.headHeight || 0)));
+ }
+ if (this._onLabels) this._onLabels();
+ }
+
+ // Project an avatar's head to screen space (for DOM labels). Returns null if behind camera.
+ projectHead(avatar, out) {
+ const p = avatar.worldHead(_tmpVec);
+ p.project(this.camera);
+ if (p.z > 1) return null;
+ const w = this.canvas.clientWidth, h = this.canvas.clientHeight;
+ out.x = (p.x * 0.5 + 0.5) * w;
+ out.y = (-p.y * 0.5 + 0.5) * h;
+ out.behind = p.z > 1;
+ return out;
+ }
+
+ setLabelUpdater(fn) { this._onLabels = fn; }
+
+ _aspect() { return (this.canvas.clientWidth || window.innerWidth) / (this.canvas.clientHeight || window.innerHeight); }
+
+ _onResize() {
+ const w = this.canvas.clientWidth || window.innerWidth;
+ const h = this.canvas.clientHeight || window.innerHeight;
+ this.renderer.setSize(w, h, false);
+ this.camera.aspect = w / h;
+ this.camera.updateProjectionMatrix();
+ }
+
+ dispose() {
+ this._running = false;
+ cancelAnimationFrame(this._raf);
+ window.removeEventListener('resize', this._onResize);
+ window.removeEventListener('keydown', this._onKeyDown);
+ window.removeEventListener('keyup', this._onKeyUp);
+ this.clearAgents();
+ if (this.player) this._removeAvatar(this.player);
+ this.renderer.dispose();
+ }
+}
+
+// ── One avatar (agent or spectator) ──────────────────────────────────────────
+
+class ArenaAvatar {
+ constructor(model, lib, loopByName, clipMap) {
+ this.object = model;
+ this._clipMap = clipMap;
+ this._loopByName = loopByName;
+ this.anim = new AnimationManager();
+ this.anim.setAnimationDefs(lib.getAnimationDefs());
+ // Inject the shared canonical clips so attach() builds retargeted actions
+ // without re-fetching or re-parsing them.
+ for (const [name, clip] of lib.clips) this.anim.clips.set(name, clip);
+ this.anim.attach(model);
+ this._configureLoops();
+ this._emoteTimer = 0;
+ this._moving = false;
+ this._busy = false; // mid one-shot emote
+ this._box = new Box3().setFromObject(model);
+ }
+
+ _configureLoops() {
+ for (const [name, action] of this.anim.actions) {
+ const loop = this._loopByName.get(name) !== false;
+ action.setLoop(loop ? LoopRepeat : LoopOnce, loop ? Infinity : 1);
+ action.clampWhenFinished = !loop;
+ }
+ }
+
+ idle() { this._busy = false; this.anim.crossfadeTo(this._clipMap.idle, 0.3); }
+
+ play(name, { loop = true } = {}) {
+ const clip = this._clipMap[name] || name;
+ this.anim.crossfadeTo(clip, 0.3);
+ }
+
+ setMoving(moving) {
+ if (this._busy) return;
+ if (moving === this._moving) return;
+ this._moving = moving;
+ this.anim.crossfadeTo(moving ? this._clipMap.walk : this._clipMap.idle, 0.18);
+ }
+
+ // A one-shot reaction that returns to idle/locomotion when done.
+ emote(kind) {
+ const name = this._clipMap[kind] || kind;
+ this._busy = true;
+ this.anim.crossfadeTo(name, 0.15);
+ const clip = this.anim.clips.get(name);
+ const dur = clip ? clip.duration : 1.6;
+ this._emoteTimer = Math.max(0.6, dur);
+ }
+
+ update(dt) {
+ this.anim.update(dt);
+ if (this._busy) {
+ this._emoteTimer -= dt;
+ if (this._emoteTimer <= 0) {
+ this._busy = false;
+ this.anim.crossfadeTo(this._moving ? this._clipMap.walk : this._clipMap.idle, 0.25);
+ }
+ }
+ }
+
+ measureHeadHeight() {
+ const box = new Box3().setFromObject(this.object);
+ return Math.min(2.2, Math.max(1.2, box.max.y - box.min.y)) ;
+ }
+
+ worldHead(out = new Vector3()) {
+ this.root.getWorldPosition(out);
+ out.y += (this.headHeight || this.measureHeadHeight()) + 0.15;
+ return out;
+ }
+
+ dispose() {
+ this.anim.dispose();
+ this.object.traverse((o) => {
+ if (o.isMesh) {
+ o.geometry?.dispose?.();
+ const m = o.material;
+ if (Array.isArray(m)) m.forEach((x) => x.dispose?.()); else m?.dispose?.();
+ }
+ });
+ }
+}
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+
+const _tmpVec = new Vector3();
+
+function dampAngle(current, target, lambda) {
+ let diff = ((target - current + Math.PI) % (Math.PI * 2)) - Math.PI;
+ if (diff < -Math.PI) diff += Math.PI * 2;
+ return current + diff * Math.min(1, lambda);
+}
+
+function makeLabelTexture(text, colorHex) {
+ const c = document.createElement('canvas');
+ c.width = 256; c.height = 128;
+ const ctx = c.getContext('2d');
+ const col = '#' + new Color(colorHex).getHexString();
+ ctx.font = 'bold 64px ui-monospace, "JetBrains Mono", monospace';
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.shadowColor = col; ctx.shadowBlur = 22;
+ ctx.fillStyle = col;
+ ctx.fillText(String(text ?? ''), 128, 66);
+ const tex = new CanvasTexture(c);
+ tex.colorSpace = SRGBColorSpace;
+ return tex;
+}
+
+export { ArenaAvatar };
diff --git a/src/play/arena.js b/src/play/arena.js
new file mode 100644
index 000000000..9d8ba1853
--- /dev/null
+++ b/src/play/arena.js
@@ -0,0 +1,415 @@
+// arena.js — orchestrates the live 3D Sniper Arena.
+//
+// Pulls the real leaderboard + SSE trade stream, places each agent as an
+// animated avatar in the 3D world (src/play/arena-world.js), turns every live
+// buy/sell into an emote + particle burst + a tape entry, lets the spectator
+// pick their own avatar and walk the floor, and keeps floating DOM labels
+// pinned over each agent's head. All data is real — no placeholders.
+
+import { ArenaWorld } from './arena-world.js';
+
+const NETWORK = new URLSearchParams(location.search).get('network') || 'mainnet';
+
+// Humanoid GLBs the canonical clip library animates cleanly. Agents are assigned
+// one deterministically by id (template-cached, so repeats are free). The
+// spectator picks their own (local roster + public gallery).
+const ROSTER = [
+ { url: '/avatars/default.glb', name: 'Default' },
+ { url: '/avatars/michelle.glb', name: 'Michelle' },
+ { url: '/avatars/xbot.glb', name: 'X-Bot' },
+ { url: '/avatars/readyplayerme.glb', name: 'RPM' },
+ { url: '/avatars/cz.glb', name: 'CZ' },
+];
+const MAX_AGENTS = 9;
+const PLAYER_KEY = 'arena:avatar:v1';
+
+const $ = (id) => document.getElementById(id);
+const fmtSol = (n) => (n == null ? '—' : `${n >= 0 ? '+' : ''}${Number(n).toFixed(3)}◎`);
+const fmtPct = (n) => (n == null ? '' : `${n >= 0 ? '+' : ''}${Number(n).toFixed(1)}%`);
+const esc = (s) => String(s ?? '').replace(/[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[c]));
+const hash = (s) => { let h = 0; for (let i = 0; i < String(s).length; i++) h = (h * 31 + s.charCodeAt(i)) | 0; return Math.abs(h); };
+const isBig = (p) => (p?.pnl_sol ?? 0) >= 0.4 || (p?.pnl_pct ?? 0) >= 100;
+
+let world = null;
+let labelLayer = null;
+const labelEls = new Map(); // agentId -> { el, pos }
+let topAgentId = null;
+
+// ── boot ──────────────────────────────────────────────────────────────────────
+
+(async function boot() {
+ const canvas = $('scene');
+ labelLayer = $('labels');
+ world = new ArenaWorld(canvas, { onAgentClick: focusAgent });
+
+ // Spin up the render loop immediately so the floor + lights are alive while
+ // avatars stream in (perceived performance).
+ setLoading('Building the arena…');
+ world.start();
+
+ try {
+ await world.loadAnimations();
+ } catch (e) {
+ console.warn('[arena] animations failed', e);
+ }
+
+ // Spectator avatar: restore saved pick, else a sensible default.
+ const saved = localStorage.getItem(PLAYER_KEY);
+ try { await world.spawnPlayer(saved || '/avatars/default.glb'); } catch (e) { console.warn('[arena] player spawn', e); }
+
+ world.setLabelUpdater(updateLabels);
+ mountControls();
+ mountJoystick(canvas);
+
+ await loadAndPlace();
+ connectStream();
+ setLoading(null);
+
+ // Periodic board refresh (realized P&L only changes on a close; SSE also nudges this).
+ setInterval(loadBoardOnly, 30_000);
+})();
+
+// ── data: leaderboard → agents in the world ────────────────────────────────────
+
+let _placed = false;
+async function loadAndPlace() {
+ let data;
+ try {
+ const r = await fetch(`/api/sniper/leaderboard?network=${NETWORK}`);
+ if (!r.ok) throw new Error('http ' + r.status);
+ data = await r.json();
+ } catch (e) {
+ renderBoard([]);
+ setEmpty(true);
+ return;
+ }
+ const board = (data.leaderboard || []).slice(0, MAX_AGENTS);
+ renderBoard(data.leaderboard || []);
+ renderTopCard((data.leaderboard || [])[0]);
+ setEmpty(board.length === 0);
+
+ if (!_placed && board.length) {
+ _placed = true;
+ const positions = arenaPositions(board.length);
+ // Spawn sequentially-ish but don't block the loop; stagger for a nice fill.
+ board.forEach((row, i) => {
+ const av = ROSTER[hash(row.agent_id) % ROSTER.length];
+ const pos = positions[i];
+ setTimeout(() => {
+ world.spawnAgent({
+ id: row.agent_id,
+ name: row.agent_name || 'Agent',
+ glbUrl: av.url,
+ position: [pos.x, pos.z],
+ facingY: pos.facing,
+ leader: i === 0,
+ pnlText: fmtSol(row.realized_pnl_sol),
+ pnlUp: (row.realized_pnl_sol ?? 0) >= 0,
+ thumbnail: row.image || '',
+ rank: row.rank,
+ }).then((agent) => createLabel(agent)).catch((err) => console.warn('[arena] spawn agent', err));
+ }, i * 180);
+ });
+ topAgentId = board[0].agent_id;
+ }
+
+ // Seed the tape with recent closed trades (oldest first so prepend keeps order).
+ (data.trades || []).slice(0, 12).reverse().forEach((t) => pushTape('sell', t, { quiet: true }));
+}
+
+async function loadBoardOnly() {
+ try {
+ const r = await fetch(`/api/sniper/leaderboard?network=${NETWORK}`);
+ if (!r.ok) return;
+ const d = await r.json();
+ renderBoard(d.leaderboard || []);
+ renderTopCard((d.leaderboard || [])[0]);
+ // Update floating labels' live P&L.
+ (d.leaderboard || []).forEach((row) => {
+ const L = labelEls.get(row.agent_id);
+ if (L) {
+ const up = (row.realized_pnl_sol ?? 0) >= 0;
+ L.el.querySelector('.lbl-pnl').textContent = fmtSol(row.realized_pnl_sol);
+ L.el.querySelector('.lbl-pnl').className = 'lbl-pnl ' + (up ? 'up' : 'down');
+ }
+ });
+ } catch { /* keep last good */ }
+}
+
+// Arrange agents on a forward-facing arc; #1 elevated at the back-centre.
+function arenaPositions(n) {
+ const out = [];
+ // Leader.
+ out.push({ x: 0, z: -7.2, facing: 0 });
+ const rest = n - 1;
+ for (let i = 0; i < rest; i++) {
+ const t = rest === 1 ? 0.5 : i / (rest - 1); // 0..1
+ const ang = (t - 0.5) * (Math.PI * 0.95); // spread ~ -85°..85°
+ const rad = 8.2;
+ const x = Math.sin(ang) * rad;
+ const z = -3.4 - Math.cos(ang) * 3.6; // bow toward the back
+ out.push({ x, z, facing: Math.atan2(x - 0, 12 - z) }); // face the entrance
+ }
+ return out;
+}
+
+// ── live stream ────────────────────────────────────────────────────────────────
+
+let es = null;
+function connectStream() {
+ const dot = $('liveDot');
+ es = new EventSource(`/api/sniper/stream?network=${NETWORK}`);
+ es.addEventListener('open', () => setLive(true));
+ 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); };
+}
+const safe = (fn) => { try { fn(); } catch (e) { /* one bad frame never breaks the stream */ } };
+
+function onBuy(p) {
+ world.reactBuy(p.agent_id, { amountText: fmtSol(p.entry_sol) });
+ pushTape('buy', p);
+ bumpAgentBusy(p.agent_id);
+}
+
+function onSell(p) {
+ const win = (p.pnl_sol ?? 0) >= 0;
+ const big = isBig(p);
+ world.reactSell(p.agent_id, { win, big, pnlText: `${fmtSol(p.pnl_sol)}` });
+ pushTape('sell', p);
+ if (win && big) bigWinBanner(p);
+ bumpAgentBusy(p.agent_id);
+ // A close changes realized P&L — refresh the board shortly.
+ clearTimeout(connectStream._t);
+ connectStream._t = setTimeout(loadBoardOnly, 1600);
+}
+
+function bumpAgentBusy(id) {
+ const L = labelEls.get(id);
+ if (!L) return;
+ L.el.classList.add('active');
+ clearTimeout(L._t);
+ L._t = setTimeout(() => L.el.classList.remove('active'), 2600);
+}
+
+// ── floating labels over agents ────────────────────────────────────────────────
+
+function createLabel(agent) {
+ if (!agent || labelEls.has(agent.id)) return;
+ const el = document.createElement('button');
+ el.className = 'agent-label no-orbit' + (agent.leader ? ' leader' : '');
+ el.type = 'button';
+ el.innerHTML = `
+ <span class="lbl-rank">#${agent.label.rank ?? '?'}</span>
+ ${agent.label.thumbnail ? `<img class="lbl-av" src="${esc(agent.label.thumbnail)}" alt="" onerror="this.remove()"/>` : ''}
+ <span class="lbl-meta">
+ <span class="lbl-name">${esc(agent.label.name)}</span>
+ <span class="lbl-pnl ${agent.label.pnlUp ? 'up' : 'down'}">${esc(agent.label.pnlText)}</span>
+ </span>`;
+ el.addEventListener('click', () => focusAgent(agent.id));
+ labelLayer.appendChild(el);
+ labelEls.set(agent.id, { el, pos: { x: 0, y: 0 } });
+}
+
+const _proj = { x: 0, y: 0, behind: false };
+function updateLabels() {
+ if (!labelEls.size) return;
+ for (const [id, L] of labelEls) {
+ const agent = world.agents.get(id);
+ if (!agent) { L.el.style.display = 'none'; continue; }
+ const p = world.projectHead(agent, _proj);
+ if (!p) { L.el.style.opacity = '0'; L.el.style.pointerEvents = 'none'; continue; }
+ L.el.style.opacity = '1';
+ L.el.style.pointerEvents = 'auto';
+ L.el.style.transform = `translate(-50%, -100%) translate(${p.x.toFixed(1)}px, ${(p.y - 6).toFixed(1)}px)`;
+ }
+}
+
+function focusAgent(id) {
+ const row = world.agents.get(id);
+ if (!row) return;
+ world._ringPulse?.(row.root.position, row.color);
+ row.emote('buy');
+ // Promote into the top card for a beat.
+ const L = labelEls.get(id);
+ if (L) { L.el.classList.add('active'); setTimeout(() => L.el.classList.remove('active'), 2200); }
+}
+
+// ── HUD: leaderboard, top card, tape, banner ────────────────────────────────────
+
+function renderBoard(rows) {
+ const body = $('board');
+ if (!rows.length) { body.innerHTML = ''; return; }
+ body.innerHTML = rows.slice(0, 12).map((r) => {
+ const wr = r.closed ? Math.round((r.wins / r.closed) * 100) : 0;
+ const up = (r.realized_pnl_sol ?? 0) >= 0;
+ return `<button class="row no-orbit" data-id="${esc(r.agent_id)}">
+ <span class="r-rank">${r.rank}</span>
+ <img class="r-av" src="${esc(r.image || '/avatars/thumbs/default.png')}" alt="" onerror="this.style.visibility='hidden'"/>
+ <span class="r-name">${esc(r.agent_name || 'Agent')}<small>${r.open_positions} open · ${r.closed ? wr + '% win' : 'new'}</small></span>
+ <span class="r-pnl ${up ? 'up' : 'down'}">${fmtSol(r.realized_pnl_sol)}</span>
+ </button>`;
+ }).join('');
+ body.querySelectorAll('.row').forEach((b) => b.addEventListener('click', () => focusAgent(b.dataset.id)));
+}
+
+function renderTopCard(top) {
+ if (!top) return;
+ $('topName').textContent = top.agent_name || 'Agent';
+ const pnl = $('topPnl');
+ pnl.textContent = fmtSol(top.realized_pnl_sol);
+ pnl.className = 'big ' + ((top.realized_pnl_sol ?? 0) >= 0 ? 'up' : 'down');
+ $('topWins').textContent = top.wins ?? 0;
+ $('topOpen').textContent = top.open_positions ?? 0;
+ const wr = top.closed ? Math.round((top.wins / top.closed) * 100) : 0;
+ $('topWr').textContent = top.closed ? wr + '%' : '—';
+ const img = $('topAv');
+ if (top.image) { img.src = top.image; img.style.display = ''; } else img.style.display = 'none';
+}
+
+let tapeCount = 0;
+function pushTape(kind, p, { quiet = false } = {}) {
+ const tape = $('tape');
+ $('tapeEmpty')?.remove();
+ const isSell = kind === 'sell';
+ const win = isSell && (p.pnl_sol ?? 0) >= 0;
+ const sideCls = !isSell ? 'buy' : win ? 'win' : 'loss';
+ const sideTxt = !isSell ? 'BUY' : win ? 'SELL ▲' : 'SELL ▼';
+ const proof = isSell ? p.sell_url : p.buy_url;
+ const pnl = isSell ? `<span class="t-pnl ${win ? 'up' : 'down'}">${fmtSol(p.pnl_sol)} ${fmtPct(p.pnl_pct)}</span>` : '';
+ const row = document.createElement('div');
+ row.className = 'tape-ev' + (quiet ? '' : ' fresh');
+ row.innerHTML = `
+ <span class="t-side ${sideCls}">${sideTxt}</span>
+ <span class="t-body">
+ <span class="t-l1"><b>${esc(p.agent_name || 'Agent')}</b> <span class="t-sym">${esc(p.symbol || p.name || (p.mint || '').slice(0, 6))}</span></span>
+ <span class="t-l2">${isSell ? esc(p.exit_reason || 'closed') : `entry ${fmtSol(p.entry_sol)}`} ${proof ? `· <a href="${esc(proof)}" target="_blank" rel="noopener" class="no-orbit">on-chain ↗</a>` : '· simulated'}</span>
+ </span>
+ ${pnl}`;
+ tape.prepend(row);
+ while (tape.children.length > 40) tape.lastChild.remove();
+ tapeCount++;
+}
+
+let bannerTimer = null;
+function bigWinBanner(p) {
+ const b = $('banner');
+ b.innerHTML = `🚀 <b>${esc(p.agent_name || 'Agent')}</b> just closed <b class="up">${fmtSol(p.pnl_sol)} ${fmtPct(p.pnl_pct)}</b> on <span>${esc(p.symbol || (p.mint || '').slice(0, 6))}</span>${p.sell_url ? ` · <a href="${esc(p.sell_url)}" target="_blank" rel="noopener" class="no-orbit">proof ↗</a>` : ''}`;
+ b.classList.add('show');
+ clearTimeout(bannerTimer);
+ bannerTimer = setTimeout(() => b.classList.remove('show'), 6500);
+}
+
+// ── status / states ─────────────────────────────────────────────────────────────
+
+function setLive(on) {
+ const dot = $('liveDot');
+ dot.classList.toggle('on', on);
+ dot.querySelector('span').textContent = on ? 'live' : 'reconnecting…';
+}
+function setLoading(text) {
+ const el = $('loading');
+ if (!el) return;
+ if (text) { el.textContent = text; el.style.display = ''; }
+ else el.style.display = 'none';
+}
+function setEmpty(on) { const e = $('emptyState'); if (e) e.hidden = !on; }
+
+// ── controls + avatar picker ────────────────────────────────────────────────────
+
+function mountControls() {
+ $('pickBtn')?.addEventListener('click', openPicker);
+ $('pickClose')?.addEventListener('click', closePicker);
+ $('pickBackdrop')?.addEventListener('click', closePicker);
+ $('emptyPick')?.addEventListener('click', openPicker);
+ // Collapse side panels on mobile.
+ $('togglePanels')?.addEventListener('click', () => document.body.classList.toggle('panels-open'));
+ window.addEventListener('keydown', (e) => { if (e.key === 'Escape') closePicker(); });
+}
+
+let pickerLoaded = false;
+function openPicker() {
+ $('picker').classList.add('open');
+ if (!pickerLoaded) { pickerLoaded = true; renderPicker(); }
+}
+function closePicker() { $('picker').classList.remove('open'); }
+
+async function renderPicker() {
+ const grid = $('pickGrid');
+ const saved = localStorage.getItem(PLAYER_KEY) || '/avatars/default.glb';
+ const localThumbs = {
+ '/avatars/default.glb': '/avatars/thumbs/default.png',
+ '/avatars/cz.glb': '/avatars/thumbs/cz.png',
+ };
+ const local = ROSTER.map((r) => ({ name: r.name, url: r.url, thumb: localThumbs[r.url] || '', starter: true }));
+ grid.innerHTML = local.map(tile(saved)).join('') + `<div class="pick-loading" id="pickLoading">Loading community avatars…</div>`;
+ wireTiles(grid);
+
+ try {
+ const r = await fetch('/api/avatars/public?limit=24');
+ const d = r.ok ? await r.json() : { avatars: [] };
+ $('pickLoading')?.remove();
+ const items = (d.avatars || []).filter((a) => a.model_url).map((a) => ({
+ name: a.name || 'Avatar', url: a.model_url, thumb: a.thumbnail_url || '', starter: false,
+ }));
+ if (items.length) {
+ grid.insertAdjacentHTML('beforeend', `<div class="pick-sep">Community gallery</div>` + items.map(tile(saved)).join(''));
+ wireTiles(grid);
+ }
+ } catch {
+ $('pickLoading')?.remove();
+ }
+}
+
+function tile(saved) {
+ return (a) => `
+ <button class="pick-tile no-orbit ${a.url === saved ? 'selected' : ''}" data-url="${esc(a.url)}" title="${esc(a.name)}">
+ <span class="pick-thumb">${a.thumb ? `<img src="${esc(a.thumb)}" alt="" loading="lazy" onerror="this.remove()"/>` : `<span class="pick-mono">${esc((a.name || '?').slice(0, 2).toUpperCase())}</span>`}</span>
+ <span class="pick-name">${esc(a.name)}</span>
+ ${a.starter ? '<span class="pick-badge">starter</span>' : ''}
+ </button>`;
+}
+
+function wireTiles(grid) {
+ grid.querySelectorAll('.pick-tile').forEach((b) => {
+ if (b._wired) return; b._wired = true;
+ b.addEventListener('click', () => choose(b.dataset.url, b));
+ });
+}
+
+async function choose(url, btn) {
+ const grid = $('pickGrid');
+ grid.querySelectorAll('.pick-tile').forEach((x) => x.classList.remove('selected'));
+ btn.classList.add('selected');
+ btn.classList.add('busy');
+ try {
+ await world.spawnPlayer(url);
+ localStorage.setItem(PLAYER_KEY, url);
+ closePicker();
+ } catch (e) {
+ btn.classList.add('failed');
+ setTimeout(() => btn.classList.remove('failed'), 1500);
+ } finally {
+ btn.classList.remove('busy');
+ }
+}
+
+// ── mobile joystick (nipplejs, lazy) ────────────────────────────────────────────
+
+async function mountJoystick(canvas) {
+ const isTouch = matchMedia('(pointer: coarse)').matches;
+ if (!isTouch) return;
+ try {
+ const { default: nipplejs } = await import('nipplejs');
+ const zone = $('joystick');
+ zone.style.display = 'block';
+ const stick = nipplejs.create({ zone, mode: 'static', position: { left: '60px', bottom: '70px' }, color: 'rgba(110,231,255,0.6)', size: 110 });
+ stick.on('move', (_e, d) => {
+ const f = (d.force || 0);
+ const a = d.angle?.radian ?? 0;
+ 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 */ }
+}
diff --git a/src/pump/bundle-detect.js b/src/pump/bundle-detect.js
deleted file mode 100644
index 90ae38d09..000000000
--- a/src/pump/bundle-detect.js
+++ /dev/null
@@ -1,174 +0,0 @@
-/**
- * pump/bundle-detect.js
- * ---------------------
- * Pure analytics over a coin's early trade footprint. No I/O — the coin-intel
- * worker feeds in aggregated per-wallet stats (and a wallet→funder map it
- * resolved from the chain), and these functions derive the organic-vs-bundle
- * signals and the composite intel score the sniper reads. Pure so every number
- * is unit-testable and identical in the worker and the API.
- *
- * A "trader" is one row per wallet for one coin:
- * { wallet, buy_lamports, sell_lamports, buy_count, sell_count, is_dev }
- * amounts are plain numbers (lamports). Volumes for a fresh launch stay well
- * inside Number.MAX_SAFE_INTEGER (1 SOL = 1e9; 9e15 ≈ 9M SOL).
- */
-
-function num(v) {
- const n = Number(v);
- return Number.isFinite(n) ? n : 0;
-}
-function pct(part, whole) {
- if (!(whole > 0)) return 0;
- return Math.round((part / whole) * 1000) / 10; // 1 decimal
-}
-function clamp(n, lo, hi) {
- return Math.max(lo, Math.min(hi, n));
-}
-
-/**
- * Roll a coin's per-wallet rows up into headline metrics.
- * @param {Array} traders
- * @returns {object} metrics
- */
-export function summarizeTraders(traders) {
- const rows = Array.isArray(traders) ? traders : [];
- let unique_buyers = 0,
- unique_sellers = 0,
- total_buys = 0,
- total_sells = 0,
- buy_volume = 0,
- sell_volume = 0,
- largest_buy = 0,
- dev_buy = 0;
- let dev_sold = false;
- let topBuyerVol = 0;
-
- for (const t of rows) {
- const b = num(t.buy_lamports);
- const s = num(t.sell_lamports);
- const bc = num(t.buy_count);
- const sc = num(t.sell_count);
- if (b > 0) unique_buyers++;
- if (s > 0) unique_sellers++;
- total_buys += bc;
- total_sells += sc;
- buy_volume += b;
- sell_volume += s;
- if (b > largest_buy) largest_buy = b;
- if (b > topBuyerVol) topBuyerVol = b;
- if (t.is_dev) {
- dev_buy = b;
- if (s > 0) dev_sold = true;
- }
- }
-
- const avg_buy = unique_buyers > 0 ? Math.round(buy_volume / unique_buyers) : 0;
- return {
- unique_buyers,
- unique_sellers,
- total_buys,
- total_sells,
- buy_volume,
- sell_volume,
- net_volume: buy_volume - sell_volume,
- largest_buy,
- avg_buy,
- dev_buy,
- dev_sold,
- dev_buy_pct: pct(dev_buy, buy_volume),
- top_buyer_pct: pct(topBuyerVol, buy_volume),
- };
-}
-
-/**
- * Cluster wallets that share a funding source ("bubblemaps-lite"): a single
- * funder backing ≥2 of a coin's buyers is the classic bundle signature.
- *
- * @param {Array} traders per-wallet rows (need buy_lamports + wallet)
- * @param {Map<string,string>|object} funderOf wallet → funder address (null/absent = unknown)
- * @returns {{ bundle_detected, bundle_wallet_count, bundle_buy_pct, cluster_count }}
- */
-export function detectBundle(traders, funderOf) {
- const rows = Array.isArray(traders) ? traders : [];
- const lookup = funderOf instanceof Map ? (w) => funderOf.get(w) : (w) => funderOf?.[w];
-
- // funder → [wallets buying through it]
- const byFunder = new Map();
- let buy_volume = 0;
- const buyVol = new Map();
- for (const t of rows) {
- const b = num(t.buy_lamports);
- buy_volume += b;
- if (b <= 0) continue;
- buyVol.set(t.wallet, b);
- const f = lookup(t.wallet);
- if (!f) continue;
- if (!byFunder.has(f)) byFunder.set(f, []);
- byFunder.get(f).push(t.wallet);
- }
-
- let bundleWallets = new Set();
- let cluster_count = 0;
- for (const [, wallets] of byFunder) {
- if (wallets.length >= 2) {
- cluster_count++;
- for (const w of wallets) bundleWallets.add(w);
- }
- }
-
- let bundledVol = 0;
- for (const w of bundleWallets) bundledVol += buyVol.get(w) || 0;
-
- return {
- bundle_detected: bundleWallets.size > 0,
- bundle_wallet_count: bundleWallets.size,
- bundle_buy_pct: pct(bundledVol, buy_volume),
- cluster_count,
- };
-}
-
-/**
- * 0 (heavily bundled / concentrated) … 100 (clean, broad, organic).
- * Transparent penalties so a strategy author can reason about the gate.
- */
-export function organicScore(metrics, bundle) {
- let score = 100;
- // shared-funder bundling is the heaviest penalty — dollar-for-dollar.
- score -= num(bundle?.bundle_buy_pct);
- // single-wallet dominance above a quarter of buy volume.
- const top = num(metrics?.top_buyer_pct);
- if (top > 25) score -= (top - 25) * 0.8;
- // dev hoarding above half the buy volume.
- const dev = num(metrics?.dev_buy_pct);
- if (dev > 50) score -= (dev - 50) * 0.6;
- // a launch nobody else has touched yet is not "organic", just empty.
- const buyers = num(metrics?.unique_buyers);
- if (buyers < 5) score -= (5 - buyers) * 8;
- // dev already dumping into the first buyers.
- if (metrics?.dev_sold) score -= 15;
- return clamp(Math.round(score), 0, 100);
-}
-
-// Classifications that read as "someone built something", nudged up slightly.
-const SUBSTANTIVE = new Set(['tech', 'utility', 'community', 'culture']);
-
-/**
- * Composite 0..100 the sniper gates on. Organic quality is the backbone;
- * socials, a confident classification, and real buyer breadth add to it.
- */
-export function intelScore({ metrics, bundle, organic, hasSocials, classification, confidence }) {
- const org = organic != null ? num(organic) : organicScore(metrics, bundle);
- let score = org * 0.6; // organic is 60% of the weight
-
- // buyer breadth (capped) — up to 20 pts for ≥20 distinct buyers.
- const buyers = num(metrics?.unique_buyers);
- score += clamp(buyers, 0, 20);
-
- // socials present and a confident category each add headroom.
- if (hasSocials) score += 8;
- const conf = num(confidence);
- if (classification && classification !== 'other') score += clamp(conf * 8, 0, 8);
- if (SUBSTANTIVE.has(classification)) score += 4;
-
- return clamp(Math.round(score), 0, 100);
-}
diff --git a/src/pump/coin-classifier.js b/src/pump/coin-classifier.js
deleted file mode 100644
index c54b2e0e1..000000000
--- a/src/pump/coin-classifier.js
+++ /dev/null
@@ -1,137 +0,0 @@
-/**
- * pump/coin-classifier.js
- * -----------------------
- * Classify a pump.fun coin from its launch metadata (name, symbol, description,
- * socials). The real path is an LLM call through the platform's free-first
- * provider chain (Groq/OpenRouter/NVIDIA before any paid key). If every provider
- * is unavailable the keyword heuristic takes over — classification NEVER fails
- * and never blocks the intel pipeline (operating rule 9). The heuristic is pure
- * and exported so it's unit-testable on its own.
- */
-
-export const TAXONOMY = [
- 'meme', // generic internet meme
- 'news_meme', // riffs on a current news story / event
- 'culture', // a cultural moment or trend
- 'community', // community / social / fan token
- 'animal', // animal-themed (dog, cat, frog, …)
- 'celebrity', // a person / celebrity
- 'political', // politics / elections / policy
- 'tech', // technology, AI, infra, DeFi, tooling
- 'utility', // a coin with a stated product/use
- 'other',
-];
-
-const KEYWORDS = {
- animal: ['dog', 'doge', 'shib', 'inu', 'cat', 'kitty', 'pepe', 'frog', 'toad', 'monkey', 'ape', 'bear', 'bull', 'hippo', 'penguin', 'duck', 'goat', 'wif', 'bonk', 'pup', 'hamster'],
- tech: ['ai', 'gpt', 'agent', 'protocol', 'network', 'chain', 'infra', 'zk', 'defi', 'swap', 'dex', 'oracle', 'data', 'compute', 'node', 'sdk', 'llm', 'model', 'bot', 'quant', 'rollup', 'layer', 'rwa', 'depin'],
- political: ['trump', 'biden', 'maga', 'election', 'president', 'senate', 'congress', 'putin', 'war', 'gov', 'policy', 'vote', 'kamala', 'potus'],
- community: ['dao', 'community', 'fam', 'gang', 'society', 'club', 'army', 'holders', 'fren', 'frens'],
- culture: ['meme', 'vibe', 'based', 'wagmi', 'gm', 'moon', 'lambo', 'degen', 'culture', 'trend', 'viral'],
- celebrity: ['elon', 'musk', 'kanye', 'taylor', 'drake', 'mrbeast', 'ronaldo', 'messi'],
-};
-
-const haystack = (coin) =>
- `${coin?.name || ''} ${coin?.symbol || ''} ${coin?.description || ''}`.toLowerCase();
-
-/**
- * Keyword classifier. Pure, deterministic, no I/O. The fallback AND a useful
- * source of `tags` the LLM result is merged with.
- * @returns {{classification, confidence, tags, theme, source}}
- */
-export function heuristicClassify(coin) {
- const text = haystack(coin);
- const tags = [];
- const hits = {};
- for (const [cat, words] of Object.entries(KEYWORDS)) {
- for (const w of words) {
- // word-boundary-ish: avoid 'ai' matching 'rain'.
- const re = new RegExp(`(^|[^a-z])${w}([^a-z]|$)`, 'i');
- if (re.test(text)) {
- hits[cat] = (hits[cat] || 0) + 1;
- tags.push(w);
- }
- }
- }
- const ranked = Object.entries(hits).sort((a, b) => b[1] - a[1]);
- let classification = 'meme';
- let confidence = 0.4;
- if (ranked.length) {
- classification = ranked[0][0];
- // culture keywords are weak meme-adjacent signals — only win if alone.
- if (classification === 'culture' && ranked.length > 1) classification = ranked[1][0];
- confidence = clamp(0.45 + ranked[0][1] * 0.1, 0.4, 0.7);
- }
- return {
- classification,
- confidence,
- tags: [...new Set(tags)].slice(0, 8),
- theme: ranked.length ? `${classification} signals: ${tags.slice(0, 3).join(', ')}` : 'unclassified meme',
- source: 'heuristic',
- };
-}
-
-const SYSTEM = `You classify newly-launched pump.fun (Solana) coins from their metadata. Reply with ONLY a compact JSON object, no markdown, no prose:
-{"classification": <one of: ${TAXONOMY.join(', ')}>, "confidence": <0..1>, "tags": [<up to 6 short lowercase tags>], "theme": "<≤12 word description of the coin's angle>"}
-Rules: "news_meme" = references a current real-world news story/event. "culture" = a broad cultural trend/moment. "community" = a fan/social/community token. "tech" = AI, infra, DeFi, or a real tool. "utility" = states a concrete product. Pick the single best fit; use "other" only if nothing fits.`;
-
-/**
- * Classify a coin. Tries the LLM; falls back to the heuristic on any failure.
- * @param {{name,symbol,description,twitter,telegram,website}} coin
- * @param {{track?:object, timeoutMs?:number}} [opts]
- * @returns {Promise<{classification,confidence,tags,theme,source,model}>}
- */
-export async function classifyCoin(coin, opts = {}) {
- const base = heuristicClassify(coin);
- try {
- const { llmComplete } = await import('../../api/_lib/llm.js');
- const user = JSON.stringify({
- name: coin?.name || null,
- symbol: coin?.symbol || null,
- description: (coin?.description || '').slice(0, 600) || null,
- has_twitter: !!coin?.twitter,
- has_telegram: !!coin?.telegram,
- has_website: !!coin?.website,
- });
- const res = await llmComplete({
- system: SYSTEM,
- user,
- maxTokens: 200,
- timeoutMs: opts.timeoutMs ?? 12_000,
- track: { tool: 'coin-intel-classify', ...(opts.track || {}) },
- });
- const parsed = parseJson(res.text);
- if (parsed && TAXONOMY.includes(parsed.classification)) {
- const tags = Array.isArray(parsed.tags) ? parsed.tags : [];
- return {
- classification: parsed.classification,
- confidence: clamp(Number(parsed.confidence), 0, 1) || 0.6,
- // union the model's tags with the heuristic's keyword hits.
- tags: [...new Set([...tags, ...base.tags].map((t) => String(t).toLowerCase().slice(0, 24)))].slice(0, 8),
- theme: String(parsed.theme || base.theme).slice(0, 120),
- source: `llm:${res.provider}`,
- model: res.model,
- };
- }
- } catch {
- // fall through to heuristic — never throw out of classify.
- }
- return { ...base, model: null };
-}
-
-function parseJson(text) {
- if (!text) return null;
- const m = String(text).match(/\{[\s\S]*\}/);
- if (!m) return null;
- try {
- return JSON.parse(m[0]);
- } catch {
- return null;
- }
-}
-
-function clamp(n, lo, hi) {
- const x = Number(n);
- if (!Number.isFinite(x)) return lo;
- return Math.max(lo, Math.min(hi, x));
-}
diff --git a/src/trader-format.js b/src/trader-format.js
new file mode 100644
index 000000000..9fe16f9fb
--- /dev/null
+++ b/src/trader-format.js
@@ -0,0 +1,116 @@
+/**
+ * Shared formatting + presentation helpers for the trader surfaces
+ * (leaderboard, profile, PnL card). Pure, dependency-free, safe to import in any
+ * browser module. Centralized so the leaderboard row and the profile header can
+ * never render the same number two different ways.
+ */
+
+const SOL = '◎';
+
+export function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => (
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
+ ));
+}
+
+/** Compact number: 1234 → "1.2K", 1_500_000 → "1.5M". */
+export function compact(n) {
+ const v = Number(n) || 0;
+ const abs = Math.abs(v);
+ if (abs >= 1e9) return (v / 1e9).toFixed(2).replace(/\.?0+$/, '') + 'B';
+ if (abs >= 1e6) return (v / 1e6).toFixed(2).replace(/\.?0+$/, '') + 'M';
+ if (abs >= 1e3) return (v / 1e3).toFixed(1).replace(/\.?0+$/, '') + 'K';
+ return String(Math.round(v * 100) / 100);
+}
+
+/** Signed SOL with the ◎ glyph: 2.013 → "+2.01 ◎". */
+export function fmtSol(n, { sign = true } = {}) {
+ const v = Number(n) || 0;
+ const s = sign && v > 0 ? '+' : '';
+ const mag = Math.abs(v);
+ const body = mag >= 1000 ? compact(mag) : mag.toFixed(mag >= 1 ? 2 : 3);
+ return `${s}${v < 0 ? '−' : ''}${body} ${SOL}`;
+}
+
+/** Signed USD: 401.2 → "+$401". */
+export function fmtUsd(n, { sign = true } = {}) {
+ if (n == null) return '';
+ const v = Number(n) || 0;
+ const s = sign && v > 0 ? '+' : v < 0 ? '−' : '';
+ const abs = Math.abs(v);
+ const body = abs >= 1000 ? '$' + compact(abs) : '$' + abs.toFixed(abs < 1 ? 2 : 0);
+ return `${s}${body}`;
+}
+
+/** Percent: 50.25 → "50.3%" (or "+50.3%" when signed). */
+export function fmtPct(n, { sign = false, dp = 1 } = {}) {
+ if (n == null) return '—';
+ const v = Number(n) || 0;
+ const s = sign && v > 0 ? '+' : v < 0 ? '−' : '';
+ return `${s}${Math.abs(v).toFixed(dp)}%`;
+}
+
+/** Tailwind-free semantic class for a signed value. */
+export function pnlClass(n) {
+ const v = Number(n) || 0;
+ return v > 0 ? 'lb-pos' : v < 0 ? 'lb-neg' : 'lb-muted';
+}
+
+/** Short pubkey: "7xKq…WtUK". */
+export function shortAddr(a, head = 4, tail = 4) {
+ if (!a || a.length <= head + tail + 1) return a || '';
+ return `${a.slice(0, head)}…${a.slice(-tail)}`;
+}
+
+/** Human hold duration from seconds: 10 → "10s", 125 → "2m", 5400 → "1.5h". */
+export function holdTime(seconds) {
+ const s = Number(seconds) || 0;
+ if (s < 60) return `${Math.round(s)}s`;
+ if (s < 3600) return `${Math.round(s / 60)}m`;
+ if (s < 86400) return `${(s / 3600).toFixed(s < 36000 ? 1 : 0)}h`;
+ return `${(s / 86400).toFixed(1)}d`;
+}
+
+/** Relative time: "just now", "3m ago", "2h ago", "5d ago". */
+export function relTime(iso) {
+ if (!iso) return '';
+ const then = new Date(iso).getTime();
+ if (!Number.isFinite(then)) return '';
+ const diff = Math.max(0, Date.now() - then) / 1000;
+ if (diff < 45) return 'just now';
+ if (diff < 3600) return `${Math.round(diff / 60)}m ago`;
+ if (diff < 86400) return `${Math.round(diff / 3600)}h ago`;
+ return `${Math.round(diff / 86400)}d ago`;
+}
+
+/**
+ * Deterministic SVG identicon data-URI from a seed string. The visual fingerprint
+ * for any trader without a profile image — stable per agent, never a blank void.
+ */
+export function identicon(seed) {
+ let h = 2166136261;
+ for (let i = 0; i < String(seed).length; i++) {
+ h ^= String(seed).charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ const hue = Math.abs(h) % 360;
+ const hue2 = (hue + 140) % 360;
+ const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='64' height='64'>
+ <defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'>
+ <stop offset='0' stop-color='hsl(${hue} 65% 55%)'/>
+ <stop offset='1' stop-color='hsl(${hue2} 60% 38%)'/></linearGradient></defs>
+ <rect width='64' height='64' fill='url(#g)'/>
+ <circle cx='${20 + (Math.abs(h >> 3) % 24)}' cy='${20 + (Math.abs(h >> 7) % 24)}' r='12' fill='rgba(255,255,255,0.18)'/>
+ </svg>`;
+ return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
+}
+
+const CHECK_SVG = `<svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M8 0.5l1.9 1.4 2.3-.3 1 2.1 2.1 1-.3 2.3 1.4 1.9-1.4 1.9.3 2.3-2.1 1-1 2.1-2.3-.3L8 15.5l-1.9-1.4-2.3.3-1-2.1-2.1-1 .3-2.3L-0.5 8l1.4-1.9-.3-2.3 2.1-1 1-2.1 2.3.3z" fill="currentColor" opacity="0.18"/><path d="M5.2 8.1l1.9 1.9 3.7-3.9" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
+
+/** Verified badge markup (only when verified). */
+export function verifiedBadge(verified, label = 'Verified track record') {
+ if (!verified) return '';
+ return `<span class="lb-verified" title="${escapeHtml(label)}" aria-label="${escapeHtml(label)}">${CHECK_SVG}</span>`;
+}
+
+export { SOL };
diff --git a/tests/coin-intel.test.js b/tests/coin-intel.test.js
new file mode 100644
index 000000000..e856ba8bd
--- /dev/null
+++ b/tests/coin-intel.test.js
@@ -0,0 +1,264 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ computeSignals, aggregateWallets, bundleScore, summarizeRisk,
+ bubblemapConnectivity, freshWalletRatio, _internals,
+} from '../workers/agent-sniper/intel/signals.js';
+import { heuristicClassify, _internals as classifyInternals } from '../workers/agent-sniper/intel/classify.js';
+import { scoreIntel } from '../workers/agent-sniper/scorer.js';
+import { correlation, deriveOutcome, learnedScore } from '../workers/agent-sniper/intel/learn.js';
+
+const SOL = _internals.LAMPORTS_PER_SOL;
+
+// Build a trade list helper. ts is ms-from-base; trader keyed by tag.
+function trades(specs, baseTs = 1_000_000) {
+ return specs.map((s, i) => ({
+ trader: s.w,
+ isBuy: s.buy !== false,
+ lamports: Math.round((s.sol ?? 0.5) * SOL),
+ baseAmount: s.base ?? 1000,
+ ts: baseTs + (s.t ?? i * 1000),
+ signature: `sig${i}`,
+ }));
+}
+
+describe('aggregateWallets', () => {
+ it('sums buys and sells per wallet', () => {
+ const agg = aggregateWallets(trades([
+ { w: 'A', sol: 1 },
+ { w: 'A', sol: 0.5 },
+ { w: 'A', sol: 0.3, buy: false },
+ { w: 'B', sol: 2 },
+ ]));
+ expect(agg.size).toBe(2);
+ expect(agg.get('A').buyCount).toBe(2);
+ expect(agg.get('A').sellCount).toBe(1);
+ expect(agg.get('A').buyLamports).toBe(1.5 * SOL);
+ expect(agg.get('A').sellLamports).toBe(0.3 * SOL);
+ expect(agg.get('B').buyLamports).toBe(2 * SOL);
+ });
+});
+
+describe('bundleScore', () => {
+ it('scores a clustered identical-size launch burst high', () => {
+ // 8 distinct wallets all buying ~0.5 SOL within the first 2s = bundle.
+ const burst = trades(
+ Array.from({ length: 8 }, (_, i) => ({ w: `bot${i}`, sol: 0.5, t: i * 200 })),
+ );
+ expect(bundleScore(burst)).toBeGreaterThan(0.5);
+ });
+
+ it('scores spread-out varied organic buys low', () => {
+ // Varied sizes, spread across 60s, distinct wallets = organic.
+ const organic = trades(
+ Array.from({ length: 10 }, (_, i) => ({ w: `human${i}`, sol: 0.1 + i * 0.13, t: i * 6000 })),
+ );
+ expect(bundleScore(organic)).toBeLessThan(0.4);
+ });
+
+ it('returns 0 with too few buys to judge', () => {
+ expect(bundleScore(trades([{ w: 'A' }, { w: 'B' }]))).toBe(0);
+ });
+});
+
+describe('computeSignals', () => {
+ it('flags a bundle launch and gives it a low quality score', () => {
+ const t = trades(Array.from({ length: 8 }, (_, i) => ({ w: `bot${i}`, sol: 0.5, t: i * 150 })));
+ const { signals, quality_score, risk_flags } = computeSignals({
+ mint: 'M', creator: 'dev', firstSeenAtMs: 1_000_000, endedAtMs: 1_090_000,
+ devBuyLamports: 0.5 * SOL, trades: t,
+ });
+ expect(signals.bundle_score).toBeGreaterThan(0.5);
+ expect(risk_flags).toContain('bundle_launch');
+ expect(quality_score).toBeLessThan(50);
+ });
+
+ it('rewards a diverse, spread-out organic launch', () => {
+ const t = trades(Array.from({ length: 14 }, (_, i) => ({ w: `human${i}`, sol: 0.1 + (i % 5) * 0.2, t: i * 5000 })));
+ const { signals, quality_score } = computeSignals({
+ mint: 'M', creator: 'dev', firstSeenAtMs: 1_000_000, endedAtMs: 1_090_000, trades: t,
+ });
+ expect(signals.unique_buyers).toBe(14);
+ expect(signals.organic_score).toBeGreaterThan(0.4);
+ expect(quality_score).toBeGreaterThan(40);
+ });
+
+ it('detects a dev dump', () => {
+ const t = trades([
+ { w: 'dev', sol: 1 },
+ { w: 'buyer1', sol: 0.5 },
+ { w: 'dev', sol: 0.9, buy: false },
+ ]);
+ const { signals, risk_flags } = computeSignals({
+ mint: 'M', creator: 'dev', firstSeenAtMs: 1_000_000, endedAtMs: 1_090_000, trades: t,
+ });
+ expect(signals.dev_sold).toBe(true);
+ expect(risk_flags).toContain('dev_dumped');
+ });
+
+ it('flags single-whale concentration', () => {
+ const t = trades([
+ { w: 'whale', sol: 50 },
+ { w: 'a', sol: 0.2 },
+ { w: 'b', sol: 0.2 },
+ ]);
+ const { signals, risk_flags } = computeSignals({
+ mint: 'M', creator: 'dev', firstSeenAtMs: 1_000_000, endedAtMs: 1_090_000, trades: t,
+ });
+ expect(signals.concentration_top1).toBeGreaterThan(0.5);
+ expect(risk_flags).toContain('single_whale');
+ });
+
+ it('leaves wallet-graph signals null without enrichment (no fake data)', () => {
+ const t = trades([{ w: 'a' }, { w: 'b' }, { w: 'c' }, { w: 'd' }]);
+ const { signals } = computeSignals({
+ mint: 'M', creator: 'dev', firstSeenAtMs: 1_000_000, endedAtMs: 1_090_000, trades: t,
+ });
+ expect(signals.fresh_wallet_ratio).toBeNull();
+ expect(signals.bubblemap_connectivity).toBeNull();
+ });
+});
+
+describe('wallet-graph enrichment', () => {
+ it('computes bubblemap connectivity from a shared funder', () => {
+ const agg = aggregateWallets(trades([{ w: 'a' }, { w: 'b' }, { w: 'c' }, { w: 'd' }]));
+ const meta = new Map([
+ ['a', { funder: 'X' }], ['b', { funder: 'X' }],
+ ['c', { funder: 'X' }], ['d', { funder: 'Y' }],
+ ]);
+ expect(bubblemapConnectivity(agg, meta)).toBe(0.75); // 3 of 4 share funder X
+ });
+
+ it('computes fresh-wallet ratio from prior tx counts', () => {
+ const agg = aggregateWallets(trades([{ w: 'a' }, { w: 'b' }, { w: 'c' }, { w: 'd' }]));
+ const meta = new Map([
+ ['a', { priorTxCount: 0 }], ['b', { priorTxCount: 1 }],
+ ['c', { priorTxCount: 50 }], ['d', { priorTxCount: 200 }],
+ ]);
+ expect(freshWalletRatio(agg, meta)).toBe(0.5); // a,b fresh
+ });
+});
+
+describe('summarizeRisk', () => {
+ it('clamps the quality score to 0..100', () => {
+ const { quality_score } = summarizeRisk({
+ organic_score: 1, bundle_score: 0, concentration_top1: 0,
+ dev_sold: false, fresh_wallet_ratio: null, unique_buyers: 100,
+ });
+ expect(quality_score).toBeLessThanOrEqual(100);
+ expect(quality_score).toBeGreaterThanOrEqual(0);
+ });
+});
+
+describe('normalizedEntropy', () => {
+ it('is 1 for a perfectly even distribution and ~0 for a spike', () => {
+ expect(_internals.normalizedEntropy([5, 5, 5, 5])).toBeCloseTo(1, 5);
+ expect(_internals.normalizedEntropy([10, 0, 0, 0])).toBe(0);
+ });
+});
+
+describe('heuristicClassify', () => {
+ it('classifies by keyword and always returns a category', () => {
+ expect(heuristicClassify({ name: 'Doge Killer', symbol: 'DOGE' }).category).toBe('animal');
+ expect(heuristicClassify({ description: 'an autonomous AI agent coin' }).category).toBe('ai');
+ expect(heuristicClassify({ name: 'Trump 2024' }).category).toBe('political');
+ expect(heuristicClassify({}).category).toBe('unknown');
+ });
+
+ it('only uses the known category set', () => {
+ const c = heuristicClassify({ name: 'random thing here' });
+ expect(classifyInternals.CATEGORIES).toContain(c.category);
+ });
+});
+
+describe('scoreIntel', () => {
+ const baseRec = {
+ quality_score: 80, category: 'meme', twitter: 't',
+ risk_flags: [], signals: { organic_score: 0.7, bundle_score: 0.1, concentration_top1: 0.2, dev_sold: false },
+ };
+
+ it('passes a clean coin and scores it', () => {
+ const r = scoreIntel(baseRec, { min_quality_score: 60 }, null);
+ expect(r.pass).toBe(true);
+ expect(r.score).toBeGreaterThan(0);
+ });
+
+ it('vetoes below the quality floor', () => {
+ const r = scoreIntel({ ...baseRec, quality_score: 40 }, { min_quality_score: 60 });
+ expect(r.pass).toBe(false);
+ expect(r.reasons[0]).toContain('quality_below_min');
+ });
+
+ it('vetoes a bundle above the cap', () => {
+ const r = scoreIntel({ ...baseRec, signals: { ...baseRec.signals, bundle_score: 0.8 } }, { max_bundle_score: 0.5 });
+ expect(r.pass).toBe(false);
+ expect(r.reasons[0]).toContain('bundle_above_max');
+ });
+
+ it('vetoes a dev dump by default', () => {
+ const r = scoreIntel({ ...baseRec, signals: { ...baseRec.signals, dev_sold: true } }, {});
+ expect(r.pass).toBe(false);
+ expect(r.reasons).toContain('dev_dumped');
+ });
+
+ it('respects category allowlist', () => {
+ const r = scoreIntel(baseRec, { allowed_categories: ['ai', 'tech'] });
+ expect(r.pass).toBe(false);
+ expect(r.reasons[0]).toContain('category_excluded');
+ });
+
+ it('blends learned weights into the score when available', () => {
+ const weights = { organic_score: 0.9, bundle_score: -0.9 };
+ const withLearned = scoreIntel(baseRec, {}, weights);
+ const without = scoreIntel(baseRec, {}, null);
+ expect(withLearned.score).not.toBe(without.score);
+ expect(withLearned.reasons.some((r) => r.startsWith('learned:'))).toBe(true);
+ });
+});
+
+describe('correlation', () => {
+ it('is +1 for a perfectly increasing relationship', () => {
+ expect(correlation([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]])).toBeCloseTo(1, 5);
+ });
+ it('is -1 for a perfectly decreasing relationship', () => {
+ expect(correlation([[0, 1], [1, 0.75], [2, 0.5], [3, 0.25], [4, 0]])).toBeCloseTo(-1, 5);
+ });
+ it('returns 0 with too few samples', () => {
+ expect(correlation([[1, 1], [2, 0]])).toBe(0);
+ });
+ it('returns 0 with no variance', () => {
+ expect(correlation([[1, 1], [1, 1], [1, 1], [1, 1], [1, 1]])).toBe(0);
+ });
+});
+
+describe('deriveOutcome', () => {
+ it('labels a graduated coin', () => {
+ const o = deriveOutcome({ complete: true, usd_market_cap: 90000, market_cap: 400 }, 50);
+ expect(o.outcome).toBe('graduated');
+ expect(o.graduated).toBe(true);
+ });
+ it('labels a pump by ATH multiple', () => {
+ // first-seen 50 SOL mc; ath 250 USD / (100usd/400sol price) ... craft a 5x.
+ const o = deriveOutcome({ usd_market_cap: 20000, market_cap: 100, ath_market_cap: 100000 }, 100);
+ expect(o.outcome).toBe('pumped');
+ });
+ it('labels a rug when market cap collapses', () => {
+ const o = deriveOutcome({ usd_market_cap: 1500, market_cap: 8 }, 100);
+ expect(o.outcome).toBe('rugged');
+ expect(o.rugged).toBe(true);
+ });
+ it('returns unknown when the coin cannot be fetched', () => {
+ expect(deriveOutcome(null, 100).outcome).toBe('unknown');
+ });
+});
+
+describe('learnedScore', () => {
+ it('returns null without weights', () => {
+ expect(learnedScore({ organic_score: 0.5 }, null)).toBeNull();
+ });
+ it('returns a 0..1 score with weights', () => {
+ const s = learnedScore({ organic_score: 0.9, bundle_score: 0.1 }, { organic_score: 0.8, bundle_score: -0.8 });
+ expect(s).toBeGreaterThan(0);
+ expect(s).toBeLessThanOrEqual(1);
+ });
+});
diff --git a/workers/agent-sniper/intel/classify.js b/workers/agent-sniper/intel/classify.js
index 1ea744a71..f1ba9a023 100644
--- a/workers/agent-sniper/intel/classify.js
+++ b/workers/agent-sniper/intel/classify.js
@@ -56,7 +56,7 @@ export function heuristicClassify({ name, symbol, description } = {}) {
}
}
// No keyword hit: short tickers with descriptions read as memes; otherwise unknown.
- const words = tokenize(`${name} ${description}`);
+ const words = tokenize(`${name || ''} ${description || ''}`);
return {
category: words.length ? 'meme' : 'unknown',
tags: [],