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(launches): replace coin scores with neutral token stats, shared chart embeds, and pump.fun candles for young coins
nirholasba48c672de18
diff --git a/api/pump/launch-og.js b/api/pump/launch-og.jsindex ba6ea08dd..93dbb775b 100644--- a/api/pump/launch-og.js+++ b/api/pump/launch-og.js@@ -15,9 +15,13 @@* top-left — three.ws wordmark + "pump.fun launch"* hero left — coin image (120×120 circle, fetched and base64'd if available)* hero right — name (large), symbol, mint short- * mid-left — quality score badge + organic/bundle signals- * mid-right — price / market cap- * outcome — "GRADUATED ✓" or "RUGGED ✕" or "LIVE" pill (bottom-right)+ * mid-left : launch activity: unique buyers, buys and sells (raw counts)+ * mid-right : market cap+ * outcome : "GRADUATED ✓" or "LIVE" pill (bottom-right)+ *+ * Neutral by design: the card never carries a score, grade, or engine label+ * such as "rugged". A shared card is a statement about someone's coin, and a+ * number on it reads as investment advice when high and as FUD when low.* footer — three.ws branding*/@@ -58,23 +62,6 @@ function fmtNum(v) {return `$${n.toFixed(4)}`;}-// pump_coin_intel stores organic_score and bundle_score as 0..1 fractions (the-// enrichment writes ratios, e.g. 0.4279), while the card draws them as percent-// bars. Convert once, here, so a 43% organic launch renders a 43% bar instead of-// the 0%/1px sliver it drew when the raw fraction was fed straight to the gauge.-function scoreToPercent(v) {- const n = Number(v);- if (!Number.isFinite(n) || n <= 0) return 0;- return Math.min(100, n * 100);-}--function qualityColor(score) {- if (score == null) return '#6b7280';- if (score >= 70) return '#22c55e';- if (score >= 40) return '#f59e0b';- return '#ef4444';-}-// Fetch the coin's logo from pump.fun as base64 — if it times out or fails,// we just omit the image; the card still renders fine without it.async function fetchLogoBase64(imageUri) {@@ -105,8 +92,8 @@ async function buildCardData(mint) {LIMIT 1`,sql`- SELECT name, symbol, image_uri, quality_score, organic_score, bundle_score,- category, description, buy_count, sell_count, unique_buyers, creator+ SELECT name, symbol, image_uri, category, description,+ buy_count, sell_count, unique_buyers, creatorFROM pump_coin_intelWHERE mint = ${mint}LIMIT 1@@ -126,7 +113,6 @@ async function buildCardData(mint) {const name = intel?.name || reg?.name || '';const symbol = intel?.symbol || reg?.symbol || '';const imageUri = intel?.image_uri || null;- const qualityScore = intel?.quality_score ?? null;const category = intel?.category || '';const isThreeWsLaunch = !!reg;@@ -144,7 +130,7 @@ async function buildCardData(mint) {wantsLiveMcap ? fetchLiveMarketCap(mint) : Promise.resolve(null),]);- return { name, symbol, imageUri, logoBase64, qualityScore, category, isThreeWsLaunch, intel, outcome, liveMcap };+ return { name, symbol, imageUri, logoBase64, category, isThreeWsLaunch, intel, outcome, liveMcap };}// Live USD market cap for a coin still on the curve. Any failure returns null and@@ -165,22 +151,18 @@ async function fetchLiveMarketCap(mint) {}export function renderCard(mint, d) {- const { name, symbol, logoBase64, qualityScore, category, isThreeWsLaunch, intel, outcome, liveMcap } = d;+ const { name, symbol, logoBase64, category, isThreeWsLaunch, intel, outcome, liveMcap } = d;const displayName = trunc(name || 'Unknown coin', 36);const displaySym = symbol ? `$${symbol.toUpperCase()}` : '';const mc = liveMcap ?? outcome?.ath_market_cap_usd ?? outcome?.last_market_cap_usd ?? null;const mcText = mc ? fmtNum(mc) : '';- const qColor = qualityColor(qualityScore);- const qText = qualityScore != null ? String(Math.round(qualityScore)) : '-';+ const accent = '#818cf8';let outcomePill = '';if (outcome?.graduated) {outcomePill = `<rect x="870" y="510" width="260" height="68" rx="10" fill="#16a34a22"/><text x="890" y="553" fill="#22c55e" font-size="22" font-weight="600">GRADUATED ✓</text>`;- } else if (outcome?.rugged) {- outcomePill = `<rect x="870" y="510" width="240" height="68" rx="10" fill="#dc262622"/>- <text x="890" y="553" fill="#ef4444" font-size="22" font-weight="600">RUGGED ✕</text>`;} else {outcomePill = `<circle cx="891" cy="545" r="7" fill="#22c55e"><animate attributeName="opacity" values="1;0.3;1" dur="1.8s" repeatCount="indefinite"/>@@ -188,13 +170,6 @@ export function renderCard(mint, d) {<text x="908" y="552" fill="#22c55e" font-size="20" font-weight="500">LIVE</text>`;}- // Organic vs bundle gauge bar (230 px wide, so 2.3 px per percentage point).- const organic = scoreToPercent(intel?.organic_score);- const organicW = Math.round(organic * 2.3);- const bundle = scoreToPercent(intel?.bundle_score);- // 0.3 is the coordinated-launch threshold api/_lib/market-realness.js uses.- const bundleColor = bundle > 30 ? '#ef4444' : '#f59e0b';-// Horizontal divider y-position.const imgBlock = logoBase64? `<image href="${logoBase64}" x="80" y="150" width="120" height="120" clip-path="url(#imgCircle)"/>`@@ -211,16 +186,12 @@ export function renderCard(mint, d) {<stop offset="0%" stop-color="#0a0b0f"/><stop offset="100%" stop-color="#0f1119"/></linearGradient>- <linearGradient id="scoreGrad" x1="0" y1="0" x2="0" y2="1">- <stop offset="0%" stop-color="${qColor}" stop-opacity="0.25"/>- <stop offset="100%" stop-color="${qColor}" stop-opacity="0.08"/>- </linearGradient></defs><!-- Background --><rect width="1200" height="630" fill="url(#bg)"/><!-- Subtle top border -->- <rect x="0" y="0" width="1200" height="3" fill="${qColor}" opacity="0.7"/>+ <rect x="0" y="0" width="1200" height="3" fill="${accent}" opacity="0.7"/><!-- Header row --><text x="80" y="92" fill="rgba(229,229,229,0.9)"@@ -248,25 +219,16 @@ export function renderCard(mint, d) {<!-- Divider --><line x1="80" y1="316" x2="1120" y2="316" stroke="rgba(255,255,255,0.07)" stroke-width="1"/>- <!-- Quality score block -->- <rect x="80" y="342" width="130" height="130" rx="12" fill="url(#scoreGrad)" stroke="${qColor}" stroke-width="1.5" stroke-opacity="0.6"/>- <text x="145" y="415" text-anchor="middle" fill="${qColor}"- font-family="Inter,-apple-system,system-ui,sans-serif"- font-size="54" font-weight="700">${x(qText)}</text>- <text x="145" y="454" text-anchor="middle" fill="rgba(229,229,229,0.35)"- font-size="14" font-weight="500" letter-spacing="2">SCORE</text>-- <!-- Organic / bundle bar -->- ${intel?.organic_score != null ? `- <text x="240" y="370" fill="rgba(229,229,229,0.4)" font-size="14" letter-spacing="2">ORGANIC BUY</text>- <rect x="240" y="380" width="230" height="8" rx="4" fill="rgba(255,255,255,0.08)"/>- <rect x="240" y="380" width="${organicW}" height="8" rx="4" fill="#22c55e"/>- <text x="480" y="390" fill="#22c55e" font-size="14" font-weight="600" text-anchor="end">${Math.round(organic)}%</text>-- <text x="240" y="420" fill="rgba(229,229,229,0.4)" font-size="14" letter-spacing="2">BUNDLE</text>- <rect x="240" y="430" width="230" height="8" rx="4" fill="rgba(255,255,255,0.08)"/>- <rect x="240" y="430" width="${Math.round(bundle * 2.3)}" height="8" rx="4" fill="${bundleColor}"/>- <text x="480" y="440" fill="${bundleColor}" font-size="14" font-weight="600" text-anchor="end">${Math.round(bundle)}%</text>+ <!-- Launch activity: raw counts only -->+ ${intel?.unique_buyers ? `+ <text x="80" y="375" fill="rgba(229,229,229,0.4)" font-size="14" letter-spacing="2">UNIQUE BUYERS</text>+ <text x="80" y="440" fill="rgba(229,229,229,0.85)"+ font-size="44" font-weight="300">${x(String(intel.unique_buyers))}</text>+ ` : ''}+ ${intel?.buy_count != null && intel?.sell_count != null ? `+ <text x="400" y="375" fill="rgba(229,229,229,0.4)" font-size="14" letter-spacing="2">BUYS / SELLS AT LAUNCH</text>+ <text x="400" y="440" fill="rgba(229,229,229,0.85)"+ font-size="44" font-weight="300">${x(`${intel.buy_count} / ${intel.sell_count}`)}</text>` : ''}<!-- Market cap -->@@ -277,13 +239,6 @@ export function renderCard(mint, d) {font-size="52" font-weight="300" letter-spacing="-1">${x(mcText)}</text>` : ''}- <!-- Buyers -->- ${intel?.unique_buyers ? `- <text x="560" y="375" fill="rgba(229,229,229,0.4)" font-size="14" letter-spacing="2">UNIQUE BUYERS</text>- <text x="560" y="440" fill="rgba(229,229,229,0.85)"- font-size="44" font-weight="300">${x(String(intel.unique_buyers))}</text>- ` : ''}-<!-- Outcome pill -->${outcomePill}@@ -319,7 +274,7 @@ export default wrap(async (req, res) => {// because swallowing it silently made a real outage indistinguishable from// a coin we simply have no data on: both render the same blank card.console.warn('[launch-og] card data failed for %s: %s', mint, err?.message || err);- data = { name: '', symbol: '', logoBase64: null, qualityScore: null, category: '', isThreeWsLaunch: false, intel: null, outcome: null, liveMcap: null };+ data = { name: '', symbol: '', logoBase64: null, category: '', isThreeWsLaunch: false, intel: null, outcome: null, liveMcap: null };}const svg = renderCard(mint, data);diff --git a/api/pump/price-history.js b/api/pump/price-history.jsindex 05eb23cc2..cf5eea30d 100644--- a/api/pump/price-history.js+++ b/api/pump/price-history.js@@ -3,7 +3,11 @@// OHLCV proxy with automatic fallback chain:// 1. Birdeye (paid, quota-limited) — best data quality// 2. GeckoTerminal (free, no key) — pool lookup then candles-// 3. The last good candles for this mint+interval, served as `stale: true`+// 3. pump.fun's own candle API (free, no key). GeckoTerminal indexes a new+// pump.fun coin only once it trades enough, so a young three.ws launch had+// a live, trading market and still rendered "no price history". pump.fun+// charts its own bonding curves from the first trade.+// 4. The last good candles for this mint+interval, served as `stale: true`//// On any upstream failure the next source is tried transparently.// Never fabricates candles.@@ -17,7 +21,7 @@// candles already land on those boundaries, so the response is identical while// every poll inside one candle shares a single cache entry.//-// Response: { data: [ { t, o, h, l, c, v } ], source?: 'birdeye'|'gecko', stale?: true }+// Response: { data: [ { t, o, h, l, c, v } ], source?: 'birdeye'|'gecko'|'pumpfun', stale?: true }import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -247,6 +251,84 @@ async function fetchGeckoOhlcv({ mint, interval, from, to }) {.sort((a, b) => a.t - b.t);}+// ──────────────────────────────────────────────────────────────────────────────+// pump.fun candles: the rung that knows a coin from its first trade.+// The API accepts a fixed interval set and always answers the most recent+// `limit` (max 1000) candles in ascending order, so every interval it lacks is+// built from its nearest base interval and the result is filtered to the window.+// ──────────────────────────────────────────────────────────────────────────────+const PUMP_CANDLES_API = 'https://swap-api.pump.fun/v1/coins';+const PUMP_CANDLE_LIMIT = 1000;++// Our normalized interval → [pump.fun base interval, candles per bucket].+const PUMP_INTERVALS = {+ '1m': ['1m', 1],+ '3m': ['1m', 3],+ '5m': ['5m', 1],+ '15m': ['15m', 1],+ '30m': ['30m', 1],+ '1H': ['1h', 1],+ '2H': ['1h', 2],+ '4H': ['4h', 1],+ '6H': ['6h', 1],+ '8H': ['4h', 2],+ '12H': ['12h', 1],+ '1D': ['24h', 1],+ '3D': ['24h', 3],+ '1W': ['24h', 7],+ '1M': ['24h', 30],+};++/**+ * Folds consecutive candles into buckets of `width` seconds aligned to the Unix+ * epoch, the same alignment every other source uses. Exported for the tests.+ */+export function aggregateCandles(candles, width) {+ const out = [];+ for (const c of candles) {+ const t = Math.floor(c.t / width) * width;+ const last = out[out.length - 1];+ if (last && last.t === t) {+ last.h = Math.max(last.h, c.h);+ last.l = Math.min(last.l, c.l);+ last.c = c.c;+ last.v += c.v;+ } else {+ out.push({ t, o: c.o, h: c.h, l: c.l, c: c.c, v: c.v });+ }+ }+ return out;+}++/** Maps pump.fun's string-typed, millisecond candle rows to our shape. Exported for the tests. */+export function mapPumpCandles(rows) {+ if (!Array.isArray(rows)) return [];+ return rows+ .map((r) => ({+ t: Math.floor(Number(r?.timestamp) / 1000),+ o: Number(r?.open),+ h: Number(r?.high),+ l: Number(r?.low),+ c: Number(r?.close),+ v: Number(r?.volume) || 0,+ }))+ .filter((d) => Number.isFinite(d.t) && d.t > 0 && Number.isFinite(d.c) && d.c > 0)+ .sort((a, b) => a.t - b.t);+}++async function fetchPumpOhlcv({ mint, interval, from, to }) {+ const [base, factor] = PUMP_INTERVALS[interval] || PUMP_INTERVALS['15m'];+ const url = `${PUMP_CANDLES_API}/${mint}/candles?interval=${base}&limit=${PUMP_CANDLE_LIMIT}¤cy=USD`;+ const resp = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });+ // pump.fun answers 4xx for a mint it never launched: not a pump.fun market.+ if (resp.status >= 400 && resp.status < 500) throw new NoPoolError(`pump.fun candles ${resp.status}`);+ if (!resp.ok) throw new Error(`pump.fun candles ${resp.status}`);+ const rows = mapPumpCandles(await resp.json().catch(() => null));+ if (!rows.length) throw new NoPoolError('pump.fun has no trades for this mint');+ const candles = factor > 1 ? aggregateCandles(rows, intervalSeconds(interval)) : rows;+ return candles.filter((d) => d.t >= from && d.t <= to);+}+// ──────────────────────────────────────────────────────────────────────────────// Cache — shared across both sources. Key includes interval + time window.// ──────────────────────────────────────────────────────────────────────────────@@ -281,7 +363,7 @@ function recallGood(mint, interval) {// just shrinking its blast radius.const _inflight = new Map(); // key → Promise<result descriptor>-// Runs the Birdeye → GeckoTerminal → stale-cache chain once and returns a+// Runs the Birdeye → GeckoTerminal → pump.fun → stale-cache chain once and returns a// plain descriptor the caller turns into an HTTP response. Never throws —// every failure mode is represented in the descriptor.async function resolveCandles({ mint, interval, from, to, key, now }) {@@ -297,6 +379,7 @@ async function resolveCandles({ mint, interval, from, to, key, now }) {}}+ let geckoNoPool = false;try {const data = await fetchGeckoOhlcv({ mint, interval, from, to });_cache.set(key, { value: data, source: 'gecko', expiresAt: now + TTL_MS });@@ -304,12 +387,24 @@ async function resolveCandles({ mint, interval, from, to, key, now }) {rememberGood(mint, interval, data, 'gecko');return { kind: 'ok', data, source: 'gecko' };} catch (err) {- // A token with no market has nothing to chart — say so plainly. This is a- // designed empty state, not an outage, so it is never served from stale.- if (err instanceof NoPoolError) return { kind: 'no_market' };- // Both live sources exhausted — fall through to the stale tier.+ geckoNoPool = err instanceof NoPoolError;}+ let pumpNoMarket = false;+ try {+ const data = await fetchPumpOhlcv({ mint, interval, from, to });+ _cache.set(key, { value: data, source: 'pumpfun', expiresAt: now + TTL_MS });+ if (_cache.size > 256) _cache.delete(_cache.keys().next().value);+ rememberGood(mint, interval, data, 'pumpfun');+ return { kind: 'ok', data, source: 'pumpfun' };+ } catch (err) {+ pumpNoMarket = err instanceof NoPoolError;+ }++ // A token no source has a market for has nothing to chart: say so plainly.+ // This is a designed empty state, not an outage, so it is never served stale.+ if (geckoNoPool && pumpNoMarket) return { kind: 'no_market' };+const stale = recallGood(mint, interval);if (stale) return { kind: 'ok', data: stale.value, source: stale.source, stale: true, as_of: Math.floor(stale.at / 1000) };diff --git a/api/pump/token-stats.js b/api/pump/token-stats.jsnew file mode 100644index 000000000..e3b2f9632--- /dev/null+++ b/api/pump/token-stats.js@@ -0,0 +1,321 @@+/**+ * /api/pump/token-stats: the neutral, trader-terminal fact sheet behind the+ * "Token stats" panel on /launches/<mint>.+ *+ * GET /api/pump/token-stats?mint=<mint>+ *+ * Facts only, never a verdict. Every field is a number or a state read straight+ * from a public source, so the page can show what GMGN-style terminals show+ * without scoring, ranking, or labeling anyone's coin:+ *+ * · windows 5m / 1h / 6h / 24h volume, buys, sells, buy and sell volume,+ * net buy, unique traders, price change (pump.fun swap API+ * trades, paged back up to 24h)+ * · holders holder count, top-10 share, top holder, dev share, bonding+ * curve share, early-buyer share, top-10 list (Helius DAS)+ * · authorities mint and freeze authority as read off the mint account+ * · curve bonding curve progress, curve reserves, graduation state+ * · market liquidity and DEX Screener paid-profile state+ *+ * A field that could not be read is null, never 0, so the client renders "-"+ * instead of a made-up figure. mainnet only: pump.fun has no devnet market.+ */++import { PublicKey } from '@solana/web3.js';+import { unpackMint } from '@solana/spl-token';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { cacheWrapLastGood } from '../_lib/cache.js';+import { pumpFetchJson, PUMP_FRONTEND_BASE, PUMP_SWAP_BASE } from '../_lib/pump-feed-fetch.js';+import { liveHolderSet } from '../_lib/coin/cohorts-live.js';+import { getConnection } from '../_lib/pump.js';+import { solPriceUsd } from '../_lib/sol-price.js';++const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const DEXSCREENER = 'https://api.dexscreener.com';++const TRADE_PAGE = 100;+const TRADE_MAX_PAGES = 15; // 1,500 trades: a full day for all but the busiest coins+const DAY_SEC = 86_400;+// pump.fun bonding curves start with 793.1M tokens available to buy; progress is+// the share of that pool already bought out.+const INITIAL_REAL_TOKEN_RESERVES = 793_100_000_000_000n;+// A buy landing within this many seconds of creation counts as an early buy.+const EARLY_BUY_SEC = 5;+const CACHE_TTL_S = 20;++export const WINDOWS = [+ { key: '5m', sec: 300 },+ { key: '1h', sec: 3600 },+ { key: '6h', sec: 21_600 },+ { key: '24h', sec: DAY_SEC },+];++const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+};++/** Normalize one swap-API trade row. Rows without a timestamp or side are dropped. */+export function normalizeTrade(t) {+ const ts = Date.parse(t?.timestamp);+ const side = String(t?.type || '').toLowerCase();+ if (!Number.isFinite(ts) || (side !== 'buy' && side !== 'sell')) return null;+ return {+ t: Math.floor(ts / 1000),+ buy: side === 'buy',+ user: t.userAddress || t.user || null,+ usd: num(t.amountUsd) ?? 0,+ sol: num(t.amountSol) ?? 0,+ price: num(t.priceUsd),+ };+}++/**+ * Roll normalized trades (any order) into per-window stats. `coveredFrom` is the+ * oldest timestamp the fetched history reaches, or null when the history is the+ * coin's complete trade list; a window reaching past it is flagged partial.+ */+export function windowStats(trades, { now, coveredFrom = null }) {+ const sorted = [...trades].sort((a, b) => a.t - b.t);+ const last = sorted.length ? sorted[sorted.length - 1] : null;+ return Object.fromEntries(+ WINDOWS.map((w) => {+ const start = now - w.sec;+ const inWin = sorted.filter((x) => x.t >= start);+ const makers = new Set();+ let buys = 0;+ let sells = 0;+ let buyUsd = 0;+ let sellUsd = 0;+ for (const x of inWin) {+ if (x.user) makers.add(x.user);+ if (x.buy) {+ buys++;+ buyUsd += x.usd;+ } else {+ sells++;+ sellUsd += x.usd;+ }+ }+ // Price change: last trade price against the last trade before the window+ // opened (the price the window started at). No prior trade means the coin+ // did not exist yet, so the first trade inside the window is the base.+ let change = null;+ if (last?.price) {+ const before = sorted.filter((x) => x.t < start && x.price);+ const base = before.length ? before[before.length - 1] : inWin.find((x) => x.price);+ if (base?.price && base !== last) change = ((last.price - base.price) / base.price) * 100;+ else if (base === last) change = 0;+ }+ return [+ w.key,+ {+ volume_usd: buyUsd + sellUsd,+ buys,+ sells,+ buy_usd: buyUsd,+ sell_usd: sellUsd,+ net_buy_usd: buyUsd - sellUsd,+ traders: makers.size,+ price_change_pct: change,+ partial: coveredFrom != null && coveredFrom > start,+ },+ ];+ }),+ );+}++/** Page the swap API back until a day of history, the coin's first trade, or the page cap. */+async function fetchDayOfTrades(mint, now) {+ const out = [];+ let cursor = null;+ let complete = false;+ for (let page = 0; page < TRADE_MAX_PAGES; page++) {+ const qs = new URLSearchParams({ limit: String(TRADE_PAGE) });+ if (cursor) qs.set('cursor', cursor);+ const { ok, body } = await pumpFetchJson(+ `${PUMP_SWAP_BASE}/v2/coins/${encodeURIComponent(mint)}/trades?${qs}`,+ { timeoutMs: 6000 },+ );+ if (!ok) {+ if (page === 0) return null;+ break;+ }+ const rows = (Array.isArray(body?.trades) ? body.trades : []).map(normalizeTrade).filter(Boolean);+ out.push(...rows);+ cursor = body?.pagination?.nextCursor || null;+ if (!body?.pagination?.hasMore || !cursor) {+ complete = true;+ break;+ }+ const oldest = rows.length ? Math.min(...rows.map((r) => r.t)) : now;+ if (oldest < now - DAY_SEC) break;+ }+ const oldest = out.length ? Math.min(...out.map((r) => r.t)) : null;+ return { trades: out, complete, oldest };+}++function shareOfSupply(units, supply) {+ if (supply <= 0n) return null;+ return Number((units * 1_000_000_000n) / supply) / 1_000_000_000;+}++/**+ * Holder facts over the live holder set. The bonding curve and AMM pool are+ * program-owned liquidity, not holders, so they are reported separately and+ * excluded from the top-holder ranking the way trading terminals do.+ */+export function holderStats(holders, { supply, creator, curve, pool, earlyBuyers }) {+ const program = new Set([curve, pool].filter(Boolean));+ const people = holders.filter((h) => !program.has(h.wallet));+ const byWallet = new Map(holders.map((h) => [h.wallet, h.units]));+ const sum = (list) => list.reduce((acc, h) => acc + h.units, 0n);+ const top10 = people.slice(0, 10);+ const early = earlyBuyers+ ? sum(people.filter((h) => earlyBuyers.has(h.wallet) && h.wallet !== creator))+ : null;+ return {+ count: people.length,+ top10_pct: shareOfSupply(sum(top10), supply),+ top1_pct: people[0] ? shareOfSupply(people[0].units, supply) : null,+ dev_pct: creator ? shareOfSupply(byWallet.get(creator) || 0n, supply) : null,+ curve_pct: curve ? shareOfSupply(byWallet.get(curve) || 0n, supply) : null,+ pool_pct: pool ? shareOfSupply(byWallet.get(pool) || 0n, supply) : null,+ early_buyers: earlyBuyers ? earlyBuyers.size : null,+ early_buyers_pct: early == null ? null : shareOfSupply(early, supply),+ top: top10.map((h) => ({+ wallet: h.wallet,+ pct: shareOfSupply(h.units, supply),+ is_dev: h.wallet === creator,+ })),+ };+}++async function readAuthorities(mint) {+ try {+ const mintPk = new PublicKey(mint);+ const info = await getConnection({ network: 'mainnet' }).getAccountInfo(mintPk, 'confirmed');+ if (!info) return null;+ const m = unpackMint(mintPk, info, info.owner);+ return {+ mint_authority: m.mintAuthority ? m.mintAuthority.toBase58() : null,+ freeze_authority: m.freezeAuthority ? m.freezeAuthority.toBase58() : null,+ };+ } catch {+ return null;+ }+}++async function readDexScreener(mint) {+ const [pairsRes, ordersRes] = await Promise.all([+ pumpFetchJson(`${DEXSCREENER}/tokens/v1/solana/${mint}`, { timeoutMs: 5000, retries: 0 }),+ pumpFetchJson(`${DEXSCREENER}/orders/v1/solana/${mint}`, { timeoutMs: 5000, retries: 0 }),+ ]);+ const pairs = pairsRes.ok && Array.isArray(pairsRes.body) ? pairsRes.body : [];+ const liquidity = pairs.reduce((acc, p) => acc + (num(p?.liquidity?.usd) || 0), 0);+ const orders = ordersRes.ok && Array.isArray(ordersRes.body?.orders) ? ordersRes.body.orders : null;+ return {+ liquidity_usd: liquidity > 0 ? liquidity : null,+ dex_paid: orders == null ? null : orders.some((o) => o?.type === 'tokenProfile' && o?.status === 'approved'),+ pair_url: pairs[0]?.url || null,+ };+}++async function buildStats(mint) {+ const now = Math.floor(Date.now() / 1000);+ const metaRes = await pumpFetchJson(`${PUMP_FRONTEND_BASE}/coins-v2/${mint}`, { timeoutMs: 5000 });+ const coin = metaRes.ok ? metaRes.body : null;++ const supply = coin?.total_supply != null ? BigInt(Math.round(Number(coin.total_supply))) : 1_000_000_000_000_000n;+ const creator = coin?.creator || null;+ const curve = coin?.bonding_curve || null;+ const pool = coin?.pool_address || null;+ const createdSec = num(coin?.created_timestamp) != null ? Math.floor(coin.created_timestamp / 1000) : null;++ const [tradeHist, holderSet, authorities, dex, solUsd] = await Promise.all([+ fetchDayOfTrades(mint, now),+ liveHolderSet({ mint, network: 'mainnet' }).catch(() => null),+ readAuthorities(mint),+ readDexScreener(mint),+ solPriceUsd().catch(() => null),+ ]);++ // Early buyers are only knowable when the fetched history reaches the coin's+ // first trade; otherwise the field stays null rather than undercounting.+ let earlyBuyers = null;+ if (tradeHist?.complete && createdSec != null) {+ earlyBuyers = new Set(+ tradeHist.trades+ .filter((x) => x.buy && x.user && x.user !== creator && x.t - createdSec <= EARLY_BUY_SEC)+ .map((x) => x.user),+ );+ }++ const devTrades = tradeHist && creator ? tradeHist.trades.filter((x) => x.user === creator) : [];++ const realTokens = coin?.real_token_reserves != null ? BigInt(Math.round(Number(coin.real_token_reserves))) : null;+ const graduated = coin?.complete === true;+ const curveProgress = graduated+ ? 100+ : realTokens != null+ ? Math.max(0, Math.min(100, Number(((INITIAL_REAL_TOKEN_RESERVES - realTokens) * 1_000_000n) / INITIAL_REAL_TOKEN_RESERVES) / 10_000))+ : null;+ const curveSol = !graduated && coin?.real_sol_reserves != null ? Number(coin.real_sol_reserves) / 1e9 : null;+ // Curve liquidity the way trading terminals quote it: both sides of the+ // virtual reserves valued in USD (SOL side doubled, since the token side is+ // priced against it). A graduated coin reads its AMM liquidity from DEX Screener.+ const virtualSol = coin?.virtual_sol_reserves != null ? Number(coin.virtual_sol_reserves) / 1e9 : null;+ const curveLiquidityUsd = !graduated && virtualSol != null && solUsd ? virtualSol * 2 * solUsd : null;++ return {+ mint,+ as_of: new Date(now * 1000).toISOString(),+ windows: tradeHist+ ? windowStats(tradeHist.trades, { now, coveredFrom: tradeHist.complete ? null : tradeHist.oldest })+ : null,+ trades_sampled: tradeHist?.trades.length ?? null,+ holders: holderSet?.holders?.length+ ? holderStats(holderSet.holders, { supply, creator, curve, pool, earlyBuyers })+ : null,+ authorities,+ dev: creator+ ? {+ wallet: creator,+ bought: devTrades.filter((x) => x.buy).length,+ sold: devTrades.filter((x) => !x.buy).length,+ }+ : null,+ curve: coin+ ? {+ graduated,+ progress_pct: curveProgress,+ real_sol: curveSol,+ real_sol_usd: curveSol != null && solUsd ? curveSol * solUsd : null,+ }+ : null,+ market: {+ market_cap_usd: num(coin?.usd_market_cap ?? coin?.market_cap_usd),+ ath_market_cap_usd: num(coin?.ath_market_cap),+ liquidity_usd: dex.liquidity_usd ?? curveLiquidityUsd,+ dex_paid: dex.dex_paid,+ dexscreener_url: dex.pair_url,+ },+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);+ const mint = (url.searchParams.get('mint') || '').trim();+ if (!MINT_RE.test(mint)) return error(res, 400, 'invalid_mint', 'mint must be a base58 address');++ const body = await cacheWrapLastGood(`pump:token-stats:${mint}`, CACHE_TTL_S, () => buildStats(mint));+ res.setHeader('cache-control', 'public, max-age=15, s-maxage=20');+ return json(res, 200, body);+});diff --git a/pages/launch-detail.html b/pages/launch-detail.htmlindex d66463425..4fbae8af9 100644--- a/pages/launch-detail.html+++ b/pages/launch-detail.html@@ -7,7 +7,7 @@<title data-i18n="launch_detail.meta_title">Coin · three.ws</title><metaname="description"- content="A live, on-chain profile for a coin launched on three.ws — market cap, the Coin Intelligence verdict, holder distribution, the live trade tape, and the agent behind the mint."+ content="A live, on-chain profile for a coin launched on three.ws: market cap, volume, buys and sells, holders, the live trade tape, and the agent behind the mint."data-i18n-attr="content:launch_detail.meta_description"/><meta property="og:type" content="website" /><meta property="og:site_name" content="three.ws" />@@ -15,7 +15,7 @@<meta property="og:title" content="Coin · three.ws" data-i18n-attr="content:launch_detail.meta_og_title"/><metaproperty="og:description"- content="A live, on-chain profile for a coin launched on three.ws — market cap, intelligence verdict, holders, live trades, and the agent behind it."+ content="A live, on-chain profile for a coin launched on three.ws: market cap, volume, holders, live trades, and the agent behind it."data-i18n-attr="content:launch_detail.meta_og_description"/><meta property="og:image" content="https://three.ws/og-image.png" /><meta property="og:image:width" content="1200" />@@ -25,7 +25,7 @@<meta name="twitter:title" content="Coin · three.ws" data-i18n-attr="content:launch_detail.meta_twitter_title"/><metaname="twitter:description"- content="A live, on-chain profile for a coin launched on three.ws — market cap, intelligence verdict, holders, live trades, and the agent behind it."+ content="A live, on-chain profile for a coin launched on three.ws: market cap, volume, holders, live trades, and the agent behind it."data-i18n-attr="content:launch_detail.meta_twitter_description"/><meta name="twitter:image" content="https://three.ws/og-image.png" /><meta name="theme-color" content="#0a0a0a" />@@ -54,21 +54,20 @@<!-- Hero / identity. Hydrated by src/launch-detail.js. --><section id="ld-hero" class="ld-hero" aria-label="Coin overview"></section>- <!-- Market metrics — multi-timeframe price moves + on-chain safety. -->- <section id="ld-metrics" class="ld-section ld-metrics" aria-label="Market metrics"></section>+ <!-- Token stats: per-timeframe trading activity and on-chain facts. -->+ <section id="ld-metrics" class="ld-section ld-metrics" aria-label="Token stats"></section><!-- Primary intelligence + market column, secondary sidebar. --><div class="ld-body"><div class="ld-main">- <section id="ld-verdict" class="ld-section" aria-label="Coin Intelligence verdict"></section>- <section id="ld-smart" class="ld-section" aria-label="Smart money in this coin"></section>+ <section id="ld-verdict" class="ld-section" aria-label="Launch activity"></section>+ <section id="ld-smart" class="ld-section" aria-label="Notable wallets"></section><section id="ld-chart" class="ld-section" aria-label="Price history"></section><section id="ld-distribution" class="ld-section" aria-label="Holder distribution"></section><section id="ld-economics" class="ld-section" aria-label="Buyback & burn economics"></section><section id="ld-copilot" class="ld-section" aria-label="Launch Copilot — autonomous market-maker"></section></div><aside class="ld-side">- <section id="ld-oracle" class="ld-section" aria-label="Oracle conviction score"></section><section id="ld-agent" class="ld-section" aria-label="The agent behind this coin"></section><section id="ld-tape" class="ld-section" aria-label="Live trades"></section><section id="ld-community" class="ld-section" aria-label="Community"></section>diff --git a/pages/launches.html b/pages/launches.htmlindex 3c3a28295..ba1507ae4 100644--- a/pages/launches.html+++ b/pages/launches.html@@ -140,12 +140,6 @@Devnet</button></div>- <div class="lx-oracle-filter" role="group" aria-label="Oracle conviction filter">- <button type="button" class="lx-of-btn active" data-tier="" aria-pressed="true" data-i18n="launches.all">All</button>- <button type="button" class="lx-of-btn" data-tier="prime" aria-pressed="false" data-i18n="launches.prime">⭐ Prime</button>- <button type="button" class="lx-of-btn" data-tier="strong" aria-pressed="false" data-i18n="launches.strong">Strong</button>- <button type="button" class="lx-of-btn" data-tier="lean" aria-pressed="false" data-i18n="launches.lean">Lean</button>- </div><div id="lx-agent-filter" class="lx-agent-filter" hidden></div><span id="lx-count" class="lx-count" aria-live="polite"></span></section>diff --git a/src/coin-page.js b/src/coin-page.jsindex a9008f14e..7a2952eb5 100644--- a/src/coin-page.js+++ b/src/coin-page.js@@ -8,6 +8,13 @@// never mocked.import { watchEmbed, renderEmbedFallback, DEFAULT_EMBED_TIMEOUT_MS } from './shared/embed-guard.js';+import {+ CHART_CHAINS,+ CHART_EMBEDS,+ chartEmbedUrls,+ resolveGeckoPool,+ validChartAddress,+} from './shared/chart-embeds.js';import {formatUsd,formatPrice,@@ -116,31 +123,15 @@ function renderHead(coin) {// The chart panel is a multi-source switcher. CoinGecko powers the default,// zero-dependency native line chart (with the time-range selector); the other-// sources lazy-mount a full third-party terminal in an iframe only when picked:-// • TradingView — advanced candlestick widget, for coins with a ticker.-// • DexScreener — on-chain terminal keyed by the token address (all chains).-// • GeckoTerminal — on-chain terminal keyed by the token's most-liquid pool.+// sources lazy-mount a full third-party chart in an iframe only when picked:+// • TradingView advanced candlestick widget, for coins with a ticker.+// • DexScreener, Birdeye, GMGN, GeckoTerminal: each provider's on-chain chart+// for the token's contract, built by src/shared/chart-embeds.js so this page+// and /launches/<mint> embed identically.// Each source is offered only when it can actually render for the coin, so the// switcher never lands on a dead chart. The picked source persists across coins.const CHART_SOURCE_KEY = 'tws_coin_chart_source';-// CoinGecko asset-platform id → the chain slug DexScreener and the network id-// GeckoTerminal use for the same chain. Solana leads (home chain); the rest are-// the majors both terminals index. A platform without a mapping is not offered-// an on-chain chart.-const CHAIN_MAP = {- solana: { ds: 'solana', gt: 'solana', evm: false },- ethereum: { ds: 'ethereum', gt: 'eth', evm: true },- base: { ds: 'base', gt: 'base', evm: true },- 'binance-smart-chain': { ds: 'bsc', gt: 'bsc', evm: true },- 'polygon-pos': { ds: 'polygon', gt: 'polygon_pos', evm: true },- 'arbitrum-one': { ds: 'arbitrum', gt: 'arbitrum', evm: true },- 'optimistic-ethereum': { ds: 'optimism', gt: 'optimism', evm: true },- avalanche: { ds: 'avalanche', gt: 'avax', evm: true },-};--const EVM_RE = /^0x[0-9a-fA-F]{40}$/;-// TradingView resolves an unprefixed BASE+QUOTE pair (e.g. BTCUSD) to its// top-liquidity listing, so no exchange mapping table is needed.function tvSymbol(coin) {@@ -148,18 +139,15 @@ function tvSymbol(coin) {return sym && /^[A-Z0-9]{1,15}$/.test(sym) ? `${sym}USD` : null;}-// The coin's on-chain identity for the DEX terminals: a contract address plus-// the per-provider chain slugs. Solana is preferred when present (home chain);-// otherwise the first platform whose address is well-formed for a mapped chain.+// The coin's on-chain identity for the DEX charts: a chain every provider module+// knows plus a contract address well-formed for it. Solana is preferred when+// present (home chain); otherwise the first mapped platform.function onchainRef(coin) {const entries = Object.entries(coin.platforms || {});const ordered = entries.sort(([a], [b]) => (a === 'solana' ? -1 : b === 'solana' ? 1 : 0));for (const [platform, address] of ordered) {- const m = CHAIN_MAP[platform];- if (!m || typeof address !== 'string') continue;- const addr = address.trim();- const valid = m.evm ? EVM_RE.test(addr) : MINT_RE.test(addr);- if (valid) return { platform, address: addr, ds: m.ds, gt: m.gt };+ const addr = typeof address === 'string' ? address.trim() : '';+ if (validChartAddress(platform, addr)) return { platform, address: addr };}return null;}@@ -169,8 +157,16 @@ function onchainRef(coin) {const CHART_SOURCES = [{ id: 'coingecko', label: 'CoinGecko', kind: 'native', available: () => true },{ id: 'tradingview', label: 'TradingView', kind: 'tradingview', available: (c) => tvSymbol(c) != null },- { id: 'dexscreener', label: 'DexScreener', kind: 'dexscreener', available: (c) => onchainRef(c) != null },- { id: 'geckoterminal', label: 'GeckoTerminal', kind: 'geckoterminal', available: (c) => onchainRef(c) != null },+ ...CHART_EMBEDS.map((provider) => ({+ id: provider.id,+ label: provider.label,+ kind: 'embed',+ provider,+ available: (c) => {+ const ref = onchainRef(c);+ return !!(ref && CHART_CHAINS[ref.platform][provider.slug]);+ },+ })),];function availableSources(coin) {@@ -193,7 +189,7 @@ const chartState = {source: storedChartSource(),// GeckoTerminal pool resolution is async, resolved once per coin.gtPool: null,- gtState: 'idle', // idle | loading | ready | error+ gtState: 'idle', // idle | loading | ready | unindexed | error};// The source actually rendered for this coin: the stored preference when it's@@ -292,48 +288,21 @@ function mountTradingView(host, symbol, fallback) {host.replaceChildren(container);}-function mountDexScreener(host, ref, fallback) {- const t = chartTheme();- const p = new URLSearchParams({- embed: '1',- loadChartSettings: '0',- theme: t,- chartTheme: t,- chartType: 'usd',- interval: '15',- info: '0',- });- host.replaceChildren(- iframeEl(`https://dexscreener.com/${ref.ds}/${encodeURIComponent(ref.address)}?${p}`, 'DexScreener chart', fallback),- );-}--function mountGeckoTerminal(host, ref, pool, fallback) {- const p = new URLSearchParams({- embed: '1',- info: '0',- swaps: '0',- grayscale: '0',- light_chart: chartTheme() === 'light' ? '1' : '0',- });- host.replaceChildren(- iframeEl(`https://www.geckoterminal.com/${ref.gt}/pools/${encodeURIComponent(pool)}?${p}`, 'GeckoTerminal chart', fallback),- );+function mountEmbed(host, url, title, fallback) {+ host.replaceChildren(iframeEl(url, title, fallback));}-// GeckoTerminal embeds are keyed by pool, not token, so resolve the most-liquid-// pool once via our cached proxy, then mount. State drives the loading/error UI.+// GeckoTerminal embeds are keyed by pool, not token, and 404 for a pool it has+// not indexed, so resolve and confirm the pool once per coin, then mount. State+// drives the loading, not-indexed and error UI.async function loadGtPool(coin, ref) {if (chartState.gtState === 'loading') return;chartState.gtState = 'loading';renderChart(coin);try {- const { pool } = await getJson(- `/api/coin/pool?address=${encodeURIComponent(ref.address)}&network=${encodeURIComponent(ref.gt)}`,- );- if (!pool) throw new Error('no pool');+ const { pool, indexed } = await resolveGeckoPool(ref.platform, ref.address);chartState.gtPool = pool;- chartState.gtState = 'ready';+ chartState.gtState = indexed ? 'ready' : 'unindexed';} catch {chartState.gtPool = null;chartState.gtState = 'error';@@ -501,24 +470,29 @@ function embedChartBody(coin, source) {}const ref = onchainRef(coin);if (!ref) return '<div class="cv-chart-state">Chart data unavailable</div>';- if (source.kind === 'dexscreener') {- const credit = `<a href="https://dexscreener.com/${esc(ref.ds)}/${esc(ref.address)}" target="_blank" rel="noopener nofollow noreferrer">Open in DexScreener ↗</a>`;- return `<div class="cv-adv-wrap" id="cv-adv" aria-label="DexScreener chart for ${esc(coin.name)}"></div><p class="cv-tv-credit">${credit}</p>`;+ const { provider } = source;+ const label = esc(provider.label);+ const wrap = `<div class="cv-adv-wrap" id="cv-adv" aria-label="${label} chart for ${esc(coin.name)}"></div>`;+ if (provider.needs !== 'pool') {+ const urls = chartEmbedUrls(provider.id, { chain: ref.platform, token: ref.address, theme: chartTheme() });+ return `${wrap}<p class="cv-tv-credit"><a href="${esc(urls.page)}" target="_blank" rel="noopener nofollow noreferrer">Open in ${label} ↗</a></p>`;}- // geckoterminal- const openLink = `<a href="https://www.geckoterminal.com/${esc(ref.gt)}/tokens/${esc(ref.address)}" target="_blank" rel="noopener nofollow noreferrer">Open in GeckoTerminal ↗</a>`;if (chartState.gtState === 'error') {- return `<div class="cv-chart-state">On-chain chart unavailable · ${openLink}</div>`;+ return `<div class="cv-chart-state">${label} could not be reached for this coin's pool.</div>`;+ }+ if (chartState.gtState === 'unindexed') {+ return `<div class="cv-chart-state">${label} has not indexed a pool for this coin yet. DexScreener and Birdeye chart it now.</div>`;}if (chartState.gtState !== 'ready' || !chartState.gtPool) {- return '<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading GeckoTerminal…</div>';+ return `<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading ${label}…</div>`;}- return `<div class="cv-adv-wrap" id="cv-adv" aria-label="GeckoTerminal chart for ${esc(coin.name)}"></div><p class="cv-tv-credit">${openLink}</p>`;+ const urls = chartEmbedUrls(provider.id, { chain: ref.platform, token: ref.address, pool: chartState.gtPool, theme: chartTheme() });+ return `${wrap}<p class="cv-tv-credit"><a href="${esc(urls.page)}" target="_blank" rel="noopener nofollow noreferrer">Open in ${label} ↗</a></p>`;}// Mount the iframe for the active non-native source into #cv-adv. GeckoTerminal// first resolves its pool (kicking off the async fetch on the idle→loading-// transition); the other terminals mount synchronously.+// transition); the other charts mount synchronously.function mountActiveEmbed(coin, source) {ensureThemeRemount(coin);// Re-rendering the whole chart panel rebuilds the host node and remounts the@@ -536,28 +510,27 @@ function mountActiveEmbed(coin, source) {}const ref = onchainRef(coin);if (!ref) return;- if (source.kind === 'dexscreener') {- mountDexScreener($('cv-adv'), ref, {- name: 'The DexScreener chart',- href: `https://dexscreener.com/${ref.ds}/${ref.address}`,- label: 'Open in DexScreener',- onRetry,- });- return;- }- // geckoterminal- if (chartState.gtState === 'idle') {- loadGtPool(coin, ref);- return;- }- if (chartState.gtState === 'ready' && chartState.gtPool) {- mountGeckoTerminal($('cv-adv'), ref, chartState.gtPool, {- name: 'The GeckoTerminal chart',- href: `https://www.geckoterminal.com/${ref.gt}/tokens/${ref.address}`,- label: 'Open in GeckoTerminal',- onRetry,- });+ const { provider } = source;+ if (provider.needs === 'pool') {+ if (chartState.gtState === 'idle') {+ loadGtPool(coin, ref);+ return;+ }+ if (chartState.gtState !== 'ready' || !chartState.gtPool) return;}+ const urls = chartEmbedUrls(provider.id, {+ chain: ref.platform,+ token: ref.address,+ pool: chartState.gtPool,+ theme: chartTheme(),+ });+ if (!urls) return;+ mountEmbed($('cv-adv'), urls.embed, `${provider.label} chart`, {+ name: `The ${provider.label} chart`,+ href: urls.page,+ label: `Open in ${provider.label}`,+ onRetry,+ });}function wireChartPointer() {diff --git a/src/launch-detail.css b/src/launch-detail.cssindex a5c116266..d5c45160f 100644--- a/src/launch-detail.css+++ b/src/launch-detail.css@@ -274,8 +274,6 @@ body {}.ld-outcome b { font-weight: var(--weight-bold); }.ld-outcome-good { color: var(--success); border: 1px solid var(--success); background: color-mix(in srgb, var(--success) 12%, transparent); }-.ld-outcome-bad { color: var(--danger); border: 1px solid var(--danger); background: color-mix(in srgb, var(--danger) 12%, transparent); }-.ld-outcome-muted { color: var(--ink-dim); border: 1px solid var(--stroke); }.ld-hero-stats {display: grid;@@ -307,85 +305,15 @@ body {.lb-neg { color: var(--danger); }.lb-muted { color: var(--ink-dim); }-/* ── Verdict ──────────────────────────────────────────────────────────────── */--.ld-verdict { display: flex; flex-direction: column; gap: var(--space-md); }-.ld-verdict-head { display: flex; align-items: center; gap: var(--space-md); }-.ld-quality {- flex: 0 0 auto;- width: 84px;- height: 84px;- border-radius: var(--radius-md);- display: grid;- place-items: center;- border: 1px solid currentColor;- background: color-mix(in srgb, currentColor 8%, transparent);-}-.ld-quality-good { color: var(--success); }-.ld-quality-warn { color: var(--warn); }-.ld-quality-danger { color: var(--danger); }-.ld-quality-muted { color: var(--ink-dim); }-.ld-quality-num { font-family: var(--font-display); font-size: var(--text-2xl); font-weight: var(--weight-bold); line-height: 1; }-.ld-quality-max { font-size: var(--text-2xs); color: var(--ink-dim); }-.ld-verdict-copy { min-width: 0; }-.ld-verdict-label { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim); }-.ld-narrative { margin: var(--space-2xs) 0 0; font-size: var(--text-sm); color: var(--ink); line-height: 1.5; }--.ld-flags { display: flex; flex-wrap: wrap; gap: var(--space-xs); }-.ld-flag {- font-size: var(--text-2xs);- font-weight: var(--weight-medium);- border-radius: var(--radius-pill);- padding: 3px var(--space-sm);- border: 1px solid currentColor;- background: color-mix(in srgb, currentColor 10%, transparent);- cursor: help;-}-.ld-flag-good { color: var(--success); }-.ld-flag-warn { color: var(--warn); }-.ld-flag-danger { color: var(--danger); }--.ld-gauges {- display: grid;- grid-template-columns: repeat(2, 1fr);- gap: var(--space-sm) var(--space-md);-}-@media (max-width: 560px) { .ld-gauges { grid-template-columns: 1fr; } }-.ld-gauge-head { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 4px; }-.ld-gauge-label { font-size: var(--text-xs); color: var(--ink-dim); }-.ld-gauge-val { font-family: var(--font-mono); font-size: var(--text-xs); font-weight: var(--weight-semibold); }-.ld-gauge-track { height: 6px; border-radius: var(--radius-pill); background: var(--surface-3); overflow: hidden; }-.ld-gauge-fill { height: 100%; border-radius: var(--radius-pill); transition: width var(--duration-slow) var(--ease-out); }-.ld-fill-good { background: var(--success); }-.ld-fill-warn { background: var(--warn); }-.ld-fill-danger { background: var(--danger); }.ld-fill-muted { background: var(--stroke-strong); }-.ld-aggregates {- display: flex;- flex-wrap: wrap;- gap: var(--space-xs);- padding-top: var(--space-sm);- border-top: 1px solid var(--stroke);-}-.ld-kv {- display: inline-flex;- gap: var(--space-2xs);- align-items: baseline;- font-size: var(--text-xs);- color: var(--ink-dim);- background: var(--surface-2);- border: 1px solid var(--stroke);- border-radius: var(--radius-sm);- padding: 3px var(--space-xs);-}-.ld-kv b { font-family: var(--font-mono); color: var(--ink-bright); font-weight: var(--weight-semibold); }-/* ── Chart ────────────────────────────────────────────────────────────────── */.ld-chart { display: flex; flex-direction: column; gap: var(--space-sm); }.ld-chart-controls { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm); flex-wrap: wrap; }-.ld-chart-views { display: flex; gap: 4px; }+.ld-chart-views { display: flex; gap: 4px; flex-wrap: wrap; }+.ld-int-btn:focus-visible { outline: 2px solid var(--accent, #6ce0c8); outline-offset: 2px; }+.ld-int-btn:active { transform: translateY(1px); }.ld-chart-bar { display: flex; gap: 4px; }.ld-chart-open {font-family: var(--font-mono);@@ -435,6 +363,55 @@ body {.ld-dex-wrap .ld-skel-chart { position: absolute; inset: 0; height: 100%; border-radius: 0; }.ld-dex-ready .ld-dex-frame { opacity: 1; }.ld-dex-ready .ld-skel-chart { display: none; }+.ld-dex-wrap > .ld-embed-fallback {+ min-height: 460px;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: var(--space-2xs);+ padding: var(--space-md);+ color: var(--ink-dim);+}+.ld-embed-fallback p { margin: 0; max-width: 46ch; }+.ld-embed-fallback a { color: var(--accent, #6ce0c8); }+.ld-dex-fallback-actions { display: flex; justify-content: center; align-items: center; gap: var(--space-sm); flex-wrap: wrap; margin-top: var(--space-xs); }+.ld-chart-open-slot:empty { display: none; }++/* TradingView view: the shared Mission Control candle chart (src/mission-control/chart.js),+ themed with this page's tokens. */+.ld-tv {+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ background: var(--surface-2);+ padding: var(--space-sm);+}+.ld-tv .mc-chart { display: flex; flex-direction: column; gap: 8px; }+.ld-tv .mc-chart-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 20px; flex-wrap: wrap; }+.ld-tv .mc-chart-legend { display: flex; align-items: baseline; gap: 8px; min-width: 0; flex-wrap: wrap; }+.ld-tv .mc-section-h { margin: 0; font-family: var(--font-mono); font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.07em; color: var(--ink-dim); }+.ld-tv .mc-chart-px { font-family: var(--font-mono); font-size: var(--text-md, 0.875rem); font-weight: 700; color: var(--ink-bright); font-variant-numeric: tabular-nums; }+.ld-tv .mc-chart-chg { font-family: var(--font-mono); font-size: var(--text-2xs); font-weight: 700; font-variant-numeric: tabular-nums; }+.ld-tv .mc-chart-chg.pos { color: var(--success); }+.ld-tv .mc-chart-chg.neg { color: var(--danger); }+.ld-tv .mc-chart-ohlc { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-faint, var(--ink-dim)); font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.ld-tv .mc-chart-ohlc b { color: var(--ink-dim); font-weight: 600; }+.ld-tv .mc-chart-right { display: flex; align-items: center; gap: 10px; flex: none; }+.ld-tv .mc-chart-live { display: inline-flex; align-items: center; gap: 5px; font-family: var(--font-mono); font-size: var(--text-2xs); font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-dim); transition: color var(--duration-fast); }+.ld-tv .mc-chart-live-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--ink-dim); transition: background var(--duration-fast); }+.ld-tv .mc-chart-live[data-state="on"] { color: var(--success); }+.ld-tv .mc-chart-live[data-state="on"] .mc-chart-live-dot { background: var(--success); box-shadow: 0 0 6px var(--success); }+.ld-tv .mc-chart-ivs { display: inline-flex; gap: 2px; background: var(--surface-3, var(--surface-2)); border: 1px solid var(--stroke); border-radius: var(--radius-sm); padding: 2px; }+.ld-tv .mc-chart-iv { font-family: var(--font-mono); font-size: var(--text-2xs); font-weight: 600; color: var(--ink-dim); background: transparent; border: 0; border-radius: 4px; padding: 3px 8px; cursor: pointer; transition: color var(--duration-fast), background var(--duration-fast); }+.ld-tv .mc-chart-iv:hover { color: var(--ink-bright); }+.ld-tv .mc-chart-iv[aria-selected="true"] { color: var(--ink-bright); background: color-mix(in srgb, var(--accent, #6ce0c8) 22%, transparent); }+.ld-tv .mc-chart-iv:focus-visible { outline: 2px solid var(--accent, #6ce0c8); outline-offset: 1px; }+.ld-tv .mc-chart-body { position: relative; width: 100%; height: 420px; }+.ld-tv .mc-chart-canvas { position: absolute; inset: 0; }+.ld-tv .mc-chart-msg { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; padding: 0 12px; text-align: center; color: var(--ink-dim); font-size: var(--text-sm); pointer-events: none; }+@media (max-width: 640px) {+ .ld-tv .mc-chart-body { height: 320px; }+}.ld-int-btn {font-family: var(--font-mono);font-size: var(--text-2xs);@@ -481,19 +458,8 @@ body {}.ld-metric-label { display: block; font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-dim); }.ld-metric-val { font-family: var(--font-mono); font-size: var(--text-md); font-weight: var(--weight-semibold); color: var(--ink-bright); }-.ld-conc-track { height: 10px; border-radius: var(--radius-pill); background: var(--surface-3); overflow: hidden; }-.ld-conc-top { height: 100%; background: var(--warn); border-radius: var(--radius-pill); transition: width var(--duration-slow) var(--ease-out); }-.ld-conc-top.ld-good { background: var(--success); }-.ld-conc-top.ld-danger { background: var(--danger); }-.ld-conc-legend { display: flex; justify-content: space-between; font-size: var(--text-2xs); color: var(--ink-dim); margin-top: 4px; }+.ld-cohorts { display: flex; flex-wrap: wrap; gap: var(--space-xs); }-.ld-cohort {- display: inline-flex; gap: var(--space-2xs); align-items: baseline;- font-size: var(--text-xs); color: var(--ink-dim);- border: 1px solid var(--stroke); border-radius: var(--radius-pill);- padding: 3px var(--space-sm); background: var(--surface-2);-}-.ld-cohort b { font-family: var(--font-mono); color: var(--ink-bright); }/* ── Economics ────────────────────────────────────────────────────────────── */@@ -602,9 +568,7 @@ body {.ld-agent-stage-world:focus-visible { outline: 2px solid var(--ink-bright); outline-offset: 2px; }.ld-trader { display: flex; gap: var(--space-md); align-items: center; }-.ld-trader-score { width: 76px; height: 76px; border-radius: var(--radius-md); display: grid; place-items: center; border: 1px solid currentColor; background: color-mix(in srgb, currentColor 8%, transparent); flex: 0 0 auto; }-.ld-trader-num { font-family: var(--font-display); font-size: var(--text-xl); font-weight: var(--weight-bold); line-height: 1; }-.ld-trader-max { font-size: 9px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-dim); }+.ld-trader-stats { flex: 1 1 auto; display: flex; flex-direction: column; gap: 3px; }.ld-trader-row { display: flex; justify-content: space-between; font-size: var(--text-xs); }.ld-tl { color: var(--ink-dim); }@@ -682,20 +646,14 @@ body {.ld-empty-title { font-weight: var(--weight-semibold); color: var(--ink-bright); margin: 0 0 var(--space-2xs); }.ld-empty p { margin: 0 0 var(--space-sm); font-size: var(--text-sm); color: var(--ink-dim); }-/* ── Oracle Conviction (sidebar) ─────────────────────────────────────────── */-.ld-oracle-body { display: flex; flex-direction: column; gap: var(--space-sm); }-.ld-oracle-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm); }-.ld-oracle-dial { display: flex; align-items: baseline; gap: 2px; }-.ld-oracle-score { font-family: var(--font-display); font-size: var(--text-2xl); font-weight: var(--weight-bold); line-height: 1; color: var(--ink-bright); }-.ld-oracle-score-max { font-size: var(--text-2xs); color: var(--ink-dim); }-.ld-oracle-tier { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .1em; padding: 3px 9px; border-radius: var(--radius-pill); border: 1px solid; }+/* ── Comment breakdown bars (community panel) ───────────────────────────── */+.ld-oracle-pillars { display: flex; flex-direction: column; gap: 6px; }.ld-oracle-pillar { display: grid; grid-template-columns: 68px 1fr 28px; align-items: center; gap: var(--space-xs); }.ld-oracle-pillar-label { font-size: 10.5px; text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim); }.ld-oracle-pillar-bar { height: 5px; border-radius: 99px; background: var(--surface-2); overflow: hidden; }.ld-oracle-pillar-fill { height: 100%; border-radius: 99px; transition: width var(--duration-slow) var(--ease-out); }.ld-oracle-pillar-val { font: 600 11px/1 var(--font-mono); text-align: right; color: var(--ink-dim); }-.ld-oracle-actions { margin-top: var(--space-2xs); }.ld-state { margin-top: var(--space-lg); }.ld-fatal { text-align: center; max-width: 460px; margin: var(--space-2xl) auto; }@@ -777,38 +735,75 @@ body {@keyframes ld-shimmer { from { background-position: 100% 0; } to { background-position: -100% 0; } }@media (prefers-reduced-motion: reduce) { .ld-skel { animation: none; } }-/* ── Market metrics — multi-timeframe moves + on-chain safety ──────────────── */+/* ── Token stats: timeframe tabs, fact grid, holder list ──────────────────── */-.ld-metrics-body {- display: grid;- grid-template-columns: 1fr 1fr;- gap: var(--space-lg);-}-@media (max-width: 720px) { .ld-metrics-body { grid-template-columns: 1fr; } }-.ld-metrics-block { min-width: 0; }-.ld-metrics-h {- margin: 0 0 var(--space-sm);- font-size: var(--text-2xs);- text-transform: uppercase;- letter-spacing: 0.12em;- color: var(--ink-dim);- font-weight: var(--weight-semibold);-}--/* Multi-timeframe price-move strip */-.ld-mtf { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-xs); }-.ld-mtf-cell {+.ld-ts { display: flex; flex-direction: column; gap: var(--space-md); }+.ld-ts-tabs { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-xs); margin-bottom: var(--space-sm); }+.ld-ts-tab {display: flex;flex-direction: column;align-items: center;gap: 2px;- padding: var(--space-sm) var(--space-xs);+ padding: var(--space-xs);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ background: var(--surface-2);+ color: var(--ink);+ font: inherit;+ cursor: pointer;+ transition: border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);+}+.ld-ts-tab:hover { border-color: var(--stroke-strong); }+.ld-ts-tab:active { transform: translateY(1px); }+.ld-ts-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.ld-ts-tab.active { background: var(--surface-3); border-color: var(--stroke-strong); }+.ld-ts-tab-k { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-dim); }+.ld-ts-tab-v { font-family: var(--font-mono); font-size: var(--text-sm); font-weight: var(--weight-semibold); font-variant-numeric: tabular-nums; }+.ld-ts-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--space-xs); }+.ld-ts-facts { grid-template-columns: repeat(4, 1fr); }+@media (max-width: 720px) { .ld-ts-grid, .ld-ts-facts { grid-template-columns: repeat(2, 1fr); } }+.ld-ts-cell {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ padding: var(--space-xs) var(--space-sm);border: 1px solid var(--stroke);border-radius: var(--radius-md);background: var(--surface-2);}-.ld-mtf-label { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-dim); }-.ld-mtf-val { font-family: var(--font-mono); font-size: var(--text-md); font-weight: var(--weight-semibold); font-variant-numeric: tabular-nums; }+.ld-ts-cell[title] { cursor: help; }+.ld-ts-k { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-dim); }+.ld-ts-v { font-family: var(--font-mono); font-size: var(--text-sm); font-weight: var(--weight-semibold); color: var(--ink-bright); font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.ld-ts-v.lb-pos { color: var(--success); }+.ld-ts-v.lb-neg { color: var(--danger); }+.ld-ts-v.lb-muted { color: var(--ink-dim); }+.ld-ts-split { height: 4px; margin-top: var(--space-sm); border-radius: var(--radius-pill); background: color-mix(in srgb, var(--danger) 55%, transparent); overflow: hidden; }+.ld-ts-split-buy { height: 100%; background: var(--success); transition: width var(--duration-slow) var(--ease-out); }+.ld-ts-note { margin: var(--space-xs) 0 0; font-size: var(--text-2xs); color: var(--ink-dim); }++.ld-holders { display: flex; flex-direction: column; gap: 2px; }+.ld-holder {+ display: grid;+ grid-template-columns: 22px auto auto 1fr 64px;+ align-items: center;+ gap: var(--space-sm);+ padding: 6px var(--space-sm);+ border-radius: var(--radius-sm);+ color: var(--ink);+ text-decoration: none;+ font-size: var(--text-xs);+ transition: background var(--duration-fast) var(--ease-standard);+}+.ld-holder:hover { background: var(--surface-2); }+.ld-holder:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }+.ld-holder-rank { font-family: var(--font-mono); color: var(--ink-dim); text-align: right; }+.ld-holder-addr { font-family: var(--font-mono); color: var(--ink-bright); }+.ld-holder-tag { font-size: 10px; text-transform: uppercase; letter-spacing: 0.06em; padding: 1px 6px; border-radius: var(--radius-pill); border: 1px solid var(--stroke-strong); color: var(--ink-dim); }+.ld-holder-bar { height: 4px; border-radius: var(--radius-pill); background: var(--surface-3); overflow: hidden; grid-column: 4; }+.ld-holder-bar > span { display: block; height: 100%; background: var(--stroke-strong); }+.ld-holder-pct { font-family: var(--font-mono); text-align: right; color: var(--ink-bright); grid-column: 5; }+.ld-mtf-empty {display: flex;align-items: center;@@ -819,32 +814,3 @@ body {color: var(--ink-dim);}-/* On-chain safety / trust strip */-.ld-trust-head { display: flex; align-items: center; gap: var(--space-sm); margin-bottom: var(--space-sm); }-.ld-verdict-pill {- font-size: var(--text-2xs);- font-weight: var(--weight-semibold);- text-transform: uppercase;- letter-spacing: 0.08em;- padding: 3px var(--space-sm);- border-radius: var(--radius-pill);- border: 1px solid;-}-.ld-pill-good { color: var(--success); border-color: var(--success); background: color-mix(in srgb, var(--success) 12%, transparent); }-.ld-pill-warn { color: var(--warn); border-color: var(--warn); background: color-mix(in srgb, var(--warn) 12%, transparent); }-.ld-pill-danger { color: var(--danger); border-color: var(--danger); background: color-mix(in srgb, var(--danger) 12%, transparent); }-.ld-pill-muted { color: var(--ink-dim); border-color: var(--stroke); }-.ld-trust-score { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-dim); }-.ld-trust-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--space-xs); }-.ld-trust {- display: flex;- align-items: center;- justify-content: space-between;- gap: var(--space-sm);- padding: var(--space-xs) var(--space-sm);- border: 1px solid var(--stroke);- border-radius: var(--radius-md);- background: var(--surface-2);-}-.ld-trust-k { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-dim); }-.ld-trust-v { font-family: var(--font-mono); font-size: var(--text-sm); font-weight: var(--weight-semibold); white-space: nowrap; }diff --git a/src/launch-detail.js b/src/launch-detail.jsindex 3179bcef8..e47afcfbe 100644--- a/src/launch-detail.js+++ b/src/launch-detail.js@@ -7,20 +7,22 @@//// · WHAT is it — live name / symbol / logo / price / market cap /// graduation, streamed from /api/pump/coin-// · IS IT SAFE — the Coin Intelligence verdict (quality / bundle /-// organic / snipe / concentration / fresh wallets /-// risk flags), from /api/pump/launch-detail-// · WHAT HAPPENED — the labeled outcome (graduated / rugged / ATH ×)+// · THE NUMBERS : per-timeframe volume, buys, sells, net buy, holders,+// dev share, authorities, curve progress, liquidity,+// from /api/pump/token-stats; launch-window counts from+// /api/pump/launch-detail// · WHERE IS IT GOING — the live price chart (/api/pump/price-history) and// the live trade tape (/api/pump/trades-stream, SSE)-// · WHO HOLDS IT — holder count + concentration (/api/coin/:mint/cohorts)-// · WHO MADE IT — the agent behind the mint and its verifiable track-// record (TraderScore), deep-linked to /trader & /agents+// · WHO HOLDS IT : holder count + top holders (/api/pump/token-stats)+// · WHO MADE IT : the agent behind the mint and its public track+// record, deep-linked to /trader & /agents// · WHY HOLD — buyback-and-burn economics for agent-payment coins// · WHAT CAN I DO — buy, view in 3D, enter the coin's world, watch, share//-// Honesty contract: a signal the engine did not measure renders as "not-// measured", never as 0. A coin we never observed still renders — the page+// Neutrality contract: the page never scores, grades, or labels a coin. It shows+// facts and leaves the judgment to the reader, because a score on a user's+// launch reads as investment advice or as FUD. A value we could not read+// renders as "-", never as 0. A coin we never observed still renders, and the page// degrades to whatever is real for that mint and tells the user what's missing.// ════════════════════════════════════════════════════════════════════════════@@ -40,6 +42,9 @@ import { proxiedImageURL } from './ipfs.js';import { agentAvatarGlb, hasCustomAvatar, seeInWorldHref } from './shared/agent-3d.js';import { resolveDevR2Url } from './shared/dev-r2-proxy.js';import { terminalLinks } from './shared/trading-terminals.js';+import { CHART_EMBEDS, chartEmbedUrls, resolveGeckoPool } from './shared/chart-embeds.js';+import { watchEmbed, embedFallbackNode, DEFAULT_EMBED_TIMEOUT_MS } from './shared/embed-guard.js';+import { mountPriceChart } from './mission-control/chart.js';import { flashValue, rippleOnce, liveDot, setLiveDot } from './ui-juice.js';const GRADUATION_CAP_USD = 69_000; // pump.fun bonding-curve graduation threshold@@ -53,19 +58,23 @@ const state = {coin: null,tape: null, // EventSource handlechartInterval: '15m',- chartView: 'native', // 'native' (Birdeye area chart) | 'dexscreener' (interactive embed); hydrated from localStorage in boot()- dexFrameTimer: 0, // watchdog for a stalled DexScreener embed+ chartView: 'native', // a CHART_VIEWS id; hydrated from localStorage in boot()+ chartSeq: 0, // bumps on every chart render so a stale async load never paints+ chartTeardown: null, // cancels the active view's watchdog, stream or chart+ gecko: null, // { pool, indexed } once resolved for this mintpriceTimer: 0,+ statsPromise: null, // shared /api/pump/token-stats read (stats + holders panels)+ statsWindow: '1h', // selected timeframe tab in the stats panel};-// The chart-source choice is a viewing preference, not coin-specific — persist it-// so a trader who prefers the full DexScreener terminal keeps it across coins.+// The chart-source choice is a viewing preference, not coin-specific: persist it+// so a trader who prefers one chart keeps it across coins.const CHART_VIEW_KEY = 'ld_chart_view';function readChartView() {try {const v = localStorage.getItem(CHART_VIEW_KEY);- return v === 'dexscreener' || v === 'native' ? v : 'native';+ return CHART_VIEWS.some((view) => view.id === v) ? v : 'native';} catch {return 'native';}@@ -254,11 +263,6 @@ function fmtPrice(n) {return `$${n.toExponential(2)}`;}-function pctText(v) {- // signal helpers express 0..1 fractions; render as whole percents- return v == null ? null : `${Math.round(v * 100)}%`;-}-// ── mint resolution ──────────────────────────────────────────────────────────const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -335,21 +339,12 @@ function graduationRing(pct, size = 76) {}function outcomeBadge(outcome) {- if (!outcome || !outcome.outcome) return null;- const map = {- graduated: { label: 'Graduated', tone: 'good', tip: 'This coin completed its bonding curve and moved to an AMM pool.' },- rugged: { label: 'Rugged', tone: 'bad', tip: 'The Intelligence Engine labeled this coin as rugged.' },- survived: { label: 'Survived', tone: 'good', tip: 'Still trading after the observation window.' },- died: { label: 'Faded', tone: 'muted', tip: 'Activity collapsed shortly after launch.' },- unknown: null,- };- const meta = map[outcome.outcome];- if (!meta) return null;- const parts = [el('span', { text: meta.label })];- if (Number.isFinite(outcome.ath_multiple) && outcome.ath_multiple > 1) {- parts.push(el('b', { text: `${outcome.ath_multiple.toFixed(1)}× ATH` }));- }- return el('span', { class: `ld-outcome ld-outcome-${meta.tone}`, title: meta.tip }, parts);+ // Only graduation is a plain on-chain fact. Engine labels such as "rugged" or+ // "faded" are judgments about someone's coin, so they never render here.+ if (!outcome?.graduated) return null;+ return el('span', { class: 'ld-outcome ld-outcome-good', title: 'This coin completed its bonding curve and moved to an AMM pool.' }, [+ el('span', { text: 'Graduated' }),+ ]);}function socialLinks(socials, intel) {@@ -476,410 +471,211 @@ function renderHero() {}// ════════════════════════════════════════════════════════════════════════════-// MARKET METRICS — multi-timeframe price moves + live on-chain safety read+// TOKEN STATS: the neutral fact sheet a trading terminal leads with// ════════════════════════════════════════════════════════════════════════════//-// Two live reads, each real and independently degradable:-// · price moves — one 5m-candle pull (/api/pump/price-history), windowed in the-// client into 5m / 1h / 6h / 24h percentage moves. A window is shown only-// when the history actually spans (most of) it, so a young coin renders "—"-// for 24h rather than a misleading figure derived from two hours of data.-// · trust strip — the same pre-trade firewall verdict the autonomous sniper-// enforces (/api/pump/safety): a live SPL mint/freeze authority audit + a-// tradable-venue read, scored 0..100. Answers the on-chain trust questions a-// GMGN-style terminal leads with — can the dev mint more, freeze your tokens,-// is there a real venue — at a glance, every value traceable to chain state.--const TF_WINDOWS = [- { key: '5m', label: '5m', sec: 300 },- { key: '1h', label: '1h', sec: 3600 },- { key: '6h', label: '6h', sec: 21600 },- { key: '24h', label: '24h', sec: 86400 },-];--// Window a single ascending 5m-candle series into per-timeframe % moves. Returns-// null when there isn't enough data to compute even the shortest window.-function priceDeltas(pts) {- const sorted = (pts || [])- .filter((p) => Number.isFinite(p.c) && Number.isFinite(p.t) && p.c > 0)- .sort((a, b) => a.t - b.t);- if (sorted.length < 2) return null;- const last = sorted[sorted.length - 1];- const span = last.t - sorted[0].t;- const deltas = TF_WINDOWS.map((w) => {- // Require ≥60% of the window in history before quoting it — never fabricate- // a long-horizon move from a short series.- if (span < w.sec * 0.6) return { ...w, pct: null };- const target = last.t - w.sec;- let ref = sorted[0];- for (const p of sorted) { if (p.t >= target) { ref = p; break; } }- return { ...w, pct: ref.c ? ((last.c - ref.c) / ref.c) * 100 : null };- });- return { last: last.c, deltas };+// Facts, never a verdict. Nothing on this page scores, grades, or labels a coin:+// a score on someone's launch reads as investment advice when it is high and as+// FUD when it is low. Instead every panel shows the raw numbers a trader looks+// up on GMGN or DEX Screener (volume, buys vs sells, holders, dev share, mint+// and freeze authority, curve progress, liquidity) and leaves the judgment to+// the reader. One aggregate read (/api/pump/token-stats) feeds this panel and+// the holders panel, so the two can never disagree.++const TF_KEYS = ['5m', '1h', '6h', '24h'];++function loadStats() {+ if (!state.statsPromise) {+ state.statsPromise = fetchJson(`/api/pump/token-stats?mint=${encodeURIComponent(state.mint)}`, { timeout: 20000 });+ // A failed read must not poison later retries.+ state.statsPromise.catch(() => { state.statsPromise = null; });+ }+ return state.statsPromise;}-function renderTimeframeStrip(host) {- host.replaceChildren(el('div', { class: 'ld-skel ld-skel-strip' }));- const to = Math.floor(Date.now() / 1000);- const from = to - 30 * 3600;- fetchJson(`/api/pump/price-history?mint=${encodeURIComponent(state.mint)}&interval=5m&from=${from}&to=${to}`)- .then((body) => {- const res = priceDeltas(body.data);- if (!res || res.deltas.every((d) => d.pct == null)) {- host.replaceChildren(el('p', { class: 'ld-mtf-empty', text: 'Not enough trade history yet for price moves.' }));- return;- }- host.replaceChildren(- el('div', { class: 'ld-mtf' }, res.deltas.map((d) =>- el('div', { class: 'ld-mtf-cell' }, [- el('span', { class: 'ld-mtf-label', text: d.label }),- el('span', {- class: `ld-mtf-val ${d.pct == null ? 'ld-muted' : pnlClass(d.pct)}`,- text: d.pct == null ? '—' : fmtPct(d.pct, { sign: true }),- }),- ]),- )),- );- })- .catch(() => {- host.replaceChildren(- el('div', { class: 'ld-mtf-empty' }, [- el('span', { text: 'Price moves unavailable right now.' }),- el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Retry', onclick: () => renderTimeframeStrip(host) }),- ]),- );- });-}+const usd = (n) => (n == null ? '-' : fmtUsd(n, { sign: false }));+const share = (v) => (v == null ? '-' : fmtPct(v * 100, { dp: v < 0.001 && v > 0 ? 3 : v < 0.1 ? 2 : 1 }));-const TRUST_TONE = { pass: 'good', warn: 'warn', fail: 'danger', skip: 'muted' };-const VERDICT_META = {- allow: { label: 'Tradable', tone: 'good' },- warn: { label: 'Caution', tone: 'warn' },- block: { label: 'High risk', tone: 'danger' },-};-const VENUE_LABEL = {- live_amm_pool: 'AMM pool',- live_bonding_curve: 'Bonding curve',- no_tradable_venue: 'None',- curve_reserves_empty: 'Drained',- pool_reserves_empty: 'Drained',-};+function statCell(label, value, { cls = '', title = null } = {}) {+ return el('div', { class: 'ld-ts-cell', title }, [+ el('span', { class: 'ld-ts-k', text: label }),+ el('span', { class: `ld-ts-v ${cls}`, text: value }),+ ]);+}-function trustChip(label, value, tone, title) {- return el('div', { class: 'ld-trust', title: title || null }, [- el('span', { class: 'ld-trust-k', text: label }),- el('span', { class: `ld-trust-v ld-${tone}`, text: value }),+function windowPanel(windows, key) {+ const w = windows?.[key];+ if (!w) return el('p', { class: 'ld-mtf-empty', text: 'No trade history for this window.' });+ const buyShare = w.buys + w.sells > 0 ? (w.buys / (w.buys + w.sells)) * 100 : null;+ return el('div', { class: 'ld-ts-window' }, [+ el('div', { class: 'ld-ts-grid' }, [+ statCell('Volume', usd(w.volume_usd)),+ statCell('Buys', `${compact(w.buys)} / ${usd(w.buy_usd)}`, { cls: 'lb-pos' }),+ statCell('Sells', `${compact(w.sells)} / ${usd(w.sell_usd)}`, { cls: 'lb-neg' }),+ statCell('Net buy', fmtUsd(w.net_buy_usd), { cls: pnlClass(w.net_buy_usd) }),+ statCell('Traders', compact(w.traders)),+ statCell('Price', w.price_change_pct == null ? '-' : fmtPct(w.price_change_pct, { sign: true, dp: 2 }), { cls: pnlClass(w.price_change_pct) }),+ ]),+ buyShare == null+ ? null+ : el('div', { class: 'ld-ts-split', role: 'img', 'aria-label': `${Math.round(buyShare)}% of trades were buys` }, [+ el('div', { class: 'ld-ts-split-buy', style: `width:${buyShare}%` }),+ ]),+ w.partial+ ? el('p', { class: 'ld-ts-note', text: 'This coin trades heavily, so this window covers the most recent 1,500 trades.' })+ : null,]);}-function renderTrustStrip(host) {- host.replaceChildren(el('div', { class: 'ld-skel ld-skel-strip' }));- fetchJson(`/api/pump/safety?mint=${encodeURIComponent(state.mint)}&network=${state.network}`)- .then((s) => {- const checks = Array.isArray(s.checks) ? s.checks : [];- const byName = (n) => checks.find((c) => c.name === n);- const auth = byName('mint_authority');- const venue = byName('venue');- const sell = byName('round_trip');-- const chips = [];- // A null on-chain authority means it was renounced — the dev can no longer- // inflate supply (mint) or freeze your account (the cleanest honeypot).- if (auth) {- const unread = auth.reason === 'authority_read_failed' || auth.reason === 'mint_not_found';- const mintActive = auth.detail?.mint_authority != null;- const freezeActive = auth.detail?.freeze_authority != null;- chips.push(trustChip('Mint authority', unread ? 'Unknown' : mintActive ? 'Active' : 'Revoked',- unread ? 'muted' : mintActive ? 'danger' : 'good',- mintActive ? 'The creator can still mint new supply and dilute holders.' : 'Mint authority renounced — supply is fixed.'));- chips.push(trustChip('Freeze authority', unread ? 'Unknown' : freezeActive ? 'Active' : 'Revoked',- unread ? 'muted' : freezeActive ? 'danger' : 'good',- freezeActive ? 'The creator can freeze your token account — you may be unable to sell.' : 'Freeze authority renounced — your tokens cannot be frozen.'));- }- if (venue) {- chips.push(trustChip('Liquidity', VENUE_LABEL[venue.reason] || (venue.status === 'pass' ? 'Live' : '—'),- TRUST_TONE[venue.status] || 'muted', 'Where this coin can actually be traded.'));- }- if (sell) {- const label = sell.status === 'pass' ? 'Sellable' : sell.status === 'fail' ? 'Honeypot' : 'Untested';- chips.push(trustChip('Sell test', label, TRUST_TONE[sell.status] || 'muted',- sell.status === 'skip' ? 'A live buy→sell round-trip is simulated at trade time.' : 'Simulated buy→sell round-trip on-chain.'));- }+function renderWindowTabs(host, windows) {+ const panel = el('div', { class: 'ld-ts-panel', role: 'tabpanel' });+ const tabs = TF_KEYS.map((key) => {+ const w = windows?.[key];+ const btn = el('button', {+ class: 'ld-ts-tab',+ type: 'button',+ role: 'tab',+ 'aria-selected': 'false',+ onclick: () => select(key),+ }, [+ el('span', { class: 'ld-ts-tab-k', text: key }),+ el('span', {+ class: `ld-ts-tab-v ${w?.price_change_pct == null ? 'lb-muted' : pnlClass(w.price_change_pct)}`,+ text: w?.price_change_pct == null ? '-' : fmtPct(w.price_change_pct, { sign: true }),+ }),+ ]);+ btn.dataset.key = key;+ return btn;+ });+ const select = (key) => {+ state.statsWindow = key;+ for (const t of tabs) {+ const on = t.dataset.key === key;+ t.classList.toggle('active', on);+ t.setAttribute('aria-selected', String(on));+ }+ panel.replaceChildren(windowPanel(windows, key));+ };+ host.replaceChildren(el('div', { class: 'ld-ts-tabs', role: 'tablist', 'aria-label': 'Timeframe' }, tabs), panel);+ select(state.statsWindow || '1h');+}- if (!chips.length) {- host.replaceChildren(el('p', { class: 'ld-mtf-empty', text: 'Safety checks are unavailable for this coin.' }));- return;- }+function authorityText(addr) {+ return addr ? 'Enabled' : 'Disabled';+}- const v = VERDICT_META[s.verdict] || { label: 'Unscored', tone: 'muted' };- const head = el('div', { class: 'ld-trust-head' }, [- el('span', { class: `ld-verdict-pill ld-pill-${v.tone}`, text: v.label }),- Number.isFinite(Number(s.score)) ? el('span', { class: 'ld-trust-score', text: `${Math.round(Number(s.score))}/100 safety` }) : null,- ]);- host.replaceChildren(head, el('div', { class: 'ld-trust-grid' }, chips));- })- .catch(() => {- host.replaceChildren(- el('div', { class: 'ld-mtf-empty' }, [- el('span', { text: 'Safety check unavailable right now.' }),- el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Retry', onclick: () => renderTrustStrip(host) }),- ]),- );- });+function factsGrid(stats) {+ const h = stats.holders;+ const a = stats.authorities;+ const c = stats.curve;+ const m = stats.market || {};+ const dev = stats.dev;+ return el('div', { class: 'ld-ts-grid ld-ts-facts' }, [+ statCell('Holders', h ? compact(h.count) : '-'),+ statCell('Top 10', h ? share(h.top10_pct) : '-', { title: 'Supply held by the ten largest wallets, excluding the bonding curve and AMM pool.' }),+ statCell('Dev holds', h ? share(h.dev_pct) : '-', { title: 'Supply held by the creator wallet.' }),+ statCell('Early buyers', h?.early_buyers_pct != null ? `${share(h.early_buyers_pct)} · ${compact(h.early_buyers)}` : '-', {+ title: 'Supply still held by wallets that bought within 5 seconds of launch, and how many there were.',+ }),+ statCell('Mint authority', a ? authorityText(a.mint_authority) : '-', { title: 'Whether any account can still mint new supply.' }),+ statCell('Freeze authority', a ? authorityText(a.freeze_authority) : '-', { title: 'Whether any account can still freeze token accounts.' }),+ statCell('Bonding curve', c ? (c.graduated ? 'Graduated' : fmtPct(c.progress_pct, { dp: 2 })) : '-', { title: 'Share of the bonding curve bought out. At 100% the coin moves to an AMM pool.' }),+ statCell('Liquidity', usd(m.liquidity_usd)),+ statCell('ATH market cap', usd(m.ath_market_cap_usd)),+ statCell('Dev trades', dev ? `${dev.bought} buys · ${dev.sold} sells` : '-', { title: 'Creator wallet trades in the fetched history.' }),+ statCell('DEX Screener', m.dex_paid == null ? '-' : m.dex_paid ? 'Profile paid' : 'Not paid', { title: 'Whether an enhanced token profile was paid for on DEX Screener.' }),+ statCell('Creator', dev ? shortAddr(dev.wallet, 4, 4) : '-', { title: dev?.wallet || null }),+ ]);}function renderMetrics() {const target = $('ld-metrics');if (!target) return;if (state.network !== 'mainnet') {- section(target, 'Market metrics', el('div', { class: 'ld-empty ld-empty-sm' }, [- el('p', { text: 'Live price moves and on-chain safety checks are mainnet-only.' }),+ section(target, 'Token stats', el('div', { class: 'ld-empty ld-empty-sm' }, [+ el('p', { text: 'Live trading stats are mainnet-only.' }),]));return;}- const tfHost = el('div', { class: 'ld-mtf-host' });- const trustHost = el('div', { class: 'ld-trust-host' });- const body = el('div', { class: 'ld-metrics-body' }, [- el('div', { class: 'ld-metrics-block' }, [el('h3', { class: 'ld-metrics-h', text: 'Price moves' }), tfHost]),- el('div', { class: 'ld-metrics-block' }, [el('h3', { class: 'ld-metrics-h', text: 'On-chain safety' }), trustHost]),- ]);- section(target, 'Market metrics', body, { tag: 'live' });- renderTimeframeStrip(tfHost);- renderTrustStrip(trustHost);+ const body = el('div', { class: 'ld-ts' }, [el('div', { class: 'ld-skel ld-skel-strip' }), el('div', { class: 'ld-skel', style: 'height:120px' })]);+ section(target, 'Token stats', body, { tag: 'live · on-chain' });++ loadStats()+ .then((stats) => {+ const tfHost = el('div', { class: 'ld-ts-windows' });+ body.replaceChildren(tfHost, factsGrid(stats));+ if (stats.windows) renderWindowTabs(tfHost, stats.windows);+ else tfHost.replaceChildren(el('p', { class: 'ld-mtf-empty', text: 'Trade history is unavailable right now.' }));+ })+ .catch(() => {+ body.replaceChildren(+ el('div', { class: 'ld-mtf-empty' }, [+ el('span', { text: 'Token stats are unavailable right now.' }),+ el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Retry', onclick: () => renderMetrics() }),+ ]),+ );+ });}// ════════════════════════════════════════════════════════════════════════════-// INTELLIGENCE VERDICT+// LAUNCH ACTIVITY: what happened in the first ~90 seconds, as raw counts// ════════════════════════════════════════════════════════════════════════════-const FLAG_META = {- bundle_launch: { label: 'Bundle launch', tone: 'danger', tip: 'Many wallets bought in the same block — likely coordinated.' },- dev_dumped: { label: 'Dev dumped', tone: 'danger', tip: 'The creator sold their position.' },- dev_dump: { label: 'Dev dumped', tone: 'danger', tip: 'The creator sold their position.' },- single_whale: { label: 'Single whale', tone: 'danger', tip: 'One wallet holds an outsized share of supply.' },- low_diversity: { label: 'Low diversity', tone: 'danger', tip: 'Few unique buyers — thin, concentrated participation.' },- fresh_wallet_swarm: { label: 'Fresh-wallet swarm', tone: 'danger', tip: 'A cluster of brand-new wallets bought together.' },- sell_pressure: { label: 'Sell pressure', tone: 'warn', tip: 'Sells are outpacing buys early.' },- sniped: { label: 'Sniped', tone: 'warn', tip: 'Snipers grabbed supply in the first moments.' },-};--function scoreTone(score) {- if (score == null) return 'muted';- if (score >= 70) return 'good';- if (score >= 45) return 'warn';- return 'danger';-}--function gauge(label, value01, { invert = false } = {}) {- // value01 in 0..1; invert means lower-is-better (concentration, snipe).- const measured = value01 != null;- const pct = measured ? Math.max(0, Math.min(100, value01 * 100)) : 0;- const good = invert ? 100 - pct : pct;- const tone = !measured ? 'muted' : good >= 66 ? 'good' : good >= 40 ? 'warn' : 'danger';- return el('div', { class: 'ld-gauge' }, [- el('div', { class: 'ld-gauge-head' }, [- el('span', { class: 'ld-gauge-label', text: label }),- el('span', { class: `ld-gauge-val ld-${tone}`, text: measured ? `${Math.round(pct)}%` : 'not measured' }),- ]),- el('div', { class: 'ld-gauge-track' }, [- el('div', { class: `ld-gauge-fill ld-fill-${tone}`, style: `width:${measured ? pct : 0}%` }),- ]),- ]);-}-function renderVerdict() {const target = $('ld-verdict');const intel = state.detail.intel;+ // Nothing observed means nothing to show; the stats panel above already covers+ // the live market, so an empty explainer here would only be noise.if (!intel) {- section(- target,- 'Coin Intelligence',- el('div', { class: 'ld-empty' }, [- el('p', { class: 'ld-empty-title', text: 'Not yet observed by the Intelligence Engine.' }),- el('p', {- text:- state.network === 'devnet'- ? 'The engine watches mainnet launches. Devnet coins carry no intelligence signals.'- : 'This coin launched before the engine started watching, or its first seconds were not captured. New mainnet launches are scored within ~90 seconds.',- }),- el('a', { class: 'ld-btn ld-btn-ghost', href: '/radar', text: 'Open the live radar →' }),- ]),- { tag: 'engine' },- );+ target.hidden = true;return;}- const q = intel.quality_score;- const tone = scoreTone(q);- const headline = el('div', { class: 'ld-verdict-head' }, [- el('div', { class: `ld-quality ld-quality-${tone}` }, [- el('span', { class: 'ld-quality-num', text: q != null ? String(Math.round(q)) : '—' }),- el('span', { class: 'ld-quality-max', text: '/100' }),- ]),- el('div', { class: 'ld-verdict-copy' }, [- el('span', { class: 'ld-verdict-label', text: 'Quality score' }),- el('p', {- class: 'ld-narrative',- text:- intel.narrative ||- (q >= 70- ? 'Signals read organic: diverse buyers, healthy timing, no dominant whale.'- : q >= 45- ? 'Mixed signals — some concentration or coordination worth a closer look.'- : 'High-risk signals: coordination, concentration, or early sell pressure.'),- }),- ]),- ]);+ const kv = (label, value, title) =>+ value == null ? null : statCell(label, value, { title });+ const pct01 = (v) => (v == null ? null : fmtPct(v * 100, { dp: 0 }));- const flags = (intel.risk_flags || []).length- ? el(- 'div',- { class: 'ld-flags' },- intel.risk_flags.map((f) => {- const m = FLAG_META[f] || { label: f.replace(/_/g, ' '), tone: 'warn', tip: '' };- return el('span', { class: `ld-flag ld-flag-${m.tone}`, title: m.tip, text: m.label });- }),- )- : el('div', { class: 'ld-flags' }, [- el('span', { class: 'ld-flag ld-flag-good', text: 'No risk flags raised' }),- ]);-- const gauges = el('div', { class: 'ld-gauges' }, [- gauge('Organic', intel.organic_score),- gauge('Bundle coordination', intel.bundle_score, { invert: true }),- gauge('Sniped early', intel.snipe_ratio, { invert: true }),- gauge('Top-10 concentration', intel.concentration_top10, { invert: true }),- gauge('Fresh wallets', intel.fresh_wallet_ratio, { invert: true }),- gauge('Funder clustering', intel.bubblemap_connectivity, { invert: true }),- ]);-- // First-seconds aggregates — the raw observed activity behind the scores.- const kv = (label, value) =>- value == null- ? null- : el('div', { class: 'ld-kv' }, [el('span', { text: label }), el('b', { text: value })]);- const aggregates = el('div', { class: 'ld-aggregates' }, [+ const cells = [kv('Buys', intel.buy_count != null ? compact(intel.buy_count) : null),kv('Sells', intel.sell_count != null ? compact(intel.sell_count) : null),kv('Unique buyers', intel.unique_buyers != null ? compact(intel.unique_buyers) : null),+ kv('Unique sellers', intel.unique_sellers != null ? compact(intel.unique_sellers) : null),kv('Buy volume', intel.buy_volume_sol != null ? fmtSol(intel.buy_volume_sol, { sign: false }) : null),+ kv('Sell volume', intel.sell_volume_sol != null ? fmtSol(intel.sell_volume_sol, { sign: false }) : null),kv('Dev buy', intel.dev_buy_sol != null ? fmtSol(intel.dev_buy_sol, { sign: false }) : null),kv('Largest buy', intel.largest_buy_sol != null ? fmtSol(intel.largest_buy_sol, { sign: false }) : null),- kv('Observed for', intel.observation_seconds != null ? `${intel.observation_seconds}s` : null),- ]);+ kv('Dev sold', intel.dev_sold == null ? null : intel.dev_sold ? 'Yes' : 'No'),+ kv('Opening-second volume', pct01(intel.snipe_ratio), 'Share of buy volume that landed in the first seconds after launch.'),+ kv('Top 10 at launch', pct01(intel.concentration_top10), 'Share of bought supply held by the ten largest early buyers.'),+ kv('New wallets', pct01(intel.fresh_wallet_ratio), 'Share of early buyers whose wallets had no prior history.'),+ ].filter(Boolean);- const body = el('div', { class: 'ld-verdict' }, [headline, flags, gauges, aggregates]);- section(target, 'Coin Intelligence', body, { tag: 'first ~90s, on-chain' });+ if (!cells.length) {+ target.hidden = true;+ return;+ }+ const span = intel.observation_seconds != null ? `first ${intel.observation_seconds}s` : 'at launch';+ section(target, 'Launch activity', el('div', { class: 'ld-ts-grid ld-ts-facts' }, cells), { tag: span });}// ════════════════════════════════════════════════════════════════════════════-// ORACLE CONVICTION — fused conviction score from the Oracle system-// ════════════════════════════════════════════════════════════════════════════--const ORACLE_TIER_META = {- prime: { label: 'PRIME', color: '#c084fc', bg: 'rgba(192,132,252,.14)' },- strong: { label: 'STRONG', color: '#34d399', bg: 'rgba(52,211,153,.12)' },- lean: { label: 'LEAN', color: '#fbbf24', bg: 'rgba(251,191,36,.12)' },- watch: { label: 'WATCH', color: '#94a3b8', bg: 'rgba(148,163,184,.1)' },- avoid: { label: 'AVOID', color: '#f87171', bg: 'rgba(248,113,113,.12)' },-};-const ORACLE_PILLAR_COLORS = {- pedigree: '#5fe3ff', structure: '#34d399', narrative: '#a07bff', momentum: '#fbbf24',-};--async function renderOracleConviction() {- const target = $('ld-oracle');- if (!target || state.network !== 'mainnet') return;- target.replaceChildren(el('div', { class: 'ld-skel', style: 'height:140px' }));-- let data;- try {- const r = await fetch(`/api/oracle/coin?mint=${encodeURIComponent(state.mint)}`);- if (!r.ok) { target.replaceChildren(); return; }- data = await r.json();- } catch { target.replaceChildren(); return; }-- const cv = data.conviction;- if (!cv) { target.replaceChildren(); return; }-- const tier = cv.tier || 'watch';- const meta = ORACLE_TIER_META[tier] || ORACLE_TIER_META.watch;- const score = Math.round(Number(cv.score ?? 0));- const pillars = cv.pillars || {};-- const tierBadge = el('span', {- class: 'ld-oracle-tier',- style: `background:${meta.bg};color:${meta.color};border-color:${meta.color}40`,- text: meta.label,- });-- const scoreDial = el('div', { class: 'ld-oracle-dial' }, [- el('span', { class: 'ld-oracle-score', text: String(score) }),- el('span', { class: 'ld-oracle-score-max', text: '/100' }),- ]);-- const pillarRow = el('div', { class: 'ld-oracle-pillars' },- ['pedigree', 'structure', 'narrative', 'momentum'].map((key) => {- const val = Math.round(Number(pillars[key] ?? 0));- const bar = el('div', { class: 'ld-oracle-pillar-bar' }, [- el('div', {- class: 'ld-oracle-pillar-fill',- style: `width:${val}%;background:${ORACLE_PILLAR_COLORS[key]}`,- }),- ]);- return el('div', { class: 'ld-oracle-pillar' }, [- el('span', { class: 'ld-oracle-pillar-label', text: key }),- bar,- el('span', { class: 'ld-oracle-pillar-val', text: String(val) }),- ]);- }),- );-- const actions = el('div', { class: 'ld-oracle-actions' }, [- el('a', {- class: 'ld-btn ld-btn-ghost ld-btn-sm ld-btn-block',- href: `/oracle/coin/${encodeURIComponent(state.mint)}`,- target: '_blank',- rel: 'noopener',- text: 'Full conviction breakdown ↗',- }),- ]);-- const body = el('div', { class: 'ld-oracle-body' }, [- el('div', { class: 'ld-oracle-head' }, [scoreDial, tierBadge]),- pillarRow,- actions,- ]);- section(target, 'Oracle Conviction', body, { tag: 'fused · 4 reads' });-}-+// NOTABLE WALLETS: wallets with a public track record that bought this coin// ════════════════════════════════════════════════════════════════════════════-// SMART MONEY — who is in this coin, and what is their track record//-// The single most actionable question a trader has isn't "what is the chart" —-// it's "who else is in, and do they win." The Smart Money Radar answers it: it-// crosses every wallet's footprint in this coin against which coins those same-// wallets historically graduated, scoring the *pedigree of the money* buying in.-// Data: /api/pump/smart-money?mint= (found:false until the rollup scores the coin).-// ════════════════════════════════════════════════════════════════════════════+// Shows who bought and their public record, with no score for the coin itself.+// Hidden when no such wallet has touched the coin: an empty "nobody notable"+// panel on someone's launch reads as a knock, not information.const WALLET_LABEL = {- smart_money: { label: 'Smart money', tone: 'good', tip: 'A wallet with a proven record of buying coins that went on to graduate.' },- sniper: { label: 'Sniper', tone: 'warn', tip: 'Habitually grabs supply in the first moments of a launch.' },- dumper: { label: 'Dumper', tone: 'danger', tip: 'Tends to sell into early buyers — exits fast.' },- rugger: { label: 'Rugger', tone: 'danger', tip: 'Has been tied to coins that rugged.' },- fresh: { label: 'Fresh', tone: 'muted', tip: 'A brand-new wallet with no track record yet.' },- neutral: { label: 'Neutral', tone: 'muted', tip: 'Trades both ways with no decisive edge.' },- unproven: { label: 'Unproven', tone: 'muted', tip: 'Not enough history to judge.' },+ smart_money: { label: 'Graduated picks', tip: 'This wallet has a record of buying coins that went on to graduate.' },+ sniper: { label: 'Early buyer', tip: 'This wallet often buys in the first moments of a launch.' },+ fresh: { label: 'New wallet', tip: 'This wallet has little on-chain history.' },};function walletRow(w) {- const meta = WALLET_LABEL[w.label] || { label: (w.label || 'wallet').replace(/_/g, ' '), tone: 'muted', tip: '' };+ const meta = WALLET_LABEL[w.label] || null;const winPct = w.win_rate != null ? Math.round(w.win_rate * 100) : null;- const record =- w.wins != null && w.duds != null && w.wins + w.duds > 0 ? `${w.wins}–${w.duds}` : null;-return el('a',{@@ -887,17 +683,16 @@ function walletRow(w) {href: `https://solscan.io/account/${w.wallet}`,target: '_blank',rel: 'noopener noreferrer',- 'aria-label': `${meta.label} ${shortAddr(w.wallet)} — bought ${fmtSol(w.buy_sol, { sign: false })}`,+ 'aria-label': `Wallet ${shortAddr(w.wallet)}, bought ${fmtSol(w.buy_sol, { sign: false })}`,},[- el('span', { class: `ld-sm-dot ld-fill-${meta.tone}`, 'aria-hidden': 'true' }),+ el('span', { class: 'ld-sm-dot ld-fill-muted', 'aria-hidden': 'true' }),el('div', { class: 'ld-sm-who' }, [el('span', { class: 'ld-sm-addr', text: shortAddr(w.wallet, 4, 4) }),- el('span', { class: `ld-sm-label ld-${meta.tone}`, title: meta.tip, text: meta.label }),+ meta ? el('span', { class: 'ld-sm-label ld-muted', title: meta.tip, text: meta.label }) : null,]),el('div', { class: 'ld-sm-rec' }, [- winPct != null ? el('span', { class: 'ld-sm-win', text: `${winPct}% win` }) : null,- record ? el('span', { class: 'ld-sm-wd', text: record }) : null,+ winPct != null ? el('span', { class: 'ld-sm-win', text: `${winPct}% graduated` }) : null,]),el('span', { class: 'ld-sm-buy', text: fmtSol(w.buy_sol, { sign: false }) }),],@@ -906,74 +701,25 @@ function walletRow(w) {async function renderSmartMoney() {const target = $('ld-smart');- if (state.network !== 'mainnet') {- target.hidden = true;- return;- }-- // The rollup hasn't scored this coin yet (too new, or pre-dates the engine).- // Modern API answers 200 + found:false; a fetch failure (or a pre-convention- // deploy's 404) lands in the same honest "not scored yet" panel.- function renderNotScored() {- section(- target,- 'Smart money',- el('div', { class: 'ld-empty ld-empty-sm' }, [- el('p', { class: 'ld-empty-title', text: 'No smart-money read yet.' }),- el('p', {- text: 'The radar scores a coin once proven wallets touch it. New launches are picked up within minutes. Check back, or watch the live radar.',- }),- el('a', { class: 'ld-btn ld-btn-ghost', href: '/radar', text: 'Open the Smart Money radar →' }),- ]),- { tag: 'wallet pedigree' },- );- }+ target.hidden = true;+ if (state.network !== 'mainnet') return;let data = null;try {data = await fetchJson(`/api/pump/smart-money?mint=${encodeURIComponent(state.mint)}`);} catch {- renderNotScored();return;}- if (!data || data.found === false || !data.coin) {- renderNotScored();- return;- }-- const coin = data.coin || {};- const notable = (data.notable || [])+ const notable = (data?.notable || []).filter((w) => w && w.wallet).sort((a, b) => Number(b.buy_sol || 0) - Number(a.buy_sol || 0));- const score = Number(coin.smart_money_score);- const tone = scoreTone(Number.isFinite(score) ? score : null);- const provenSol = Number(coin.proven_buy_sol) || 0;- const smartCount =- Number(coin.smart_wallet_count) || notable.filter((w) => w.label === 'smart_money').length;-- // The hook line — concrete, FOMO-honest, never synthesized.- const lede =- smartCount > 0- ? `${smartCount} proven ${smartCount === 1 ? 'wallet has' : 'wallets have'} put ${fmtSol(provenSol, { sign: false })} into this coin.`- : provenSol > 0- ? `${fmtSol(provenSol, { sign: false })} of the money here traces to wallets with a track record.`- : 'No wallets with a proven track record have bought this coin yet.';-- const headline = el('div', { class: 'ld-sm-head' }, [- el('div', { class: `ld-quality ld-quality-${tone}` }, [- el('span', { class: 'ld-quality-num', text: Number.isFinite(score) ? String(Math.round(score)) : '—' }),- el('span', { class: 'ld-quality-max', text: 'pedigree' }),- ]),- el('div', { class: 'ld-verdict-copy' }, [- el('span', { class: 'ld-verdict-label', text: 'Smart-money score' }),- el('p', { class: 'ld-narrative', text: lede }),- ]),- ]);-- const children = [headline];+ if (!notable.length) return;- if (notable.length) {- children.push(+ target.hidden = false;+ section(+ target,+ 'Notable wallets',+ el('div', { class: 'ld-sm' }, [el('div', { class: 'ld-sm-list' }, [el('div', { class: 'ld-sm-list-head' }, [el('span', { text: 'Wallet' }),@@ -982,23 +728,10 @@ async function renderSmartMoney() {]),...notable.slice(0, 8).map(walletRow),]),- );- } else {- children.push(- el('p', {- class: 'ld-agent-note',- text: 'The radar is watching, but no notable wallets have surfaced in this coin yet.',- }),- );- }-- children.push(- el('a', { class: 'ld-actions-foot', href: '/radar', text: 'See everything the smart money is buying →' }),+ ]),+ { tag: 'public track records' },);-- section(target, 'Smart money', el('div', { class: 'ld-sm' }, children), { tag: 'wallet pedigree' });}-// ════════════════════════════════════════════════════════════════════════════// PRICE CHART// ════════════════════════════════════════════════════════════════════════════@@ -1093,66 +826,68 @@ function chartIntervalBar() {);}-// View switch — the fast native area chart vs. the full interactive DexScreener-// terminal (price + depth + trades). Both read the same on-chain mint; the embed-// is loaded only when chosen so the default view stays lightweight.+// Chart source switch. Every chart a viewer might trust, free and keyless:+// · three.ws the fast native area chart over /api/pump/price-history+// · TradingView TradingView's charting engine (lightweight-charts) drawing+// real candles from the same OHLCV, ticked live by the trade+// stream. Shared with Mission Control and /trades.+// · DexScreener, Birdeye, GMGN, GeckoTerminal: each provider's own chart,+// embedded. URL shapes live in src/shared/chart-embeds.js.+// Only the chosen view loads, so the default stays light.const CHART_VIEWS = [- ['Native', 'native'],- ['DexScreener', 'dexscreener'],+ { id: 'native', label: 'three.ws', kind: 'native' },+ { id: 'tradingview', label: 'TradingView', kind: 'tradingview' },+ ...CHART_EMBEDS.map((p) => ({ id: p.id, label: p.label, kind: 'embed', provider: p })),];+const OHLCV_SOURCE_LABEL = { birdeye: 'Birdeye OHLCV', gecko: 'GeckoTerminal OHLCV', pumpfun: 'pump.fun OHLCV' };++function setChartView(id) {+ if (state.chartView === id) return;+ state.chartView = id;+ writeChartView(id);+ renderChart();+}+function chartViewBar() {- return el(- 'div',- { class: 'ld-chart-views', role: 'tablist', 'aria-label': 'Chart source' },- CHART_VIEWS.map(([label, value]) =>- el('button', {- class: `ld-int-btn${state.chartView === value ? ' active' : ''}`,- type: 'button',- role: 'tab',- 'aria-selected': String(state.chartView === value),- text: label,- onclick: () => {- if (state.chartView === value) return;- state.chartView = value;- writeChartView(value);- renderChart();- },- }),- ),+ const buttons = CHART_VIEWS.map((view) =>+ el('button', {+ class: `ld-int-btn${state.chartView === view.id ? ' active' : ''}`,+ type: 'button',+ role: 'tab',+ 'data-view': view.id,+ 'aria-selected': String(state.chartView === view.id),+ tabindex: state.chartView === view.id ? '0' : '-1',+ text: view.label,+ onclick: () => setChartView(view.id),+ }),);+ // Roving tabindex: arrow keys move between sources, Home/End jump to the ends.+ const onkeydown = (e) => {+ const i = buttons.indexOf(document.activeElement);+ if (i < 0) return;+ const next = { ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: buttons.length - 1 }[e.key];+ if (next == null) return;+ e.preventDefault();+ const id = CHART_VIEWS[(next + buttons.length) % buttons.length].id;+ setChartView(id);+ $('ld-chart').querySelector(`[data-view="${id}"]`)?.focus();+ };+ return el('div', { class: 'ld-chart-views', role: 'tablist', 'aria-label': 'Chart source', onkeydown }, buttons);}-// DexScreener serves a TradingView-grade embeddable terminal keyed by the Solana-// mint — it resolves the most-liquid pair itself, so no pair lookup is needed.-function dexEmbedUrl() {- const theme = document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';- const params = new URLSearchParams({- embed: '1',- loadChartSettings: '0',- theme,- chartTheme: theme,- chartType: 'usd',- interval: '15',- info: '0',- });- return `https://dexscreener.com/solana/${encodeURIComponent(state.mint)}?${params}`;+function currentTheme() {+ return document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';}-function dexLink() {- return el('a', {- class: 'ld-chart-open',- href: `https://dexscreener.com/solana/${encodeURIComponent(state.mint)}`,- target: '_blank',- rel: 'noopener',- text: 'Open in DexScreener ↗',- });+function openLink(href, label) {+ return el('a', { class: 'ld-chart-open', href, target: '_blank', rel: 'noopener', text: `Open in ${label} ↗` });}-// DexScreener is a chart, not a place to fill an order. Every coin page also-// offers the trading terminals people actually execute on, straight to this-// mint. Sourced from src/shared/trading-terminals.js so the links (and the GMGN-// referral baked into its deep link) stay identical across the product.+// A chart is not a place to fill an order. Every coin page also offers the+// trading terminals people actually execute on, straight to this mint. Sourced+// from src/shared/trading-terminals.js so the links (and the GMGN referral baked+// into its deep link) stay identical across the product.function terminalLinksEl() {return el('div',@@ -1170,60 +905,135 @@ function terminalLinksEl() {);}-function renderDexChart(target) {- clearTimeout(state.dexFrameTimer);- const controls = el('div', { class: 'ld-chart-controls' }, [chartViewBar(), terminalLinksEl(), dexLink()]);- const wrap = el('div', { class: 'ld-dex-wrap' });- // The recoverable state: a sentence, a retry, and a way to see the chart- // anyway. Reached from two places, so it lives in one.- const showFallback = () => {- if (wrap.classList.contains('ld-dex-ready')) return;- clearTimeout(state.dexFrameTimer);+function embedFrame(wrap, { src, title, name, page, label }) {+ const fail = () => {+ cancel();wrap.replaceChildren(- el('div', { class: 'ld-empty ld-empty-sm' }, [- el('p', { text: "DexScreener's chart didn't load. It may be blocked or still indexing this coin." }),- el('div', { class: 'ld-dex-fallback-actions' }, [- el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Retry', onclick: () => renderChart() }),- dexLink(),- ]),- ]),+ embedFallbackNode({+ name,+ href: page,+ label: `Open in ${label}`,+ onRetry: () => renderChart(),+ className: 'ld-empty ld-empty-sm ld-embed-fallback',+ buttonClassName: 'ld-btn ld-btn-ghost',+ }),);};const iframe = el('iframe', {class: 'ld-dex-frame',- src: dexEmbedUrl(),- title: 'DexScreener live chart',+ src,+ title,loading: 'lazy',+ allow: 'clipboard-write; fullscreen',+ referrerpolicy: 'strict-origin-when-cross-origin',onload: () => {- clearTimeout(state.dexFrameTimer);+ cancel();wrap.classList.add('ld-dex-ready');},- // An outright refusal (blocked host, DNS failure, a sandbox that rejects- // the frame) is knowable immediately. Without this the skeleton kept- // shimmering for the full watchdog window on a failure already decided.- onerror: showFallback,+ // An outright refusal (blocked host, DNS failure) is knowable immediately.+ onerror: fail,});+ // The watchdog clock starts once the frame is on screen, so a chart below the+ // fold is never reported dead before it began loading.+ const cancel = watchEmbed(wrap, { timeoutMs: DEFAULT_EMBED_TIMEOUT_MS, onTimeout: fail });wrap.replaceChildren(el('div', { class: 'ld-skel ld-skel-chart' }), iframe);- section(target, 'Price', el('div', { class: 'ld-chart' }, [controls, wrap]), { tag: 'DexScreener · live' });+ return cancel;+}++async function renderEmbedChart(target, view, seq) {+ const { provider } = view;+ const wrap = el('div', { class: 'ld-dex-wrap' }, [el('div', { class: 'ld-skel ld-skel-chart' })]);+ const openSlot = el('span', { class: 'ld-chart-open-slot' });+ const controls = el('div', { class: 'ld-chart-controls' }, [chartViewBar(), terminalLinksEl(), openSlot]);+ section(target, 'Price', el('div', { class: 'ld-chart' }, [controls, wrap]), { tag: `${provider.label} · live` });++ let pool = null;+ if (provider.needs === 'pool') {+ try {+ state.gecko ||= await resolveGeckoPool('solana', state.mint, { signal: AbortSignal.timeout(10_000) });+ } catch {+ if (seq !== state.chartSeq) return;+ wrap.replaceChildren(+ el('div', { class: 'ld-empty ld-empty-sm ld-embed-fallback' }, [+ el('p', { text: `Could not reach ${provider.label} to find this coin's pool.` }),+ el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Try again', onclick: () => renderChart() }),+ ]),+ );+ return;+ }+ if (seq !== state.chartSeq) return;+ if (!state.gecko.indexed) {+ // GeckoTerminal lists a pump.fun coin once it has traded enough. Until+ // then its embed is a 404 page, so say so and point at charts that+ // already cover the coin.+ wrap.replaceChildren(+ el('div', { class: 'ld-empty ld-empty-sm ld-embed-fallback' }, [+ el('p', { class: 'ld-empty-title', text: `${provider.label} has not indexed this coin yet.` }),+ el('p', { text: 'It lists new pump.fun coins once they build trading history. Birdeye, GMGN and DexScreener chart it from the first trade.' }),+ el('div', { class: 'ld-dex-fallback-actions' }, [+ el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Show Birdeye', onclick: () => setChartView('birdeye') }),+ el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Check again', onclick: () => { state.gecko = null; renderChart(); } }),+ ]),+ ]),+ );+ return;+ }+ pool = state.gecko.pool;+ }- // Watchdog: if the embed never loads (blocked, offline, sandbox), don't leave a- // dead skeleton — surface a recoverable error with a retry and a direct link.- state.dexFrameTimer = setTimeout(showFallback, 9000);+ const urls = chartEmbedUrls(provider.id, { chain: 'solana', token: state.mint, pool, theme: currentTheme() });+ openSlot.replaceChildren(openLink(urls.page, provider.label));+ state.chartTeardown = embedFrame(wrap, {+ src: urls.embed,+ title: `${provider.label} live chart`,+ name: `The ${provider.label} chart`,+ page: urls.page,+ label: provider.label,+ });+}++function renderTradingViewChart(target) {+ const host = el('div', { class: 'ld-tv' });+ const controls = el('div', { class: 'ld-chart-controls' }, [chartViewBar(), terminalLinksEl()]);+ section(target, 'Price', el('div', { class: 'ld-chart' }, [controls, host]), { tag: 'TradingView · live candles' });+ const chart = mountPriceChart({ host, mint: state.mint });+ state.chartTeardown = () => chart.destroy();+}++// The iframe providers bake the theme in at load, so a live theme switch reloads+// whichever embed is showing. Registered once per page.+let chartThemeObserver = null;+function watchChartTheme() {+ if (chartThemeObserver) return;+ chartThemeObserver = new MutationObserver(() => {+ const view = CHART_VIEWS.find((v) => v.id === state.chartView);+ if (view?.kind === 'embed') renderChart();+ });+ chartThemeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });}async function renderChart() {const target = $('ld-chart');+ const seq = ++state.chartSeq;+ state.chartTeardown?.();+ state.chartTeardown = null;if (state.network !== 'mainnet') {section(target, 'Price', el('div', { class: 'ld-empty' }, [el('p', { text: 'No price history for devnet coins.' })]));return;}- if (state.chartView === 'dexscreener') {- renderDexChart(target);+ watchChartTheme();+ const view = CHART_VIEWS.find((v) => v.id === state.chartView) || CHART_VIEWS[0];+ if (view.kind === 'tradingview') {+ renderTradingViewChart(target);+ return;+ }+ if (view.kind === 'embed') {+ await renderEmbedChart(target, view, seq);return;}const controls = el('div', { class: 'ld-chart-controls' }, [chartViewBar(), chartIntervalBar()]);const canvas = el('div', { class: 'ld-chart-canvas' }, [el('div', { class: 'ld-skel ld-skel-chart' })]);- section(target, 'Price', el('div', { class: 'ld-chart' }, [controls, canvas]), { tag: 'Birdeye OHLCV' });+ section(target, 'Price', el('div', { class: 'ld-chart' }, [controls, canvas]), { tag: 'On-chain OHLCV' });const interval = state.chartInterval;const to = Math.floor(Date.now() / 1000);@@ -1232,9 +1042,19 @@ async function renderChart() {const body = await fetchJson(`/api/pump/price-history?mint=${encodeURIComponent(state.mint)}&interval=${interval}&from=${from}&to=${to}`,);+ if (seq !== state.chartSeq) return;+ const tag = target.querySelector('.ld-sec-tag');+ if (tag && OHLCV_SOURCE_LABEL[body.source]) tag.textContent = OHLCV_SOURCE_LABEL[body.source];const pts = (body.data || []).filter((p) => Number.isFinite(p.c));if (pts.length < 2) {- canvas.replaceChildren(el('div', { class: 'ld-empty ld-empty-sm' }, [el('p', { text: 'Not enough trade history at this interval yet.' })]));+ canvas.replaceChildren(+ el('div', { class: 'ld-empty ld-empty-sm' }, [+ el('p', { text: 'Not enough trade history at this interval for a line yet.' }),+ el('div', { class: 'ld-dex-fallback-actions' }, [+ el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Show live candles', onclick: () => setChartView('tradingview') }),+ ]),+ ]),+ );return;}const first = pts[0].c;@@ -1257,6 +1077,7 @@ async function renderChart() {}canvas.replaceChildren(el('div', { class: 'ld-chart-readout' }, readout), areaChart(pts));} catch (err) {+ if (seq !== state.chartSeq) return;// A coin with no liquidity pool has no chart to draw — that is an answer,// not a failure, so it gets its own copy and no Retry button.if (err?.status === 404 && err?.code === 'no_market') {@@ -1282,80 +1103,73 @@ async function renderChart() {async function renderDistribution() {const target = $('ld-distribution');- const intel = state.detail.intel;+ if (state.network !== 'mainnet') {+ target.hidden = true;+ return;+ }+ target.replaceChildren(el('div', { class: 'ld-skel', style: 'height:180px' }));- let overview = null;+ let stats = null;try {- overview = await fetchJson(`/api/coin/${encodeURIComponent(state.mint)}/cohorts`);+ stats = await loadStats();} catch {- /* not an indexed agent token — fall back to intel concentration below */+ /* rendered as the unavailable state below */}-- const rows = [];- let holderCount = overview?.holderCount ?? null;- let top1 = overview?.concentration?.top1Share ?? null;- let top10 = overview?.concentration?.top10Share ?? (intel?.concentration_top10 ?? null);- const label = overview?.concentration?.label || null;-- if (holderCount == null && top10 == null) {+ const h = stats?.holders;+ if (!h) {section(target,'Holders',el('div', { class: 'ld-empty ld-empty-sm' }, [- el('p', { text: 'Holder distribution is not indexed for this coin yet.' }),+ el('p', { text: stats ? 'Holder data is not indexed for this coin yet.' : 'Holder data is unavailable right now.' }),+ stats ? null : el('button', { class: 'ld-btn ld-btn-ghost', type: 'button', text: 'Retry', onclick: () => renderDistribution() }),]),);return;}- const metric = (k, v, tone = '') =>+ const metric = (k, v) =>el('div', { class: 'ld-metric' }, [el('span', { class: 'ld-metric-label', text: k }),- el('span', { class: `ld-metric-val ${tone}`, text: v }),+ el('span', { class: 'ld-metric-val', text: v }),]);-- const concTone = top10 == null ? '' : top10 > 0.5 ? 'ld-danger' : top10 > 0.3 ? 'ld-warn' : 'ld-good';const metrics = el('div', { class: 'ld-metrics' }, [- holderCount != null ? metric('Holders', compact(holderCount)) : null,- top1 != null ? metric('Top holder', pctText(top1)) : null,- top10 != null ? metric('Top 10', pctText(top10), concTone) : null,- label ? metric('Spread', label) : null,+ metric('Holders', compact(h.count)),+ metric('Top holder', share(h.top1_pct)),+ metric('Top 10', share(h.top10_pct)),+ metric('Dev', share(h.dev_pct)),+ h.pool_pct ? metric('AMM pool', share(h.pool_pct)) : metric('Bonding curve', share(h.curve_pct)),]);- // Concentration bar — top10 vs the rest.- let bar = null;- if (top10 != null) {- const t10 = Math.max(0, Math.min(100, top10 * 100));- bar = el('div', { class: 'ld-conc' }, [- el('div', { class: 'ld-conc-track', title: `Top 10 wallets hold ${Math.round(t10)}%` }, [- el('div', { class: `ld-conc-top ${concTone}`, style: `width:${t10}%` }),- ]),- el('div', { class: 'ld-conc-legend' }, [- el('span', { text: `Top 10 · ${Math.round(t10)}%` }),- el('span', { text: `Everyone else · ${Math.round(100 - t10)}%` }),+ const rows = (h.top || []).map((row, i) =>+ el('a', {+ class: 'ld-holder',+ href: `https://solscan.io/account/${row.wallet}`,+ target: '_blank',+ rel: 'noopener noreferrer',+ 'aria-label': `Holder ${i + 1}, ${shortAddr(row.wallet)}, ${share(row.pct)} of supply`,+ }, [+ el('span', { class: 'ld-holder-rank', text: String(i + 1) }),+ el('span', { class: 'ld-holder-addr', text: shortAddr(row.wallet, 4, 4) }),+ row.is_dev ? el('span', { class: 'ld-holder-tag', text: 'Dev' }) : null,+ el('span', { class: 'ld-holder-bar', 'aria-hidden': 'true' }, [+ el('span', { style: `width:${Math.min(100, (row.pct || 0) * 100)}%` }),]),- ]);- }-- const cohorts = (overview?.cohorts || []).filter((c) => c.count != null && c.count > 0);- const cohortChips = cohorts.length- ? el(- 'div',- { class: 'ld-cohorts' },- cohorts.map((c) =>- el('span', { class: 'ld-cohort', title: c.description || '' }, [- el('b', { text: compact(c.count) }),- el('span', { text: c.name }),- ]),- ),- )- : null;+ el('span', { class: 'ld-holder-pct', text: share(row.pct) }),+ ]),+ );- section(target, 'Holders', el('div', { class: 'ld-dist' }, [metrics, bar, cohortChips]), {- tag: overview?.source === 'live' ? 'live · Helius' : overview ? 'snapshot' : 'engine',- });+ section(+ target,+ 'Holders',+ el('div', { class: 'ld-dist' }, [+ metrics,+ rows.length ? el('div', { class: 'ld-holders' }, rows) : null,+ el('p', { class: 'ld-ts-note', text: 'Shares are of total supply. The bonding curve and AMM pool are liquidity, not holders, so they are left out of the ranking.' }),+ ]),+ { tag: 'live · Helius' },+ );}-// ════════════════════════════════════════════════════════════════════════════// BUYBACK / BURN ECONOMICS// ════════════════════════════════════════════════════════════════════════════@@ -1622,12 +1436,7 @@ function renderAgent() {}if (trader) {- const tone = scoreTone(trader.score);const scoreEl = el('div', { class: 'ld-trader' }, [- el('div', { class: `ld-trader-score ld-quality-${tone}` }, [- el('span', { class: 'ld-trader-num', text: trader.score != null ? String(Math.round(trader.score)) : '—' }),- el('span', { class: 'ld-trader-max', text: 'TraderScore' }),- ]),el('div', { class: 'ld-trader-stats' }, [trader.verified ? el('span', { class: 'ld-verified', html: verifiedBadge(true) }) : null,el('div', { class: 'ld-trader-row' }, [@@ -1845,8 +1654,6 @@ async function renderCommunity() {const d = await res.json();if (!d.ok || !d.overall || d.overall.count < 3) { sentWrap.replaceChildren(); return; }const o = d.overall;- const scoreColor = o.score >= 60 ? 'var(--ld-good)' : o.score <= 40 ? 'var(--ld-bad)' : 'var(--ld-muted)';- const sentLabel = o.score >= 60 ? 'bullish' : o.score <= 40 ? 'bearish' : 'mixed';const bars = [['Positive', Math.round(o.posPct), 'var(--ld-good)'],@@ -1870,8 +1677,7 @@ async function renderCommunity() {sentWrap.replaceChildren(el('div', { style: 'display:flex;align-items:center;gap:8px;margin-bottom:8px' }, [- el('span', { style: `font:600 12px var(--font-mono,monospace);color:${scoreColor}` }, [document.createTextNode(sentLabel)]),- el('span', { style: 'font:10px var(--font-mono,monospace);color:var(--ld-muted)' }, [document.createTextNode(`${o.count} comments`)]),+ el('span', { style: 'font:600 12px var(--font-mono,monospace);color:var(--ld-muted)' }, [document.createTextNode(`${o.count} recent comments`)]),]),el('div', { class: 'ld-oracle-pillars' }, bars),...examples,@@ -2091,7 +1897,7 @@ function renderSkeleton() {]),el('div', { class: 'ld-hero-stats' }, Array.from({ length: 4 }, () => el('div', { class: 'ld-skel', style: 'height:46px' }))),);- for (const id of ['ld-verdict', 'ld-chart', 'ld-agent', 'ld-oracle']) {+ for (const id of ['ld-metrics', 'ld-chart', 'ld-agent']) {$(id).replaceChildren(el('div', { class: 'ld-skel', style: 'height:120px' }));}}@@ -2174,7 +1980,7 @@ async function boot() {const regName = detail.registry?.name || detail.intel?.name || '';const regSym = detail.registry?.symbol || detail.intel?.symbol || '';const pageTitle = [regSym ? `$${regSym}` : '', regName, 'three.ws'].filter(Boolean).join(' · ');- const pageDesc = `${regSym ? `$${regSym} ` : ''}on three.ws — live price, intelligence score, smart money, and trade history.`;+ const pageDesc = `${regSym ? `$${regSym} ` : ''}on three.ws: live price, volume, holders, and trade history.`;const ogImg = `https://three.ws/api/pump/launch-og?mint=${state.mint}`;document.title = pageTitle;setMeta('og:title', pageTitle);@@ -2191,7 +1997,6 @@ async function boot() {renderHero();renderMetrics();renderVerdict();- renderOracleConviction();renderSmartMoney();renderChart();renderDistribution();diff --git a/src/launches.css b/src/launches.cssindex 3c337708f..cd936260e 100644--- a/src/launches.css+++ b/src/launches.css@@ -477,41 +477,6 @@ body {}/* Oracle conviction tier filter */-.lx-oracle-filter {- display: inline-flex;- padding: var(--space-3xs);- border: 1px solid var(--stroke);- border-radius: var(--radius-md);- background: var(--surface-1);- gap: 2px;-}--.lx-of-btn {- padding: var(--space-xs) var(--space-sm);- border: 0;- border-radius: var(--radius-sm);- background: transparent;- color: var(--ink-dim);- font-size: var(--text-sm);- font-weight: var(--weight-medium);- font-family: var(--font-body);- cursor: pointer;- transition:- background var(--duration-fast) var(--ease-standard),- color var(--duration-fast) var(--ease-standard);-}--.lx-of-btn:hover { color: var(--ink); }--.lx-of-btn:focus-visible {- outline: var(--focus-ring-width) solid var(--focus-ring-color);- outline-offset: var(--focus-ring-offset);-}--.lx-of-btn.active { background: var(--surface-3); color: var(--ink-bright); }-.lx-of-btn[data-tier="prime"].active { color: #c084fc; }-.lx-of-btn[data-tier="strong"].active { color: #34d399; }-.lx-of-btn[data-tier="lean"].active { color: var(--warn); }.lx-count {margin-left: auto;@@ -1001,29 +966,6 @@ body {}/* ── Oracle conviction badge on launch cards ─────────────────────────────── */-.lx-oracle-badge {- position: absolute;- bottom: var(--space-sm);- right: var(--space-sm);- z-index: 2;- pointer-events: none;-}-.lx-ob-link {- display: flex;- align-items: center;- gap: 4px;- background: rgba(0, 0, 0, 0.7);- border: 1px solid rgba(255, 255, 255, 0.12);- border-radius: 6px;- padding: 3px 7px;- text-decoration: none;- backdrop-filter: blur(4px);- pointer-events: all;- transition: background var(--duration-fast), border-color var(--duration-fast);-}-.lx-ob-link:hover { background: rgba(0, 0, 0, 0.85); border-color: rgba(255, 255, 255, 0.22); }-.lx-ob-score { font: 700 12px/1 var(--font-mono); font-variant-numeric: tabular-nums; }-.lx-ob-tier { font: 600 8.5px/1 var(--font-mono); text-transform: uppercase; letter-spacing: .06em; opacity: .85; }/* ── Responsive ───────────────────────────────────────────────────────────── */@@ -1056,45 +998,6 @@ body {/* ── Oracle conviction badge on feed cards ──────────────────────────────── */-.lx-oracle-badge {- position: absolute;- top: var(--space-sm, 10px);- right: var(--space-sm, 10px);- z-index: 3;- pointer-events: none;-}-.lx-ob-link {- pointer-events: all;- display: flex;- flex-direction: column;- align-items: center;- background: rgba(0,0,0,0.52);- border: 1px solid rgba(255,255,255,0.09);- border-radius: 7px;- padding: 5px 8px 4px;- text-decoration: none;- line-height: 1;- backdrop-filter: blur(5px);- transition: background var(--duration-fast), border-color var(--duration-fast), transform var(--duration-fast);-}-.lx-ob-link:hover { background: rgba(0,0,0,0.72); border-color: rgba(255,255,255,0.2); transform: scale(1.06); }-.lx-ob-score {- font-family: var(--font-mono, ui-monospace, monospace);- font-size: 15px;- font-weight: 800;- font-variant-numeric: tabular-nums;- letter-spacing: -0.01em;-}-.lx-ob-tier {- font-family: var(--font-mono, ui-monospace, monospace);- font-size: 8px;- font-weight: 700;- letter-spacing: 0.07em;- text-transform: uppercase;- opacity: 0.85;- margin-top: 2px;-}-/* Money Pulse strip — compact live wallet-activity ticker linking to /pulse.Self-hides (component sets display:none) when the platform has no real events. */.lx-pulse-strip {diff --git a/src/launches.js b/src/launches.jsindex 6a0ba5db5..2b273ef43 100644--- a/src/launches.js+++ b/src/launches.js@@ -27,13 +27,11 @@ import { countUp, updateValue, enterStagger, rippleOnce, liveDot, setLiveDot } fconst log = createLogger('launches');const PAGE_SIZE = 24;-const ORACLE_TIER_COLOR = { prime: '#c084fc', strong: '#34d399', lean: '#fbbf24', watch: '#94a3b8', avoid: '#f87171' };const LIVE_REFRESH_MS = 60_000;const state = {network: 'mainnet',agentId: null,- oracleTier: '', // '' = all, 'prime' | 'strong' | 'lean'offset: 0,hasMore: false,loading: false,@@ -427,47 +425,6 @@ function resetAggregates() {if (statGradEl) { statGradEl.textContent = '—'; delete statGradEl.dataset.juiceVal; }}-// ── Oracle conviction batch enrichment ───────────────────────────────────────-// After each page of cards renders, batch-fetch Oracle conviction for all-// visible mints (≤20 per request) and paint a tier badge on each card.-// Non-blocking: a fetch failure leaves cards untouched.--function paintOracleBadge(card, mint, data) {- const badge = card.querySelector('.lx-oracle-badge');- if (!badge || !data || data.score == null) return;- const color = ORACLE_TIER_COLOR[data.tier] || '#94a3b8';- badge.innerHTML = `<a class="lx-ob-link" href="/oracle/coin/${encodeURIComponent(mint)}" title="Oracle conviction: ${data.score} — ${data.tier || 'unscored'}" tabindex="-1" aria-hidden="true">- <span class="lx-ob-score" style="color:${color}">${data.score}</span>- <span class="lx-ob-tier" style="color:${color}">${data.tier || ''}</span>- </a>`;-}--async function enrichCardsWithOracle(cards) {- const mints = cards- .map((c) => c.dataset.mint)- .filter(Boolean);- if (!mints.length) return;- const chunks = [];- for (let i = 0; i < mints.length; i += 20) chunks.push(mints.slice(i, i + 20));- let results = {};- try {- const resps = await Promise.all(- chunks.map((ch) =>- fetch(`/api/oracle/batch?mints=${ch.map(encodeURIComponent).join(',')}&network=mainnet`)- .then((r) => r.ok ? r.json() : null)- .catch(() => null),- ),- );- for (const r of resps) {- if (r?.results) Object.assign(results, r.results);- }- } catch { return; }-- for (const card of cards) {- paintOracleBadge(card, card.dataset.mint, results[card.dataset.mint]);- }-}-// ── card rendering ───────────────────────────────────────────────────────────function agentChip(agent) {@@ -641,7 +598,6 @@ function launchCard(launch, index, { featured = false } = {}) {walletChip,el('div', { class: 'lx-card-actions' }, actions),el('span', { class: 'lx-mint', text: launch.mint, title: launch.mint }),- el('div', { class: 'lx-oracle-badge', 'aria-hidden': 'true' }),]);reveal(card, index);@@ -651,10 +607,7 @@ function launchCard(launch, index, { featured = false } = {}) {variant: 'card',placeholder: identicon,onData: recordMarket,- // This feed already batch-fetches conviction for every visible mint- // (enrichCardsWithOracle → /api/oracle/batch), so the widget's own- // per-coin /api/oracle/coin round trip is redundant — one request per- // card, each a 404 for any mint the Oracle hasn't observed yet.+ // The launch feed stays neutral: no conviction tier on anyone's coin.oracle: false,}),);@@ -720,28 +673,23 @@ function clearSkeletons() {}function renderEmpty() {- const filtered = !!state.agentId || !!state.oracleTier;- const tierLabel = state.oracleTier- ? { prime: 'prime conviction', strong: 'strong conviction', lean: 'lean conviction' }[state.oracleTier] || state.oracleTier- : null;+ const filtered = !!state.agentId;feedEl.appendChild(el('div', { class: 'lx-state' }, [el('h2', { text: filtered ? 'No matching launches' : 'No launches yet' }),el('p', {- text: tierLabel- ? `No three.ws agent launches have ${tierLabel} Oracle scores yet. Try a lower tier or clear the filter.`- : state.agentId- ? 'This agent has not launched a coin on this network. Clear the filter to see the full feed.'- : state.network === 'devnet'- ? 'Nothing has been launched on devnet. Switch to mainnet to see live launches.'- : 'Be the first: create an agent, give it a coin, and it shows up here in real time.',+ text: state.agentId+ ? 'This agent has not launched a coin on this network. Clear the filter to see the full feed.'+ : state.network === 'devnet'+ ? 'Nothing has been launched on devnet. Switch to mainnet to see live launches.'+ : 'Be the first: create an agent, give it a coin, and it shows up here in real time.',}),filtered? el('button', {class: 'lx-btn',type: 'button',text: 'Clear filters',- onclick: () => { setAgentFilter(null); setOracleTier(''); },+ onclick: () => setAgentFilter(null),}): state.network === 'devnet'? el('div', { class: 'lx-state-ctas' }, [@@ -815,7 +763,6 @@ async function fetchLaunches(offset, limit) {limit: String(limit),});if (state.agentId) params.set('agent_id', state.agentId);- if (state.oracleTier) params.set('min_tier', state.oracleTier);const r = await fetch(`/api/pump/launches?${params}`);if (!r.ok) throw new Error(`launches api ${r.status}`);const body = await r.json();@@ -847,21 +794,12 @@ async function loadPage({ reset = false } = {}) {clearSkeletons();const newCards = [];- const cardsNeedingOracle = [];launches.forEach((l, i) => {state.seenMints.add(l.mint);const card = launchCard(l, i, { featured: isFirstPage && i === 0 });feedEl.appendChild(card);newCards.push(card);- // When the API already returned Oracle data (Oracle-tier filter active),- // paint the badge immediately — no batch fetch needed.- if (l.oracle) {- paintOracleBadge(card, l.mint, l.oracle);- } else {- cardsNeedingOracle.push(card);- }});- if (cardsNeedingOracle.length) enrichCardsWithOracle(cardsNeedingOracle);state.offset += launches.length;state.count += launches.length;state.hasMore = hasMore;@@ -915,7 +853,6 @@ async function liveRefresh() {feedEl.insertBefore(card, anchor || feedEl.firstChild);freshCards.push(card);}- enrichCardsWithOracle(freshCards);// Slide the just-landed launches in from the top (newest first) and fire a// single restrained ripple on the hero count — a real "new launch shipped"// beat backed by the live poll, not a timer.@@ -936,8 +873,9 @@ function syncUrl() {else url.searchParams.delete('network');if (state.agentId) url.searchParams.set('agent_id', state.agentId);else url.searchParams.delete('agent_id');- if (state.oracleTier) url.searchParams.set('oracle_tier', state.oracleTier);- else url.searchParams.delete('oracle_tier');+ // Old shared links may still carry a conviction-tier filter; the feed no+ // longer ranks coins, so drop it from the address bar.+ url.searchParams.delete('oracle_tier');history.replaceState(null, '', url);}@@ -963,18 +901,6 @@ function setNetwork(network) {loadPage({ reset: true });}-function setOracleTier(tier) {- if (state.oracleTier === tier) return;- state.oracleTier = tier;- document.querySelectorAll('.lx-of-btn').forEach((b) => {- const active = b.dataset.tier === tier;- b.classList.toggle('active', active);- b.setAttribute('aria-pressed', String(active));- });- syncUrl();- loadPage({ reset: true });-}-function setAgentFilter(agentId) {state.agentId = agentId;agentFilterEl.hidden = !agentId;@@ -1019,9 +945,6 @@ function boot() {state.network = qs.get('network') === 'devnet' ? 'devnet' : 'mainnet';const agentId = qs.get('agent_id');state.agentId = agentId && /^[0-9a-f-]{36}$/i.test(agentId) ? agentId : null;- const VALID_TIERS = new Set(['prime', 'strong', 'lean']);- const oracleTierParam = qs.get('oracle_tier') || '';- state.oracleTier = VALID_TIERS.has(oracleTierParam) ? oracleTierParam : '';const netBtns = [...document.querySelectorAll('.lx-net-btn')];syncNetworkTabs(state.network);@@ -1038,13 +961,6 @@ function boot() {});});- document.querySelectorAll('.lx-of-btn').forEach((b) => {- const active = b.dataset.tier === state.oracleTier;- b.classList.toggle('active', active);- b.setAttribute('aria-pressed', String(active));- b.addEventListener('click', () => setOracleTier(b.dataset.tier));- });-if (state.agentId) {agentFilterEl.hidden = false;renderAgentFilterChip(state.agentId);diff --git a/src/mission-control/chart.js b/src/mission-control/chart.jsindex f33af2816..c3c532f98 100644--- a/src/mission-control/chart.js+++ b/src/mission-control/chart.js@@ -5,7 +5,7 @@* TradingView's open-source `lightweight-charts`. Two real data paths, never* fabricated:*- * • History — GET /api/pump/price-history (Birdeye → GeckoTerminal OHLCV).+ * • History: GET /api/pump/price-history (Birdeye, GeckoTerminal, then pump.fun OHLCV).* • Realtime — the per-mint trade firehose (SSE /api/pump/trades-stream?mint).* Each on-chain buy/sell updates the live candle tick-by-tick: the execution* price is `sol_amount / token_amount × sol_price` (falling back to@@ -244,6 +244,7 @@ export function mountPriceChart({ host, mint }) {);if (r.ok) payload = await r.json();else if (r.status === 502) payload = { data: [] };+ else if (r.status === 404) payload = { data: [], noMarket: true };} catch {/* network — handled below */}@@ -264,8 +265,14 @@ export function mountPriceChart({ host, mint }) {.filter((b) => Number.isFinite(b.time) && Number.isFinite(b.close) && b.close > 0).sort((a, b) => a.time - b.time);- if (bars.length < 2) {- if (!quiet) showMsg(`No ${interval.label} price history yet for this coin.`);+ // One candle is a real chart: a coin minutes old has exactly that, and the+ // live stream grows it from there.+ if (!bars.length) {+ if (!quiet) {+ showMsg(payload.noMarket+ ? 'No market yet: this coin has not traded, so there is nothing to chart.'+ : `No ${interval.label} price history yet for this coin.`);+ }return;}diff --git a/src/shared/chart-embeds.js b/src/shared/chart-embeds.jsnew file mode 100644index 000000000..f387de630--- /dev/null+++ b/src/shared/chart-embeds.js@@ -0,0 +1,169 @@+// Embeddable third-party price charts, keyed by a token's on-chain identity.+//+// Every coin page on three.ws lets the viewer pick the chart they trust. The+// URL shapes for each provider live here once, so /launches/<mint> and+// /coin/:id build identical embeds and a provider changing its embed format is+// a one-file fix.+//+// Only providers verified to render inside a cross-origin <iframe> without a+// key are listed. Checked in a real browser, 2026-09-17:+// DexScreener token address, resolves the top pair itself+// Birdeye token address (its TradingView-based tv-widget)+// GMGN token address (its kline widget), Solana/ETH/Base/BSC only+// GeckoTerminal pool address, and only once GeckoTerminal indexed that pool+// Refused framing or needs a key, so deliberately absent: DEXTools+// (X-Frame-Options), Codex/Defined (frame-ancestors / bot checkpoint), Moralis+// (key-restricted widget), pump.fun, Jupiter, Photon, Axiom, Solscan.+//+// Each chain entry holds the slug every provider uses for that chain. A chain a+// provider does not index is simply missing from its field, and the provider is+// not offered for that coin rather than rendering a dead chart.++const EVM_RE = /^0x[0-9a-fA-F]{40}$/;+const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++/** Chain id (CoinGecko asset-platform id) → per-provider slug. Solana leads. */+export const CHART_CHAINS = {+ solana: { ds: 'solana', gt: 'solana', be: 'solana', gm: 'sol', evm: false },+ ethereum: { ds: 'ethereum', gt: 'eth', be: 'ethereum', gm: 'eth', evm: true },+ base: { ds: 'base', gt: 'base', be: 'base', gm: 'base', evm: true },+ 'binance-smart-chain': { ds: 'bsc', gt: 'bsc', be: 'bsc', gm: 'bsc', evm: true },+ 'polygon-pos': { ds: 'polygon', gt: 'polygon_pos', be: 'polygon', evm: true },+ 'arbitrum-one': { ds: 'arbitrum', gt: 'arbitrum', be: 'arbitrum', evm: true },+ 'optimistic-ethereum': { ds: 'optimism', gt: 'optimism', be: 'optimism', evm: true },+ avalanche: { ds: 'avalanche', gt: 'avax', be: 'avalanche', evm: true },+};++/** True when `address` is well-formed for `chain`. */+export function validChartAddress(chain, address) {+ const c = CHART_CHAINS[chain];+ if (!c || typeof address !== 'string') return false;+ return c.evm ? EVM_RE.test(address) : SOL_RE.test(address);+}++const enc = encodeURIComponent;++/**+ * The embeddable providers, in the order a switcher shows them.+ *+ * `needs` is 'token' (keyed by the token address) or 'pool' (keyed by a pool+ * address the caller resolves first). `embed()` returns the iframe URL and+ * `page()` the provider's own page for the same market, used by "open in"+ * links and by the fallback panel when an embed is blocked.+ */+export const CHART_EMBEDS = [+ {+ id: 'dexscreener',+ label: 'DexScreener',+ needs: 'token',+ slug: 'ds',+ embed: ({ slug, token, theme }) =>+ `https://dexscreener.com/${slug}/${enc(token)}?${new URLSearchParams({+ embed: '1',+ loadChartSettings: '0',+ theme,+ chartTheme: theme,+ chartType: 'usd',+ interval: '15',+ info: '0',+ })}`,+ page: ({ slug, token }) => `https://dexscreener.com/${slug}/${enc(token)}`,+ },+ {+ id: 'birdeye',+ label: 'Birdeye',+ needs: 'token',+ slug: 'be',+ embed: ({ slug, token, theme }) =>+ `https://birdeye.so/tv-widget/${enc(token)}?${new URLSearchParams({+ chain: slug,+ viewMode: 'pair',+ chartInterval: '15',+ chartType: 'CANDLE',+ chartLeftToolbar: 'show',+ theme,+ })}`,+ page: ({ slug, token }) => `https://birdeye.so/token/${enc(token)}?chain=${enc(slug)}`,+ },+ {+ id: 'gmgn',+ label: 'GMGN',+ needs: 'token',+ slug: 'gm',+ embed: ({ slug, token, theme }) =>+ `https://www.gmgn.cc/kline/${slug}/${enc(token)}?${new URLSearchParams({ theme, interval: '15' })}`,+ page: ({ slug, token }) => `https://gmgn.ai/${slug}/token/${enc(token)}`,+ },+ {+ id: 'geckoterminal',+ label: 'GeckoTerminal',+ needs: 'pool',+ slug: 'gt',+ embed: ({ slug, pool, theme }) =>+ `https://www.geckoterminal.com/${slug}/pools/${enc(pool)}?${new URLSearchParams({+ embed: '1',+ info: '0',+ swaps: '0',+ grayscale: '0',+ light_chart: theme === 'light' ? '1' : '0',+ })}`,+ page: ({ slug, pool }) => `https://www.geckoterminal.com/${slug}/pools/${enc(pool)}`,+ },+];++/** Providers that index `chain`. */+export function chartEmbedsFor(chain) {+ const c = CHART_CHAINS[chain];+ if (!c) return [];+ return CHART_EMBEDS.filter((p) => c[p.slug]);+}++/**+ * Builds the embed and page URLs for one provider on one market.+ *+ * @param {string} providerId+ * @param {{ chain: string, token: string, pool?: string|null, theme?: 'dark'|'light' }} market+ * @returns {{ embed: string, page: string } | null} null when the provider does+ * not index the chain, or it needs a pool that was not supplied.+ */+export function chartEmbedUrls(providerId, { chain, token, pool = null, theme = 'dark' }) {+ const provider = CHART_EMBEDS.find((p) => p.id === providerId);+ const slug = provider && CHART_CHAINS[chain]?.[provider.slug];+ if (!slug) return null;+ if (provider.needs === 'pool' && !pool) return null;+ const args = { slug, token, pool, theme: theme === 'light' ? 'light' : 'dark' };+ return { embed: provider.embed(args), page: provider.page(args) };+}++/**+ * Resolves the pool GeckoTerminal's embed is keyed by, and whether GeckoTerminal+ * has indexed it. /api/coin/pool falls back to DexScreener for a token+ * GeckoTerminal does not know yet (every young pump.fun coin), and GeckoTerminal+ * answers its embed for an unindexed pool with a full-page 404, so the pool is+ * confirmed against GeckoTerminal's own public API (CORS-open, keyless) before+ * the embed is mounted.+ *+ * @param {string} chain+ * @param {string} token+ * @param {{ signal?: AbortSignal }} [opts]+ * @returns {Promise<{ pool: string|null, indexed: boolean }>}+ */+export async function resolveGeckoPool(chain, token, { signal } = {}) {+ const network = CHART_CHAINS[chain]?.gt;+ if (!network) return { pool: null, indexed: false };+ const r = await fetch(`/api/coin/pool?address=${enc(token)}&network=${enc(network)}`, {+ headers: { accept: 'application/json' },+ signal,+ });+ if (r.status === 404) return { pool: null, indexed: false };+ if (!r.ok) throw new Error(`pool lookup ${r.status}`);+ const { pool } = await r.json();+ if (!pool) return { pool: null, indexed: false };+ const gt = await fetch(`https://api.geckoterminal.com/api/v2/networks/${enc(network)}/pools/${enc(pool)}`, {+ headers: { accept: 'application/json' },+ signal,+ });+ if (gt.status === 404) return { pool, indexed: false };+ if (!gt.ok) throw new Error(`GeckoTerminal ${gt.status}`);+ return { pool, indexed: true };+}diff --git a/tests/api/pump-price-history-resilience.test.js b/tests/api/pump-price-history-resilience.test.jsindex 9853c65a2..f0bf0646c 100644--- a/tests/api/pump-price-history-resilience.test.js+++ b/tests/api/pump-price-history-resilience.test.js@@ -20,7 +20,12 @@ vi.mock('../../api/_lib/birdeye.js', () => ({vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));-import handler, { snapWindow, POLL_BUCKET_SECONDS } from '../../api/pump/price-history.js';+import handler, {+ snapWindow,+ POLL_BUCKET_SECONDS,+ aggregateCandles,+ mapPumpCandles,+} from '../../api/pump/price-history.js';const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';const POOL = '58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo7';@@ -130,10 +135,11 @@ describe('geckoFetch retry (via the handler)', () => {expect(getJson(res).error).toBe('upstream_error');});- it('serves the honest no_market 404 for a mint GeckoTerminal has never indexed, without retrying', async () => {+ it('serves the honest no_market 404 when neither GeckoTerminal nor pump.fun has a market, without retrying', async () => {let poolCalls = 0;vi.spyOn(globalThis, 'fetch').mockImplementation(async (url) => {if (String(url).includes('/pools?')) { poolCalls += 1; return { ok: false, status: 404, json: async () => ({}) }; }+ if (String(url).includes('swap-api.pump.fun')) return { ok: false, status: 404, json: async () => ({}) };throw new Error('should never reach the ohlcv endpoint');});const res = makeRes();@@ -144,6 +150,59 @@ describe('geckoFetch retry (via the handler)', () => {});});+describe('pump.fun candle rung', () => {+ it('charts a young pump.fun coin GeckoTerminal has not indexed yet', async () => {+ const now = Math.floor(Date.now() / 1000);+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (url) => {+ if (String(url).includes('/pools?')) return { ok: false, status: 404, json: async () => ({}) };+ if (String(url).includes('swap-api.pump.fun')) {+ return {+ ok: true,+ status: 200,+ json: async () => [+ { timestamp: (now - 600) * 1000, open: '0.0000027', high: '0.0000029', low: '0.0000026', close: '0.0000028', volume: '65.2' },+ ],+ };+ }+ throw new Error(`unexpected upstream ${url}`);+ });+ const res = makeRes();+ await handler(makeReq(`mint=${MINT.slice(0, 34)}${safeSuffix(90_001)}pump&interval=5m&from=${now - 3600}&to=${now}`), res);+ expect(res.statusCode).toBe(200);+ const body = getJson(res);+ expect(body.source).toBe('pumpfun');+ expect(body.data).toHaveLength(1);+ expect(body.data[0].c).toBeCloseTo(0.0000028, 12);+ });++ it('maps string-typed millisecond rows and drops unusable ones', () => {+ const rows = mapPumpCandles([+ { timestamp: 1_789_614_480_000, open: '2', high: '3', low: '1', close: '2.5', volume: '10' },+ { timestamp: 1_789_614_420_000, open: '1', high: '2', low: '1', close: '2', volume: 'x' },+ { timestamp: 'bad', open: '1', high: '1', low: '1', close: '1', volume: '1' },+ { timestamp: 1_789_614_540_000, open: '1', high: '1', low: '1', close: '0', volume: '1' },+ ]);+ expect(rows.map((r) => r.t)).toEqual([1_789_614_420, 1_789_614_480]);+ expect(rows[0].v).toBe(0);+ expect(mapPumpCandles(null)).toEqual([]);+ });++ it('folds base candles into epoch-aligned buckets for intervals pump.fun lacks', () => {+ const out = aggregateCandles(+ [+ { t: 7200, o: 1, h: 2, l: 0.5, c: 1.5, v: 10 },+ { t: 10800, o: 1.5, h: 4, l: 1, c: 3, v: 5 },+ { t: 14400, o: 3, h: 3, l: 2, c: 2.5, v: 1 },+ ],+ 7200,+ );+ expect(out).toEqual([+ { t: 7200, o: 1, h: 4, l: 0.5, c: 3, v: 15 },+ { t: 14400, o: 3, h: 3, l: 2, c: 2.5, v: 1 },+ ]);+ });+});+describe('concurrency gate', () => {it('never runs more than 4 GeckoTerminal fetches at once, even under a burst across many mints', async () => {let active = 0;diff --git a/tests/pump-launch-og-card.test.js b/tests/pump-launch-og-card.test.jsindex 223fa934d..9b887d78d 100644--- a/tests/pump-launch-og-card.test.js+++ b/tests/pump-launch-og-card.test.js@@ -1,13 +1,11 @@import { describe, it, expect } from 'vitest';import { renderCard } from '../api/pump/launch-og.js';-// Guards the /launches/<mint> social card against three defects that shipped-// silently because an SVG that renders is indistinguishable from an SVG that-// renders the right numbers:+// Guards the /launches/<mint> social card:// 1. the live market cap was read from a `market_cap_in_usd` key pump.fun// does not emit, so MKT CAP never appeared for a coin still on the curve;-// 2. organic_score / bundle_score are 0..1 fractions in pump_coin_intel but-// the gauge treated them as 0..100, drawing a 1 px bar labelled "0%";+// 2. the card stays neutral: raw launch counts only, never a score, a grade,+// or an engine label such as "rugged" on someone's coin;// 3. a fatal DB read had to degrade to a branded card, never a 5xx.const MINT = 'THREEsynthetic1111111111111111111111111111';@@ -17,7 +15,6 @@ function baseCard(overrides = {}) {name: 'Synthetic Launch',symbol: 'SYN',logoBase64: null,- qualityScore: 72,category: 'meme',isThreeWsLaunch: true,intel: null,@@ -36,7 +33,7 @@ describe('launch-og renderCard', () => {expect(svg).toContain('$SYN');// No enrichment supplied, so the optional blocks stay out of the card.expect(svg).not.toContain('MKT CAP');- expect(svg).not.toContain('ORGANIC BUY');+ expect(svg).not.toContain('UNIQUE BUYERS');});it('draws the live market cap a coin on the curve reports', () => {@@ -54,32 +51,23 @@ describe('launch-og renderCard', () => {expect(svg).toContain('$84K');});- it('scales the 0..1 organic and bundle fractions onto the percent gauge', () => {+ it('shows launch activity as raw counts', () => {const svg = renderCard(MINT, baseCard({- intel: { organic_score: 0.4279, bundle_score: 0.12, unique_buyers: 29 },+ intel: { unique_buyers: 29, buy_count: 41, sell_count: 12 },}));- // 42.79% of a 230 px bar, and the label reads the percentage, not the fraction.- expect(svg).toContain('>43%<');- expect(svg).toContain('width="98" height="8"');- expect(svg).toContain('>12%<');expect(svg).toContain('UNIQUE BUYERS');expect(svg).toContain('>29<');- // A clean launch keeps the amber bundle bar, not the red one.- expect(svg).toContain('#f59e0b');+ expect(svg).toContain('BUYS / SELLS AT LAUNCH');+ expect(svg).toContain('>41 / 12<');});- it('flags a coordinated launch in red once bundle passes the 0.3 threshold', () => {+ it('never puts a score or an engine verdict on the card', () => {const svg = renderCard(MINT, baseCard({- intel: { organic_score: 0.05, bundle_score: 0.61 },+ intel: { quality_score: 12, organic_score: 0.05, bundle_score: 0.61, unique_buyers: 3 },+ outcome: { rugged: true, outcome: 'rugged', last_market_cap_usd: 4_000 },}));- expect(svg).toContain('>61%<');- expect(svg).toContain('#ef4444');- });-- it('clamps a gauge score that exceeds its range instead of overflowing the bar', () => {- const svg = renderCard(MINT, baseCard({ intel: { organic_score: 4, bundle_score: 0 } }));- expect(svg).toContain('>100%<');- expect(svg).toContain('width="230" height="8"');+ for (const banned of ['SCORE', 'ORGANIC', 'BUNDLE', 'RUGGED']) expect(svg).not.toContain(banned);+ expect(svg).toContain('LIVE');});it('escapes coin metadata so a hostile name cannot inject SVG markup', () => {@@ -91,13 +79,11 @@ describe('launch-og renderCard', () => {it('still renders a branded card when every enrichment read failed', () => {const svg = renderCard(MINT, {- name: '', symbol: '', logoBase64: null, qualityScore: null, category: '',+ name: '', symbol: '', logoBase64: null, category: '',isThreeWsLaunch: false, intel: null, outcome: null, liveMcap: null,});expect(svg).toContain('Unknown coin');expect(svg).toContain('THREE.WS');- // Unknown quality reads as a placeholder, never as a fabricated score.- expect(svg).toContain('>-<');expect(svg).not.toContain('undefined');expect(svg).not.toContain('NaN');});diff --git a/vercel.json b/vercel.jsonindex c1ba0c29d..755f25ebf 100644--- a/vercel.json+++ b/vercel.json@@ -3446,6 +3446,10 @@"src": "/api/pump/safety","dest": "/api/pump/safety.js"},+ {+ "src": "/api/pump/token-stats",+ "dest": "/api/pump/token-stats.js"+ },{"src": "/api/pump/check-three-balance","dest": "/api/pump/check-three-balance.js"