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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: enhance coin intelligence API with additional risk flags and signal handling
udvk400ce7ef0281
diff --git a/api/pump/coin-intel.js b/api/pump/coin-intel.jsindex f4bb1fda6..efb16338d 100644--- a/api/pump/coin-intel.js+++ b/api/pump/coin-intel.js@@ -24,9 +24,15 @@ const CATEGORIES = new Set([]);const lamportsToSol = (v) => (v == null ? null : Number(BigInt(v)) / 1e9);+const num = (v) => (v == null ? null : Number(v));++// Danger-level risk flags — used by the market-pulse aggregate to compute the+// "flagged" share. Mirrors the danger set the radar UI renders in red.+const DANGER_FLAGS = ['bundle_launch', 'dev_dumped', 'single_whale', 'low_diversity', 'fresh_wallet_swarm'];function shapeRow(r) {- return {+ const sig = r.signals || {};+ const out = {mint: r.mint,network: r.network,symbol: r.symbol,@@ -40,19 +46,30 @@ function shapeRow(r) {observation_seconds: r.observation_seconds,// headline signalsquality_score: r.quality_score,- bundle_score: r.bundle_score != null ? Number(r.bundle_score) : null,- organic_score: r.organic_score != null ? Number(r.organic_score) : null,- snipe_ratio: r.snipe_ratio != null ? Number(r.snipe_ratio) : null,- concentration_top10: r.concentration_top10 != null ? Number(r.concentration_top10) : null,- fresh_wallet_ratio: r.fresh_wallet_ratio != null ? Number(r.fresh_wallet_ratio) : null,- bubblemap_connectivity: r.bubblemap_connectivity != null ? Number(r.bubblemap_connectivity) : null,+ bundle_score: num(r.bundle_score),+ organic_score: num(r.organic_score),+ snipe_ratio: num(r.snipe_ratio),+ concentration_top10: num(r.concentration_top10),+ concentration_top5: sig.concentration_top5 != null ? Number(sig.concentration_top5) : null,+ concentration_top1: sig.concentration_top1 != null ? Number(sig.concentration_top1) : null,+ fresh_wallet_ratio: num(r.fresh_wallet_ratio),+ bubblemap_connectivity: num(r.bubblemap_connectivity),+ coordination_score: sig.coordination_score != null ? Number(sig.coordination_score) : null,+ timing_entropy: sig.timing_entropy != null ? Number(sig.timing_entropy) : null,risk_flags: r.risk_flags || [],+ // smart-money + cluster enrichment (highest-predictive signals)+ smart_money_count: r.smart_money_count ?? 0,+ smart_money_score: num(r.smart_money_score),+ cluster_count: r.cluster_count ?? 0,// classificationcategory: r.category,tags: r.tags || [],narrative: r.narrative,- classify_confidence: r.classify_confidence != null ? Number(r.classify_confidence) : null,+ classify_confidence: num(r.classify_confidence),classify_source: r.classify_source,+ is_news_meme: r.is_news_meme === true,+ news_headline: sig.news_headline ?? null,+ news_url: sig.news_url ?? null,// aggregatesdev_buy_sol: lamportsToSol(r.dev_buy_lamports),dev_sold: r.dev_sold,@@ -60,11 +77,27 @@ function shapeRow(r) {sell_count: r.sell_count,buy_volume_sol: lamportsToSol(r.buy_volume_lamports),sell_volume_sol: lamportsToSol(r.sell_volume_lamports),+ net_volume_sol: sig.net_volume_sol != null ? Number(sig.net_volume_sol)+ : (lamportsToSol(r.buy_volume_lamports) ?? 0) - (lamportsToSol(r.sell_volume_lamports) ?? 0),+ buy_sell_ratio: sig.buy_sell_ratio != null ? Number(sig.buy_sell_ratio) : null,unique_buyers: r.unique_buyers,unique_sellers: r.unique_sellers,largest_buy_sol: lamportsToSol(r.largest_buy_lamports),- signals: r.signals || {},+ market_cap_sol: sig.mc_sol_first_seen != null ? Number(sig.mc_sol_first_seen) : null,+ signals: sig,};++ // Feed query left-joins outcomes; surface a compact label when present so a+ // radar card can show a Graduated / Rugged badge without a second request.+ if (r.o_outcome !== undefined && (r.o_outcome || r.o_graduated || r.o_rugged)) {+ out.outcome = {+ outcome: r.o_outcome,+ graduated: r.o_graduated === true,+ rugged: r.o_rugged === true,+ ath_multiple: num(r.o_ath_multiple),+ };+ }+ return out;}export default wrap(async (req, res) => {@@ -86,6 +119,7 @@ export default wrap(async (req, res) => {return json(res, 404, { error: 'not_found', mint, hint: 'coin not observed (too old, or launched before the intel engine, or still mid-observation)' });}const out = shapeRow(row);+ out.smart_money_notable = Array.isArray(row.smart_money_notable) ? row.smart_money_notable : [];const [outcome] = await sql`select graduated, rugged, outcome, ath_multiple, ath_market_cap_usd, last_market_cap_usd, labeled_at@@ -124,19 +158,92 @@ export default wrap(async (req, res) => {return json(res, 200, out, { 'cache-control': 'public, max-age=15, s-maxage=30' });}+ // ── market pulse (aggregate over the recent window) ─────────────────────────+ // One birds-eye read of the room: how many launches, the health distribution,+ // bundle/smart-money rates, and the graduated/rugged split from labeled+ // outcomes. Every figure traces to observed rows — zeros when the table is empty.+ if (params.get('stats') === '1') {+ const [agg] = await sql`+ select+ count(*) filter (where first_seen_at > now() - interval '24 hours') as observed_24h,+ count(*) filter (where first_seen_at > now() - interval '1 hour') as observed_1h,+ round(avg(quality_score) filter (where quality_score is not null and first_seen_at > now() - interval '24 hours')) as avg_quality,+ count(*) filter (where quality_score >= 70 and first_seen_at > now() - interval '24 hours') as healthy,+ count(*) filter (where quality_score >= 40 and quality_score < 70 and first_seen_at > now() - interval '24 hours') as mixed,+ count(*) filter (where quality_score < 40 and first_seen_at > now() - interval '24 hours') as risky,+ count(*) filter (where quality_score is null and first_seen_at > now() - interval '24 hours') as unscored,+ count(*) filter (where smart_money_count > 0 and first_seen_at > now() - interval '24 hours') as smart_money_touched,+ count(*) filter (where is_news_meme and first_seen_at > now() - interval '24 hours') as news_memes,+ count(*) filter (where risk_flags && ${DANGER_FLAGS}::text[] and first_seen_at > now() - interval '24 hours') as flagged,+ round(avg(bundle_score) filter (where bundle_score is not null and first_seen_at > now() - interval '24 hours') * 100) as avg_bundle,+ round(avg(organic_score) filter (where organic_score is not null and first_seen_at > now() - interval '24 hours') * 100) as avg_organic+ from pump_coin_intel+ where network = ${network}+ `;+ const [out] = await sql`+ select+ count(*) filter (where o.graduated) as graduated,+ count(*) filter (where o.rugged) as rugged,+ count(*) as labeled+ from pump_coin_outcomes o+ join pump_coin_intel i using (mint)+ where i.network = ${network} and o.labeled_at > now() - interval '24 hours'+ `;+ const n = (v) => (v == null ? 0 : Number(v));+ return json(res, 200, {+ network,+ window_hours: 24,+ observed_24h: n(agg?.observed_24h),+ observed_1h: n(agg?.observed_1h),+ avg_quality: agg?.avg_quality != null ? Number(agg.avg_quality) : null,+ avg_bundle: agg?.avg_bundle != null ? Number(agg.avg_bundle) : null,+ avg_organic: agg?.avg_organic != null ? Number(agg.avg_organic) : null,+ healthy: n(agg?.healthy),+ mixed: n(agg?.mixed),+ risky: n(agg?.risky),+ unscored: n(agg?.unscored),+ smart_money_touched: n(agg?.smart_money_touched),+ news_memes: n(agg?.news_memes),+ flagged: n(agg?.flagged),+ outcomes: { graduated: n(out?.graduated), rugged: n(out?.rugged), labeled: n(out?.labeled) },+ t: Date.now(),+ }, { 'cache-control': 'public, max-age=15, s-maxage=30' });+ }+// ── radar feed ──────────────────────────────────────────────────────────────const limit = Math.max(1, Math.min(100, parseInt(params.get('limit'), 10) || 50));const minQuality = params.get('min_quality') != null ? parseInt(params.get('min_quality'), 10) : null;const category = CATEGORIES.has(params.get('category')) ? params.get('category') : null;const flag = params.get('flag') || null;+ const smartOnly = params.get('smart_money') === '1';+ const newsOnly = params.get('news') === '1';+ const q = (params.get('q') || '').trim().slice(0, 64);+ const qLike = q ? `%${q.replace(/[%_\\]/g, (m) => '\\' + m)}%` : null;++ // Whitelisted sort → ORDER BY fragment. Never interpolate the raw param.+ const SORTS = {+ new: sql`first_seen_at desc`,+ quality: sql`quality_score desc nulls last, first_seen_at desc`,+ smart: sql`smart_money_count desc, quality_score desc nulls last, first_seen_at desc`,+ buyers: sql`unique_buyers desc, first_seen_at desc`,+ volume: sql`buy_volume_lamports desc, first_seen_at desc`,+ };+ const order = SORTS[params.get('sort')] || SORTS.new;const rows = await sql`- select * from pump_coin_intel- where network = ${network}- and (${Number.isFinite(minQuality) ? minQuality : null}::int is null or quality_score >= ${Number.isFinite(minQuality) ? minQuality : null})- and (${category}::text is null or category = ${category})- and (${flag}::text is null or ${flag} = any(risk_flags))- order by first_seen_at desc+ select i.*,+ o.outcome as o_outcome, o.graduated as o_graduated,+ o.rugged as o_rugged, o.ath_multiple as o_ath_multiple+ from pump_coin_intel i+ left join pump_coin_outcomes o using (mint)+ where i.network = ${network}+ and (${Number.isFinite(minQuality) ? minQuality : null}::int is null or i.quality_score >= ${Number.isFinite(minQuality) ? minQuality : null})+ and (${category}::text is null or i.category = ${category})+ and (${flag}::text is null or ${flag} = any(i.risk_flags))+ and (${smartOnly} = false or i.smart_money_count > 0)+ and (${newsOnly} = false or i.is_news_meme = true)+ and (${qLike}::text is null or i.name ilike ${qLike} or i.symbol ilike ${qLike} or i.mint ilike ${qLike})+ order by ${order}limit ${limit}`;diff --git a/pages/oracle.html b/pages/oracle.htmlindex eb01bfe54..14fbc27bf 100644--- a/pages/oracle.html+++ b/pages/oracle.html@@ -54,9 +54,18 @@.hero h1 { font-size: clamp(30px, 5vw, 48px); line-height: 1.04; letter-spacing: -0.026em; margin: 18px 0 12px; font-weight: 800; }.hero h1 span { background: linear-gradient(100deg, var(--ink), var(--muted)); -webkit-background-clip: text; background-clip: text; color: transparent; }.hero p { max-width: 700px; font-size: 16px; color: var(--muted); margin: 0; }- .statline { display: flex; flex-wrap: wrap; gap: 26px; margin-top: 22px; }- .statline div span { display: block; font: 600 10.5px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--faint); margin-bottom: 5px; }- .statline div b { font: 800 22px/1 var(--mono); }+ .statline { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 24px; }+ .stat { display: flex; flex-direction: column; gap: 4px; padding: 11px 15px; min-width: 104px; text-align: left;+ border: 1px solid var(--line); border-radius: var(--r-sm); background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur); }+ button.stat { cursor: pointer; transition: transform .12s, border-color .16s, background .16s; position: relative; }+ button.stat:hover { transform: translateY(-2px); border-color: color-mix(in srgb, var(--cyan) 46%, var(--line)); background: color-mix(in srgb, var(--cyan) 6%, var(--panel)); }+ button.stat:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .stat > span { font: 600 10px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--faint); display: flex; align-items: center; gap: 6px; }+ .stat > span .stat-arrow { margin-left: auto; font-size: 9px; color: var(--faint); opacity: 0; transition: opacity .15s; }+ button.stat:hover .stat-arrow, button.stat:focus-visible .stat-arrow { opacity: 1; }+ .stat b { font: 800 23px/1 var(--mono); color: var(--ink); }+ .stat b.up { color: var(--up); } .stat b.warm { color: var(--gold); }+ .stat .stat-sub { font: 600 9.5px/1.2 var(--mono); color: var(--muted); letter-spacing: .02em; min-height: 11px; }/* tabs */.tabs { display: flex; gap: 6px; margin: 28px 0 18px; border-bottom: 1px solid var(--line); flex-wrap: wrap; }@@ -521,11 +530,25 @@<span class="eyebrow"><i id="liveDot"></i> <span id="liveLabel">Live · fused conviction</span></span><h1>Stop guessing the coin.<br><span>Know the conviction.</span></h1><p>Oracle fuses four reads on every pump.fun launch — <b>who's</b> buying it (proven-wallet pedigree), <b>how</b> it's being bought (bundle vs. organic structure), <b>what</b> it is (cultural narrative), and <b>how</b> it's moving — into one transparent 0–100 conviction score. The more coins and wallets we watch, the sharper every score. Then arm your 3D agent to act on the plays that clear your bar.</p>- <div class="statline">- <div><span>Scored today</span><b id="stScored">—</b></div>- <div><span>Win rate</span><b id="stStrong">—</b></div>- <div><span>Best ATH×</span><b id="stSmart">—</b></div>- <div><span>Prime now</span><b id="stUpdated">—</b></div>+ <div class="statline" id="statline">+ <div class="stat" title="Conviction scores produced in the last 24 hours">+ <span>Scored 24h</span><b id="stScored">—</b><span class="stat-sub" id="stScoredSub"></span>+ </div>+ <button class="stat" type="button" data-stat-action="prime" title="Coins sitting at Prime tier right now — click to filter the feed">+ <span>Prime now <span class="stat-arrow">→</span></span><b class="up" id="stPrime">—</b><span class="stat-sub">filter feed</span>+ </button>+ <button class="stat" type="button" data-stat-action="strong" title="Coins at Strong tier right now — click to filter the feed">+ <span>Strong now <span class="stat-arrow">→</span></span><b class="up" id="stStrong">—</b><span class="stat-sub">filter feed</span>+ </button>+ <button class="stat" type="button" data-stat-action="edge" title="Share of resolved calls that won — click for the full edge breakdown">+ <span>Win rate <span class="stat-arrow">→</span></span><b id="stWin">—</b><span class="stat-sub" id="stWinSub"></span>+ </button>+ <button class="stat" type="button" data-stat-action="proof" title="Best ATH multiple Oracle ever called — click for the proof gallery">+ <span>Best ATH× <span class="stat-arrow">→</span></span><b class="warm" id="stAth">—</b><span class="stat-sub">view proof</span>+ </button>+ <button class="stat" type="button" data-stat-action="agents" title="Distinct agents currently armed on Oracle conviction — click for the leaderboard">+ <span>Agents armed <span class="stat-arrow">→</span></span><b id="stArmed">—</b><span class="stat-sub" id="stArmedSub"></span>+ </button></div></header>@@ -559,7 +582,8 @@<option value="72">≥ 72 (Strong)</option><option value="86">≥ 86 (Prime)</option></select>- <div class="seg" id="sortSeg" aria-label="Sort order" style="margin-left:auto">+ <button class="wtoggle" id="watchToggle" type="button" aria-pressed="false" title="Show only coins on your watchlist" style="margin-left:auto">☆ Watching <span class="wtoggle-ct" id="watchCt"></span></button>+ <div class="seg" id="sortSeg" aria-label="Sort order"><button data-fsort="score" class="on">Top</button><button data-fsort="hot">Hot</button><button data-fsort="new">New</button>diff --git a/snapshots/current/index.html b/snapshots/current/index.htmlindex f368223b2..8c0640bcf 100644--- a/snapshots/current/index.html+++ b/snapshots/current/index.html@@ -3,7 +3,7 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />-<title>three.ws — site snapshot 2026-06-21</title>+<title>three.ws — site snapshot 2026-06-26</title><style>:root { --bg:#0a0a0b; --panel:#141416; --line:#26262b; --fg:#f4f4f5; --mut:#9a9aa3; --accent:#e8e8ea; }* { box-sizing: border-box; }@@ -43,7 +43,7 @@</header><main id="main"></main><script>-const DATA = {"capturedAt":"2026-06-21T08:42:21.012Z","date":"2026-06-21","baseUrl":"http://localhost:3000","viewports":["desktop"],"pages":[{"path":"/oracle","title":"/oracle","section":"Selected","slug":"oracle","shots":{"desktop":{"bytes":102285,"navStatus":200}}}]};+const DATA = {"capturedAt":"2026-06-26T07:13:17.006Z","date":"2026-06-26","baseUrl":"http://localhost:3000","viewports":["desktop"],"pages":[{"path":"/agents","title":"/agents","section":"Selected","slug":"agents","shots":{}}]};let viewport = DATA.viewports.includes('desktop') ? 'desktop' : 'mobile';let query = '';const main = document.getElementById('main');diff --git a/snapshots/current/manifest.json b/snapshots/current/manifest.jsonindex 64dcd0468..f841d4165 100644--- a/snapshots/current/manifest.json+++ b/snapshots/current/manifest.json@@ -1,24 +1,19 @@{- "capturedAt": "2026-06-21T08:42:21.012Z",- "date": "2026-06-21",+ "capturedAt": "2026-06-26T07:13:17.006Z",+ "date": "2026-06-26","baseUrl": "http://localhost:3000","viewports": ["desktop"],"pageCount": 1,- "capturedCount": 1,+ "capturedCount": 0,"pages": [{- "path": "/oracle",- "title": "/oracle",+ "path": "/agents",+ "title": "/agents","section": "Selected",- "slug": "oracle",- "shots": {- "desktop": {- "bytes": 102285,- "navStatus": 200- }- }+ "slug": "agents",+ "shots": {}}]}\ No newline at end of filediff --git a/src/launches.js b/src/launches.jsindex ba55d27a4..f4982801e 100644--- a/src/launches.js+++ b/src/launches.js@@ -18,7 +18,7 @@* · 60s live refresh that prepends genuinely new launches in place*/-import { mountCoinStatus } from './pump/coin-status-card.js';+import { mountCoinStatus, formatMcap } from './pump/coin-status-card.js';import { walletChipEl } from './shared/agent-wallet-chip.js';import { createLogger } from './shared/log.js';@@ -38,6 +38,9 @@ const state = {count: 0,seenMints: new Set(),latestCreatedAt: null,+ // Live market data keyed by mint, fed by each card's coin-status widget as it+ // loads/refreshes — the source for the feed's aggregate data points.+ marketByMint: new Map(),};const feedEl = document.getElementById('lx-feed');@@ -49,6 +52,8 @@ const tickerTrackEl = document.getElementById('lx-ticker-track');const statCountEl = document.getElementById('lx-stat-count');const statLatestEl = document.getElementById('lx-stat-latest');const statNetworkEl = document.getElementById('lx-stat-network');+const statMcapEl = document.getElementById('lx-stat-mcap');+const statGradEl = document.getElementById('lx-stat-grad');const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;diff --git a/src/play/arena.js b/src/play/arena.jsindex e5135de10..20effedf2 100644--- a/src/play/arena.js+++ b/src/play/arena.js@@ -39,10 +39,78 @@ const fmtPct = (n) => (n == null ? '' : `${n >= 0 ? '+' : ''}${Number(n).toFixedconst esc = (s) => String(s ?? '').replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[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;+const shortWallet = (a) => { const s = String(a || ''); return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s; };let world = null;let labelLayer = null;const labelEls = new Map(); // agentId -> { el, pos }+const rowsById = new Map(); // world id -> normalized row (for click routing)++// Board context captured on every fetch so the HUD reads consistently.+let _source = 'empty'; // 'agents' | 'live' | 'empty'+let _solUsd = null; // SOL→USD spot, for USD-denominated stats+let _liveWindow = null; // kolscan window label when source === 'live'+let _positions = []; // currently-open agent positions+let _sort = 'score'; // active leaderboard sort (agents only)++// Unify the two board shapes — provable three.ws agents and the live kolscan+// top-trader fallback — into one row model so the HUD + 3D floor render either+// without branching everywhere. `kind` carries the difference where it matters+// (click target, badges, labels).+function normalizeRow(r, kind) {+ if (kind === 'live') {+ return {+ kind: 'live',+ id: r.wallet,+ name: r.wallet_short || shortWallet(r.wallet),+ rank: r.rank,+ pnl_sol: r.realized_pnl_sol,+ pnl_usd: r.realized_pnl_usd,+ win_pct: r.win_rate != null ? Number(r.win_rate) : null, // already 0–100+ trades: r.trades ?? null,+ open: 0,+ image: '',+ url: r.account_url,+ wallet: r.wallet,+ };+ }+ const winPct = r.closed+ ? (r.win_rate != null ? r.win_rate * 100 : (r.wins / r.closed) * 100)+ : null;+ return {+ kind: 'agent',+ id: r.agent_id,+ agent_id: r.agent_id,+ name: r.agent_name || 'Agent',+ rank: r.rank,+ pnl_sol: r.realized_pnl_sol,+ pnl_usd: r.realized_pnl_usd,+ win_pct: winPct,+ closed: r.closed ?? 0,+ wins: r.wins ?? 0,+ open: r.open_positions ?? 0,+ roi_pct: r.roi_pct,+ score: r.score,+ verified: r.verified,+ copiers: r.copiers ?? 0,+ image: r.image || '',+ };+}++// Agent records are primary; the live kolscan ranking fills the floor until an+// agent posts a provable record (mirrors the leaderboard endpoint's hybrid).+function rowsFrom(data) {+ if ((data.leaderboard || []).length) return data.leaderboard.map((r) => normalizeRow(r, 'agent'));+ return (data.live_traders || []).map((r) => normalizeRow(r, 'live'));+}++// Capture the board context every fetch shares (source, price, open positions).+function ingest(data) {+ _solUsd = data.sol_usd ?? _solUsd;+ _liveWindow = data.live_window || null;+ _positions = data.positions || [];+ _source = data.source || ((data.leaderboard || []).length ? 'agents' : (data.live_traders || []).length ? 'live' : 'empty');+}// ── boot ──────────────────────────────────────────────────────────────────────@@ -85,7 +153,7 @@ let _placed = false;async function loadAndPlace() {let data;try {- const r = await fetch(`/api/sniper/leaderboard?network=${NETWORK}`);+ const r = await fetch(`/api/sniper/leaderboard?network=${NETWORK}&sort=${_sort}`);if (!r.ok) throw new Error('http ' + r.status);data = await r.json();} catch {@@ -93,10 +161,13 @@ async function loadAndPlace() {setEmpty(true);return;}- const board = (data.leaderboard || []).slice(0, MAX_AGENTS);- renderBoard(data.leaderboard || []);- renderTopCard((data.leaderboard || [])[0]);- setEmpty(board.length === 0);+ ingest(data);+ const rows = rowsFrom(data);+ const board = rows.slice(0, MAX_AGENTS);+ renderBoard(rows);+ renderTopCard(rows[0]);+ renderStats(rows);+ setEmpty(rows.length === 0);if (!_placed && board.length) {_placed = true;@@ -104,8 +175,8 @@ async function loadAndPlace() {}// Light up the Elite Floor — a server-decided trust treatment on the agents the- // network already trusts. Never blocks placement; purely additive.- markEliteFloor(board.map((r) => r.agent_id));+ // network already trusts (agents only; live wallets have no reputation record).+ markEliteFloor(board.filter((r) => r.kind === 'agent').map((r) => r.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 }));@@ -113,18 +184,22 @@ async function loadAndPlace() {async function loadBoardOnly() {try {- const r = await fetch(`/api/sniper/leaderboard?network=${NETWORK}`);+ const r = await fetch(`/api/sniper/leaderboard?network=${NETWORK}&sort=${_sort}`);if (!r.ok) return;const d = await r.json();- renderBoard(d.leaderboard || []);- renderTopCard((d.leaderboard || [])[0]);+ ingest(d);+ const rows = rowsFrom(d);+ renderBoard(rows);+ renderTopCard(rows[0]);+ renderStats(rows);// Update floating labels' live P&L.- (d.leaderboard || []).forEach((row) => {- const L = labelEls.get(row.agent_id);+ rows.forEach((row) => {+ const L = labelEls.get(row.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');+ const up = (row.pnl_sol ?? 0) >= 0;+ const pnlEl = L.el.querySelector('.lbl-pnl');+ pnlEl.textContent = fmtSol(row.pnl_sol);+ pnlEl.className = 'lbl-pnl ' + (up ? 'up' : 'down');}});} catch { /* keep last good */ }@@ -142,20 +217,21 @@ async function spawnAgentsProgressively(board) {let job;while ((job = queue.shift())) {const { row, i, pos } = job;- const av = ROSTER[hash(row.agent_id) % ROSTER.length];+ const av = ROSTER[hash(row.id) % ROSTER.length];try {const agent = await world.spawnAgent({- id: row.agent_id,- name: row.agent_name || 'Agent',+ id: row.id,+ name: row.name,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,+ pnlText: fmtSol(row.pnl_sol),+ pnlUp: (row.pnl_sol ?? 0) >= 0,thumbnail: row.image || '',rank: row.rank,});+ rowsById.set(row.id, row);createLabel(agent);} catch (err) {log.warn('spawn agent', err);diff --git a/src/pump/coin-status-card.js b/src/pump/coin-status-card.jsindex c1b9167b2..652e52285 100644--- a/src/pump/coin-status-card.js+++ b/src/pump/coin-status-card.js@@ -447,6 +447,11 @@ export function mountCoinStatus(container, mint, opts = {}) {const refreshMs = opts.refreshMs == null ? DEFAULT_REFRESH_MS : Number(opts.refreshMs);const showBuy = !!opts.showBuy;const placeholder = opts.placeholder || null;+ // Optional observer fired with the normalized coin after every successful+ // load (initial + each refresh). Lets a host surface aggregate the same live+ // market data it's already paying to fetch — e.g. the launches feed's+ // combined-market-cap / graduated tallies — without a second round trip.+ const onData = typeof opts.onData === 'function' ? opts.onData : null;const render = RENDERERS[variant];injectStyles();@@ -489,6 +494,10 @@ export function mountCoinStatus(container, mint, opts = {}) {}paint(render(lastCoin, { showBuy, placeholder, conviction: lastConviction }));+ if (onData) {+ // Never let an observer error break the widget's own render/refresh.+ try { onData(lastCoin); } catch { /* host-side aggregation is best-effort */ }+ }} catch (err) {if (err?.name === 'AbortError' || destroyed) return;// A refresh blip keeps the last good render; only a cold failure withdiff --git a/src/trades.js b/src/trades.jsindex e115403f5..bae708fe9 100644--- a/src/trades.js+++ b/src/trades.js@@ -1,453 +1,280 @@/**- * Live Trade Feed controller.+ * Trade Terminal — controller.*- * Renders /api/trades/feed — the public, no-auth feed of notable closed- * positions from all three.ws AI agents. Filters by time window, min PnL,- * and network. Supports pagination via cursor. Auto-refreshes every 30s.+ * A two-pane pump.fun analytics workstation:+ *+ * • Left rail — a live feed of three.ws's own on-chain activity: platform+ * launches (/api/pump/launches over pump_agent_mints) and notable agent+ * exits (/api/trades/feed). $THREE is pinned at the top. Selecting any row,+ * or pasting a mint into the search box, drives the deep-dive.+ *+ * • Centre — the deep-dive (./trades-detail.js): for the selected mint it+ * pulls every real signal the platform holds — candlestick chart, bonding+ * curve, intel signals, holders & cohorts, a funder bubblemap, smart money,+ * the wallet footprint, a live trade tape, outcome, and agent economics.+ *+ * The header carries a real live pulse from /api/pump/helius-stats (network+ * mint rate, graduations/hour, SOL price). Everything is real data; the only+ * pinned mint is $THREE — the platform's one coin.*/-import { escapeHtml, fmtSol, fmtPct, holdTime, relTime, shortAddr } from './trader-format.js';--const WATCH_KEY = 'ld_watchlist'; // shared with watchlist.js + launch-detail.js--function readWatchlist() {- try { return new Set(JSON.parse(localStorage.getItem(WATCH_KEY) || '[]')); } catch { return new Set(); }-}-function toggleWatch(mint) {- try {- const arr = JSON.parse(localStorage.getItem(WATCH_KEY) || '[]');- const set = new Set(Array.isArray(arr) ? arr : []);- if (set.has(mint)) { set.delete(mint); }- else { set.add(mint); }- localStorage.setItem(WATCH_KEY, JSON.stringify([...set].slice(0, 200)));- return set.has(mint);- } catch { return false; }-}+import { mountDetail } from './trades-detail.js';+import { escapeHtml, compact, shortAddr, relTime } from './trader-format.js';+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const NETWORK_KEY = 'tf_network';-const API = '/api/trades/feed';-const REFRESH_MS = 30_000;+const FEED_REFRESH_MS = 30_000;+const PULSE_REFRESH_MS = 20_000;const $ = (sel, root = document) => root.querySelector(sel);const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];const state = {- window: '24h',- minPnl: 25,+ tab: 'launches', // 'launches' | 'exits'network: localStorage.getItem(NETWORK_KEY) || 'mainnet',- cursor: null,+ selected: null,+ rows: [],};-let timer = null;+let detail = null;+let feedTimer = null;+let pulseTimer = null;-// ── Boot ─────────────────────────────────────────────────────────────────────+document.addEventListener('DOMContentLoaded', init);-document.addEventListener('DOMContentLoaded', () => {+function init() {readUrl();- applyStateToControls();-- const winSeg = $('#tfWinSeg');-- // Activate a time-window tab: sync visual state, ARIA, roving tabindex,- // then reload the feed. Shared by pointer + keyboard activation.- function selectWindowTab(btn, { focus = false } = {}) {- if (!btn) return;- $$('#tfWinSeg button').forEach((x) => {- const on = x === btn;- x.classList.toggle('on', on);- x.setAttribute('aria-selected', on ? 'true' : 'false');- x.tabIndex = on ? 0 : -1;- });- if (focus) btn.focus();- if (state.window === btn.dataset.win) return;- state.window = btn.dataset.win;- state.cursor = null;- writeUrl();- load(true);- }-- winSeg.addEventListener('click', (e) => {- const b = e.target.closest('[data-win]');- if (!b) return;- selectWindowTab(b);- });-- // WAI-ARIA tablist keyboard support: roving focus with Left/Right/Home/End,- // explicit activation on Enter/Space.- winSeg.addEventListener('keydown', (e) => {- const current = e.target.closest('[data-win]');- if (!current) return;- const tabs = $$('#tfWinSeg button');- const i = tabs.indexOf(current);- if (i === -1) return;-- let next = null;- switch (e.key) {- case 'ArrowRight':- case 'ArrowDown':- next = tabs[(i + 1) % tabs.length];- break;- case 'ArrowLeft':- case 'ArrowUp':- next = tabs[(i - 1 + tabs.length) % tabs.length];- break;- case 'Home':- next = tabs[0];- break;- case 'End':- next = tabs[tabs.length - 1];- break;- case 'Enter':- case ' ':- case 'Spacebar':- e.preventDefault();- selectWindowTab(current);- return;- default:- return;- }- e.preventDefault();- selectWindowTab(next, { focus: true });- });-- $('#tfMinPnl').addEventListener('change', () => {- state.minPnl = Number($('#tfMinPnl').value);- state.cursor = null;- writeUrl();- load(true);- });-- $('#tfNetwork').addEventListener('change', () => {- state.network = $('#tfNetwork').value;- localStorage.setItem(NETWORK_KEY, state.network);- state.cursor = null;- writeUrl();- load(true);- });-- $('#tfRefresh').addEventListener('click', () => {- state.cursor = null;- load(true);- });-- // Watch button — toggle mint in/out of local watchlist- document.addEventListener('click', (e) => {- const btn = e.target.closest('.tf-watch-btn');- if (!btn) return;- const mint = btn.dataset.mint;- if (!mint) return;- const nowWatching = toggleWatch(mint);- btn.textContent = nowWatching ? '★ Watching' : '☆ Watch';- btn.classList.toggle('tf-watching', nowWatching);- btn.setAttribute('aria-pressed', String(nowWatching));- });-- // Share button — native Web Share API with X/Twitter fallback- document.addEventListener('click', (e) => {- const btn = e.target.closest('.tf-share-btn');- if (!btn) return;- const raw = btn.dataset.share;- if (!raw) return;- let payload;- try { payload = JSON.parse(decodeURIComponent(raw)); } catch { return; }- if (navigator.share) {- navigator.share({ title: 'three.ws Trade', text: payload.text, url: payload.url }).catch(() => {});- } else {- window.open(btn.dataset.tweet, '_blank', 'noopener,width=550,height=420');- }- });-- $('#tfLoadMore').addEventListener('click', () => loadMore());+ wireControls();+ loadFeed(true);+ loadPulse();+ // Open the deep-dive immediately so the terminal is never an empty void —+ // the URL mint if present, otherwise the platform coin.+ select(state.selected || THREE_MINT, state.selected ? null : threeSeed(), { push: false });+ feedTimer = setInterval(() => loadFeed(false), FEED_REFRESH_MS);+ pulseTimer = setInterval(loadPulse, PULSE_REFRESH_MS);+ window.addEventListener('beforeunload', teardown);+}- load(true);- timer = setInterval(() => {- if (!state.cursor) load(false); // only auto-refresh when not deep in pagination- }, REFRESH_MS);-});+function teardown() {+ clearInterval(feedTimer);+ clearInterval(pulseTimer);+ try { detail?.destroy?.(); } catch { /* gone */ }+}-// ── URL sync ──────────────────────────────────────────────────────────────────+function threeSeed() {+ return { symbol: 'THREE', name: 'three.ws', image_uri: '' };+}+// ── URL ───────────────────────────────────────────────────────────────────────function readUrl() {const p = new URL(location.href).searchParams;- const wins = new Set(['1h', '6h', '24h', '7d', '30d', 'all']);- if (wins.has(p.get('window'))) state.window = p.get('window');- const mp = Number(p.get('min_pnl_pct'));- if (mp > 0) state.minPnl = mp;+ const m = p.get('mint') || p.get('coin');+ if (m && MINT_RE.test(m)) state.selected = m;if (p.get('network') === 'devnet') state.network = 'devnet';+ if (p.get('tab') === 'exits') state.tab = 'exits';}-function writeUrl() {const p = new URLSearchParams();- p.set('window', state.window);- p.set('min_pnl_pct', String(state.minPnl));+ if (state.selected) p.set('mint', state.selected);+ if (state.tab !== 'launches') p.set('tab', state.tab);if (state.network !== 'mainnet') p.set('network', state.network);- history.replaceState(null, '', `${location.pathname}?${p}`);+ history.replaceState(null, '', `${location.pathname}${p.toString() ? '?' + p : ''}`);}-function applyStateToControls() {- $('#tfMinPnl').value = String(state.minPnl);- $('#tfNetwork').value = state.network;- // sync seg buttons — visual state, ARIA selection, and roving tabindex- $$('#tfWinSeg button').forEach((b) => {- const on = b.dataset.win === state.window;- b.classList.toggle('on', on);- b.setAttribute('aria-selected', on ? 'true' : 'false');- b.tabIndex = on ? 0 : -1;- });-}--// ── Fetch + render ────────────────────────────────────────────────────────────--async function load(reset = false) {- if (reset) {- state.cursor = null;- showSkeletons();- }-- const q = new URLSearchParams({- network: state.network,- window: state.window,- min_pnl_pct: String(state.minPnl),- limit: '40',+// ── controls ────────────────────────────────────────────────────────────────────+function wireControls() {+ $$('#ttTabs [data-tab]').forEach((b) => {+ b.classList.toggle('on', b.dataset.tab === state.tab);+ b.addEventListener('click', () => {+ if (state.tab === b.dataset.tab) return;+ state.tab = b.dataset.tab;+ $$('#ttTabs [data-tab]').forEach((x) => x.classList.toggle('on', x === b));+ writeUrl();+ loadFeed(true);+ });});- let data;- try {- const r = await fetch(`${API}?${q}`);- if (!r.ok) throw new Error(`HTTP ${r.status}`);- data = await r.json();- } catch {- showError();- return;+ const net = $('#ttNetwork');+ if (net) {+ net.value = state.network;+ net.addEventListener('change', () => {+ state.network = net.value;+ localStorage.setItem(NETWORK_KEY, state.network);+ writeUrl();+ loadFeed(true);+ });}- if (!data?.items?.length) {- showEmpty();- return;+ const search = $('#ttSearch');+ if (search) {+ search.addEventListener('keydown', (e) => {+ if (e.key !== 'Enter') return;+ const v = search.value.trim();+ if (MINT_RE.test(v)) { select(v, null, { push: true }); search.blur(); }+ else if (v) { search.classList.add('shake'); setTimeout(() => search.classList.remove('shake'), 400); }+ });+ $('#ttSearchGo')?.addEventListener('click', () => {+ const v = search.value.trim();+ if (MINT_RE.test(v)) select(v, null, { push: true });+ });}- state.cursor = data.next_cursor || null;- renderStats(data.items);- renderItems(data.items, reset);+ // Event delegation for feed row selection.+ $('#ttFeed').addEventListener('click', (e) => {+ const row = e.target.closest('[data-mint]');+ if (!row) return;+ let seed = null;+ try { seed = row.dataset.seed ? JSON.parse(row.dataset.seed) : null; } catch { /* ignore */ }+ select(row.dataset.mint, seed, { push: true });+ });+}- const btn = $('#tfLoadMore');- btn.hidden = !state.cursor;- if (!btn.hidden) btn.textContent = 'Load more';+// ── selection ─────────────────────────────────────────────────────────────────+function select(mint, seed, { push = true } = {}) {+ if (!MINT_RE.test(mint)) return;+ state.selected = mint;+ highlightRow(mint);+ if (push) writeUrl();+ try { detail?.destroy?.(); } catch { /* gone */ }+ const host = $('#ttDetail');+ host.scrollTop = 0;+ detail = mountDetail(host, { mint, network: state.network, seed: seed || seedFromRows(mint) || threeSeedIf(mint) });}-async function loadMore() {- if (!state.cursor) return;- const btn = $('#tfLoadMore');- btn.disabled = true;- btn.textContent = 'Loading…';+function threeSeedIf(mint) { return mint === THREE_MINT ? threeSeed() : null; }+function seedFromRows(mint) {+ const r = state.rows.find((x) => x.mint === mint);+ return r ? { symbol: r.symbol, name: r.name, image_uri: r.image_uri } : null;+}+function highlightRow(mint) {+ $$('#ttFeed [data-mint]').forEach((el) => el.classList.toggle('on', el.dataset.mint === mint));+}- const q = new URLSearchParams({- network: state.network,- window: state.window,- min_pnl_pct: String(state.minPnl),- limit: '40',- cursor: state.cursor,- });+// ── live pulse ──────────────────────────────────────────────────────────────────+async function loadPulse() {+ try {+ const r = await fetch('/api/pump/helius-stats', { headers: { accept: 'application/json' } });+ if (!r.ok) return;+ const d = await r.json();+ const set = (id, v) => { const el = document.getElementById(id); if (el) el.textContent = v; };+ set('ttPulseMints', d.feed?.mints_per_min != null ? `${d.feed.mints_per_min}/min` : '—');+ set('ttPulseGrad', d.feed?.graduations_per_hour != null ? `${d.feed.graduations_per_hour}/hr` : '—');+ set('ttPulseSol', d.sol_price != null ? `$${Number(d.sol_price).toFixed(2)}` : '—');+ const chgEl = document.getElementById('ttPulseSolChg');+ if (chgEl && d.sol_change_24h != null) {+ const c = Number(d.sol_change_24h);+ chgEl.textContent = `${c >= 0 ? '+' : ''}${c.toFixed(1)}%`;+ chgEl.className = `tt-pulse-chg ${c >= 0 ? 'up' : 'down'}`;+ }+ } catch { /* pulse is decorative — silent */ }+}- let data;+// ── feed ─────────────────────────────────────────────────────────────────────────+async function loadFeed(reset) {+ const feed = $('#ttFeed');+ if (reset) feed.innerHTML = skeletonRows(7);try {- const r = await fetch(`${API}?${q}`);- if (!r.ok) throw new Error(`HTTP ${r.status}`);- data = await r.json();+ const rows = state.tab === 'exits' ? await fetchExits() : await fetchLaunches();+ state.rows = rows;+ renderFeed(rows);} catch {- btn.disabled = false;- btn.textContent = 'Load more';- return;- }-- if (!data?.items?.length) {- btn.hidden = true;- return;- }-- state.cursor = data.next_cursor || null;- renderItems(data.items, false);-- btn.disabled = false;- if (!state.cursor) {- btn.hidden = true;- } else {- btn.textContent = 'Load more';+ if (reset) feed.innerHTML = feedState('Could not load the feed.', 'Retry', () => loadFeed(true));}}-// ── Stats bar ─────────────────────────────────────────────────────────────────--function renderStats(items) {- const pnls = items.map((t) => t.realized_pnl_pct).filter((p) => p != null);- const mults = items.map((t) => t.multiple).filter((m) => m != null && m > 0);- const traders = new Set(items.map((t) => t.agent_id)).size;- const avgPnl = pnls.length ? pnls.reduce((a, b) => a + b, 0) / pnls.length : null;- const bestMult = mults.length ? Math.max(...mults) : null;-- const el = (id) => $(id) || { textContent: '' };- el('#tf-stat-wins').textContent = items.length;- el('#tf-stat-avg-pnl').textContent = avgPnl != null ? `+${Math.round(avgPnl)}%` : '—';- el('#tf-stat-best').textContent = bestMult != null ? `${bestMult.toFixed(1)}×` : '—';- el('#tf-stat-traders').textContent = traders || '—';+async function fetchLaunches() {+ const q = new URLSearchParams({ network: state.network, limit: '40' });+ const r = await fetch(`/api/pump/launches?${q}`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(String(r.status));+ const body = await r.json();+ const list = body?.data?.launches || body?.launches || [];+ return list.map((l) => ({+ kind: 'launch',+ mint: l.mint,+ symbol: (l.symbol || l.mint?.slice(0, 4) || '?').toUpperCase(),+ name: l.name || '',+ image_uri: l.image_uri || '',+ agent_name: l.agent_name || '',+ oracle_tier: l.oracle_tier || l.oracle?.tier || null,+ oracle_score: l.oracle_score ?? l.oracle?.score ?? null,+ ts: l.created_at || null,+ }));}-// ── Card render ───────────────────────────────────────────────────────────────--const TIER_LABEL = { prime: 'Prime', strong: 'Strong', lean: 'Lean', watch: 'Watch', avoid: 'Avoid' };--function buildShareText(t) {- const sym = (t.symbol || t.mint?.slice(0, 6) || '?').toUpperCase();- const mult = t.multiple != null ? `${t.multiple.toFixed(2)}×` : null;- const pct = t.realized_pnl_pct != null ? `+${Math.round(t.realized_pnl_pct)}%` : null;- const sol = t.realized_pnl_sol != null ? `+${t.realized_pnl_sol.toFixed(3)} SOL` : null;- const hold = t.hold_seconds != null ? holdTime(t.hold_seconds) : null;- const agent = t.agent_name || shortAddr(t.agent_id || '');- const tier = t.oracle_tier ? ` [${t.oracle_tier.toUpperCase()}]` : '';-- const parts = [`$${sym}${tier}`];- if (mult) parts.push(mult);- if (pct) parts.push(pct);- if (sol) parts.push(sol);- if (hold) parts.push(`in ${hold}`);-- return `${parts.join(' · ')} by ${agent} on @trythreews\nCopy this trader:`;+async function fetchExits() {+ const q = new URLSearchParams({ network: state.network, window: '7d', min_pnl_pct: '10', limit: '40' });+ const r = await fetch(`/api/trades/feed?${q}`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(String(r.status));+ const body = await r.json();+ return (body?.items || []).map((t) => ({+ kind: 'exit',+ mint: t.mint,+ symbol: (t.symbol || t.mint?.slice(0, 4) || '?').toUpperCase(),+ name: t.name || '',+ image_uri: t.image_uri || '',+ agent_name: t.agent_name || '',+ oracle_tier: t.oracle_tier || null,+ pnl_pct: t.realized_pnl_pct,+ multiple: t.multiple,+ ts: t.closed_at || null,+ }));}-function cardHtml(t) {- const sym = escapeHtml((t.symbol || t.mint?.slice(0, 6) || '?').toUpperCase());- const name = t.name ? escapeHtml(t.name) : '';- const imgSrc = t.image_uri ? escapeHtml(t.image_uri) : '';- const agentImg = t.agent_image ? escapeHtml(t.agent_image) : '';- const agentName = escapeHtml(t.agent_name || shortAddr(t.agent_id || ''));- const traderUrl = `/trader/${escapeHtml(t.agent_id || '')}`;-- const pumpUrl = t.mint ? `https://pump.fun/${escapeHtml(t.mint)}` : null;- const coinHref = t.mint && t.oracle_score != null ? `/oracle?mint=${escapeHtml(t.mint)}` : (pumpUrl || '#');- const coinTarget = t.oracle_score != null ? '' : ' target="_blank" rel="noopener"';- const imgHtml = `<a href="${coinHref}"${coinTarget} class="tf-coin-img-link" aria-label="View ${sym} conviction on Oracle" style="display:block;line-height:0">${imgSrc- ? `<img loading="lazy" decoding="async" src="${imgSrc}" alt="" class="tf-coin-img" style="width:48px;height:48px;border-radius:12px;object-fit:cover" onerror="this.outerHTML='<div class=tf-coin-img>${sym.slice(0, 2)}</div>'" loading="lazy" />`- : `<div class="tf-coin-img">${sym.slice(0, 2)}</div>`}</a>`;-- const agentImgHtml = agentImg- ? `<img src="${agentImg}" alt="" class="tf-agent-img" style="width:18px;height:18px;border-radius:50%;object-fit:cover" onerror="this.style.display='none'" loading="lazy" />`- : '';-- const tierBadge = t.oracle_tier && t.oracle_tier !== 'avoid'- ? `<span class="tf-tier-badge ${escapeHtml(t.oracle_tier)}">${escapeHtml(TIER_LABEL[t.oracle_tier] || t.oracle_tier)}</span>`- : '';-- const catBadge = t.oracle_category- ? `<span class="tf-category">${escapeHtml(t.oracle_category.replace(/_/g, ' '))}</span>`- : '';-- const copierBadge = t.copier_count > 0- ? `<span class="tf-copier-badge">${t.copier_count} copier${t.copier_count !== 1 ? 's' : ''}</span>`- : '';-- const pnlPct = t.realized_pnl_pct != null ? `+${Math.round(t.realized_pnl_pct)}%` : null;- const pnlSol = t.realized_pnl_sol != null ? `+${t.realized_pnl_sol.toFixed(3)} SOL` : null;- const multStr = t.multiple != null ? `${t.multiple.toFixed(2)}×` : null;- const hold = t.hold_seconds != null ? holdTime(t.hold_seconds) : null;- const when = t.closed_at ? relTime(t.closed_at) : '';-- const scoreStr = t.oracle_score != null ? `Score ${Math.round(t.oracle_score)}` : '';-- const oracleUrl = t.mint && t.oracle_score != null ? `/oracle?mint=${escapeHtml(t.mint)}` : null;- const buySig = t.buy_sig ? `https://solscan.io/tx/${escapeHtml(t.buy_sig)}` : null;- const sellSig = t.sell_sig ? `https://solscan.io/tx/${escapeHtml(t.sell_sig)}` : null;-- // Share text — pre-formatted tweet-ready PnL card- const shareText = buildShareText(t);- // Use the SSR share page so social crawlers get a rich preview- const shareUrl = t.agent_id- ? `https://three.ws/trader/${encodeURIComponent(t.agent_id)}/share`- : `https://three.ws${traderUrl}`;- const tweetHref = `https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(shareUrl)}`;- // data-share attribute carries the share payload for native Web Share API- const shareData = encodeURIComponent(JSON.stringify({ text: shareText, url: shareUrl }));-- const isWatched = t.mint ? readWatchlist().has(t.mint) : false;- const watchLabel = isWatched ? '★ Watching' : '☆ Watch';-- return `<article class="tf-card tf-win" aria-label="${sym} trade by ${agentName}">+const TIER_CLASS = { prime: 'prime', strong: 'strong', lean: 'lean', watch: 'watch', avoid: 'avoid' };++function rowHtml(r, { pinned = false } = {}) {+ const seed = escapeHtml(JSON.stringify({ symbol: r.symbol, name: r.name, image_uri: r.image_uri }));+ const initials = escapeHtml(r.symbol.slice(0, 2));+ const imgHtml = r.image_uri+ ? `<img src="${escapeHtml(r.image_uri)}" alt="" class="tt-row-img" loading="lazy" onerror="this.outerHTML='<span class=tt-row-ini>${initials}</span>'" />`+ : `<span class="tt-row-ini">${initials}</span>`;+ const tier = r.oracle_tier && r.oracle_tier !== 'avoid'+ ? `<span class="tt-tier ${TIER_CLASS[r.oracle_tier] || ''}">${escapeHtml(r.oracle_tier)}</span>` : '';+ let right = '';+ if (r.kind === 'exit') {+ const up = Number(r.pnl_pct) >= 0;+ right = `<span class="tt-row-pnl ${up ? 'up' : 'down'}">${r.multiple != null ? `${Number(r.multiple).toFixed(2)}×` : ''}${r.pnl_pct != null ? ` +${Math.round(r.pnl_pct)}%` : ''}</span>`;+ } else if (pinned) {+ right = '<span class="tt-row-pin">★</span>';+ } else if (r.oracle_score != null) {+ right = `<span class="tt-row-score">${Math.round(r.oracle_score)}</span>`;+ }+ return `<button type="button" class="tt-row${pinned ? ' tt-row--pin' : ''}${state.selected === r.mint ? ' on' : ''}" data-mint="${escapeHtml(r.mint)}" data-seed="${seed}">${imgHtml}-- <div class="tf-main">- <div class="tf-coin-row">- <a href="${coinHref}"${coinTarget} class="tf-coin-sym" style="color:inherit;text-decoration:none" aria-label="View ${sym} Oracle conviction">$${sym}</a>- ${name ? `<span class="tf-coin-name">${name}</span>` : ''}- ${tierBadge}- ${catBadge}- </div>- <div class="tf-agent-row">- ${agentImgHtml}- <a href="${traderUrl}" class="tf-agent-name">${agentName}</a>- ${copierBadge}- </div>- <div class="tf-meta-row">- ${hold ? `<span class="tf-meta-item">Held <b>${hold}</b></span>` : ''}- ${when ? `<span class="tf-meta-item">${when}</span>` : ''}- ${t.exit_reason ? `<span class="tf-meta-item">Exit <b>${escapeHtml(t.exit_reason.replace(/_/g, ' '))}</b></span>` : ''}- ${scoreStr ? `<span class="tf-meta-item">${scoreStr}</span>` : ''}- </div>- </div>-- <div class="tf-pnl">- ${multStr ? `<div class="tf-multiple">${multStr}</div>` : ''}- ${pnlPct ? `<div class="tf-pnl-pct">${pnlPct}</div>` : ''}- ${pnlSol ? `<div class="tf-pnl-sol">${pnlSol}</div>` : ''}- ${t.exit_reason ? `<div class="tf-exit-reason">${escapeHtml(t.exit_reason.replace(/_/g, ' '))}</div>` : ''}- </div>-- <div class="tf-actions">- <a href="${traderUrl}" class="tf-btn primary">Copy trader →</a>- <button type="button" class="tf-btn tf-share-btn" data-share="${shareData}" data-tweet="${escapeHtml(tweetHref)}" aria-label="Share this trade">Share ↗</button>- ${t.mint ? `<button type="button" class="tf-btn tf-watch-btn${isWatched ? ' tf-watching' : ''}" data-mint="${escapeHtml(t.mint)}" aria-pressed="${isWatched}" title="Add to watchlist">${watchLabel}</button>` : ''}- ${oracleUrl ? `<a href="${oracleUrl}" class="tf-btn" style="background:rgba(192,132,252,0.12);border-color:rgba(192,132,252,0.35);color:#c084fc">Oracle ↗</a>` : ''}- ${pumpUrl ? `<a href="${pumpUrl}" class="tf-btn" target="_blank" rel="noopener">pump.fun ↗</a>` : ''}- ${buySig ? `<a href="${buySig}" class="tf-btn" target="_blank" rel="noopener">Buy tx ↗</a>` : ''}- ${sellSig ? `<a href="${sellSig}" class="tf-btn" target="_blank" rel="noopener">Sell tx ↗</a>` : ''}- </div>- </article>`;+ <span class="tt-row-main">+ <span class="tt-row-top"><b>$${escapeHtml(r.symbol)}</b>${r.name ? `<span class="tt-row-name">${escapeHtml(r.name)}</span>` : ''}${tier}</span>+ <span class="tt-row-sub">${r.agent_name ? escapeHtml(r.agent_name) : shortAddr(r.mint, 4, 4)}${r.ts ? ` · ${escapeHtml(relTime(r.ts))}` : ''}</span>+ </span>+ ${right}+ </button>`;}-// ── DOM helpers ───────────────────────────────────────────────────────────────--function showSkeletons() {- const grid = $('#tfGrid');- grid.setAttribute('aria-busy', 'true');- grid.innerHTML = Array.from({ length: 8 }, () => '<div class="tf-skel" aria-hidden="true"></div>').join('');- $('#tfLoadMore').hidden = true;-}--function renderItems(items, reset) {- const grid = $('#tfGrid');- grid.removeAttribute('aria-busy');- if (reset) {- grid.innerHTML = items.map(cardHtml).join('');- } else {- grid.insertAdjacentHTML('beforeend', items.map(cardHtml).join(''));+function renderFeed(rows) {+ const feed = $('#ttFeed');+ // $THREE is always pinned at the top of the launches view (and never duplicated).+ const pinned = state.tab === 'launches'+ ? rowHtml({ kind: 'launch', mint: THREE_MINT, symbol: 'THREE', name: 'three.ws · platform coin', image_uri: '', agent_name: 'The only coin', oracle_tier: null }, { pinned: true })+ : '';+ const body = rows.filter((r) => !(state.tab === 'launches' && r.mint === THREE_MINT))+ .map((r) => rowHtml(r)).join('');+ if (!rows.length && !pinned) {+ feed.innerHTML = feedState(+ state.tab === 'exits' ? 'No profitable agent exits in this window yet.' : 'No launches on this network yet.',+ '', null,+ );+ return;}+ feed.innerHTML = pinned + body;+ highlightRow(state.selected);}-function showEmpty() {- const grid = $('#tfGrid');- grid.removeAttribute('aria-busy');- grid.innerHTML = `<div class="tf-state">- <h2>No trades yet</h2>- <p>No positions meeting the current filters have closed in this window.<br>- Try a wider window or lower minimum PnL threshold, or check back shortly.</p>- </div>`;- $('#tfLoadMore').hidden = true;+// ── feed states ───────────────────────────────────────────────────────────────+function skeletonRows(n) {+ return Array.from({ length: n }, () => '<div class="tt-row tt-row--skel"><span class="tt-row-ini sk"></span><span class="tt-row-main"><span class="sk sk-l"></span><span class="sk sk-s"></span></span></div>').join('');}--function showError() {- const grid = $('#tfGrid');- grid.removeAttribute('aria-busy');- grid.innerHTML = `<div class="tf-state">- <h2>Could not load feed</h2>- <p>There was a problem reaching the server. <button class="tf-btn" onclick="location.reload()">Try again</button></p>- </div>`;- $('#tfLoadMore').hidden = true;+function feedState(msg, action, fn) {+ const id = action ? `tt-fs-${Math.random().toString(36).slice(2, 8)}` : '';+ if (action && fn) setTimeout(() => { const b = document.getElementById(id); if (b) b.addEventListener('click', fn); }, 0);+ return `<div class="tt-feed-state"><p>${escapeHtml(msg)}</p>${action ? `<button id="${id}" class="tt-mini-btn">${escapeHtml(action)}</button>` : ''}</div>`;}