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
fix(markets): share one market table across the coin surfaces and keep its fallbacks honest
nirholas5644b4cfc3e6
diff --git a/api/_lib/market-fallbacks.js b/api/_lib/market-fallbacks.jsindex c8ffbd7b1..14350275a 100644--- a/api/_lib/market-fallbacks.js+++ b/api/_lib/market-fallbacks.js@@ -26,7 +26,13 @@ import { CEX_BASE_BY_ID, cexPriceProviders, cexCandleProviders } from './cex-pubimport { downsample } from '../../src/shared/coin-format.js';import { cacheGet, cacheSet } from './cache.js';+// null/undefined and the empty string must stay null, not become 0: Number(null)+// is 0, which is how a coin CoinGecko reports with market_cap_rank: null landed+// in the table as rank 0 and sorted above Bitcoin (observed live 2026-09-03 on+// tradable-singapore-fintech-ssl-2). The same coercion turned every absent+// price, market cap and volume into a confident $0.00.const num = (v) => {+ if (v == null || v === '') return null;const n = Number(v);return Number.isFinite(n) ? n : null;};@@ -118,7 +124,9 @@ function exchangePriceProviders(id) {* @throws when every free source is down.*/export async function fetchCoinPriceUsd(coingeckoId) {- const id = String(coingeckoId || '').trim().toLowerCase();+ const id = String(coingeckoId || '')+ .trim()+ .toLowerCase();if (!/^[a-z0-9][a-z0-9_-]{0,99}$/.test(id)) throw new Error(`bad coin id: ${coingeckoId}`);const { value } = await fetchFirst([@@ -273,7 +281,10 @@ export function normalizeGeckoRow(c) {change_7d: num(c.price_change_percentage_7d_in_currency),market_cap: num(c.market_cap),volume_24h: num(c.total_volume),- sparkline: downsample((c.sparkline_in_7d?.price || []).filter((v) => Number.isFinite(v)), 32),+ sparkline: downsample(+ (c.sparkline_in_7d?.price || []).filter((v) => Number.isFinite(v)),+ 32,+ ),};}@@ -319,13 +330,21 @@ function normalizeLoreRow(c) {// on its own if a category is genuinely retired.const LKG_TTL_SECONDS = 86_400;-export async function fetchMarketsTable({ page, perPage, category }) {+/**+ * A page of ranked market rows. `sparkline` (default true) fetches the trailing+ * 7d price series CoinGecko bundles into each row; a caller that renders no+ * chart column passes false and CoinGecko leaves the arrays out, which is most+ * of the response weight at 250 rows. The fallback providers carry no+ * sparklines either way, so the flag only shapes the CoinGecko rung.+ */+export async function fetchMarketsTable({ page, perPage, category, sparkline = true }) {const providers = [{name: 'coingecko',url:`${COINGECKO_BASE}/coins/markets?vs_currency=usd&order=market_cap_desc` +- `&per_page=${perPage}&page=${page}&sparkline=true&price_change_percentage=24h,7d` ++ `&per_page=${perPage}&page=${page}&sparkline=${sparkline ? 'true' : 'false'}` ++ '&price_change_percentage=24h,7d' +(category ? `&category=${encodeURIComponent(category)}` : ''),init: { headers: geckoHeaders() },parse: async (r) => {@@ -358,9 +377,14 @@ export async function fetchMarketsTable({ page, perPage, category }) {// missing rung: real rows this same endpoint fetched earlier, replayed with// an explicit staleness marker so the page can label them, instead of a// blank error state. Nothing is synthesized; a cold cache still fails.- const lkgKey = category ? `coin:markets:lkg:${category}:p${page}:pp${perPage}` : null;+ const lkgKey = category+ ? `coin:markets:lkg:${category}:p${page}:pp${perPage}${sparkline ? '' : ':nospark'}`+ : null;try {- const { value, source } = await fetchFirst(providers, { timeoutMs: 10_000, label: 'markets-table' });+ const { value, source } = await fetchFirst(providers, {+ timeoutMs: 10_000,+ label: 'markets-table',+ });if (lkgKey && Array.isArray(value) && value.length) {// Best-effort write: a cache outage must never fail a healthy read.cacheSet(lkgKey, { rows: value, at: Date.now() }, LKG_TTL_SECONDS).catch(() => {});@@ -370,7 +394,12 @@ export async function fetchMarketsTable({ page, perPage, category }) {if (!lkgKey) throw err;const cached = await cacheGet(lkgKey).catch(() => null);if (!Array.isArray(cached?.rows) || !cached.rows.length) throw err;- return { rows: cached.rows, source: 'last-known-good', stale: true, asOf: cached.at ?? null };+ return {+ rows: cached.rows,+ source: 'last-known-good',+ stale: true,+ asOf: cached.at ?? null,+ };}}diff --git a/api/coin/markets.js b/api/coin/markets.jsindex a825f5e18..492c4c5ee 100644--- a/api/coin/markets.js+++ b/api/coin/markets.js@@ -1,4 +1,5 @@// GET /api/coin/markets?page=1&per_page=100 → ranked market table rows+// GET /api/coin/markets?…&sparkline=0 → same rows without 7d series// GET /api/coin/markets?q=<text> → coin search (id/name/symbol)// GET /api/coin/markets?category=<slug>&… → table rows for one category// ---------------------------------------------------------------------------@@ -49,7 +50,10 @@ export default wrap(async (req, res) => {}const page = Math.min(Math.max(1, parseInt(params.get('page') || '1', 10) || 1), 20);- const perPage = Math.min(Math.max(10, parseInt(params.get('per_page') || '100', 10) || 100), 250);+ const perPage = Math.min(+ Math.max(10, parseInt(params.get('per_page') || '100', 10) || 100),+ 250,+ );// Optional CoinGecko category id (e.g. layer-1, artificial-intelligence) —// scopes the table to one sector for the /category/:id coins list.const category = (params.get('category') || '').trim().toLowerCase();@@ -62,7 +66,16 @@ export default wrap(async (req, res) => {// gracefully). Category scoping has no second live source, so it falls back// to the last-known-good rows for that category and reports `stale` so the// page can say so rather than showing an empty table.- const { rows, stale, asOf } = await fetchMarketsTable({ page, perPage, category });+ // sparkline=0 drops the 7d price series from every row. /coins renders that+ // series as a chart column and keeps the default; /screener renders no+ // chart and opts out, cutting a 250-row response from ~215KB to ~70KB.+ const sparkline = !/^(0|false)$/i.test(params.get('sparkline') || '');+ const { rows, stale, asOf } = await fetchMarketsTable({+ page,+ perPage,+ category,+ sparkline,+ });return json(res,200,@@ -71,7 +84,9 @@ export default wrap(async (req, res) => {page,per_page: perPage,category: category || null,- ...(stale ? { stale: true, as_of: asOf ? new Date(asOf).toISOString() : null } : {}),+ ...(stale+ ? { stale: true, as_of: asOf ? new Date(asOf).toISOString() : null }+ : {}),},{// Stale rows are served briefly and revalidated hard: the moment the@@ -82,6 +97,11 @@ export default wrap(async (req, res) => {},);} catch {- return error(res, 502, 'upstream_error', 'market data is unavailable right now — retry shortly');+ return error(+ res,+ 502,+ 'upstream_error',+ 'market data is unavailable right now — retry shortly',+ );}});diff --git a/api/leaderboard/unified.js b/api/leaderboard/unified.jsindex 072d8a5e7..ffddfbccb 100644--- a/api/leaderboard/unified.js+++ b/api/leaderboard/unified.js@@ -40,6 +40,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';import { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';import { thumbnailUrl } from '../_lib/r2.js';+import { getStreak, listBadges } from '../_lib/streaks.js';export const maxDuration = 10;@@ -217,7 +218,24 @@ export default wrap(async (req, res) => {}}- res.setHeader('cache-control', 'public, max-age=15, s-maxage=30, stale-while-revalidate=60');+ // The `me`, `streak`, and `badges` blocks are per-viewer, so a signed-in+ // response must never reach a shared cache: `public` + `s-maxage` here would+ // let the CDN hand one creator's rank and badge list to the next visitor.+ // Anonymous responses are identical for everyone and stay edge-cacheable.+ res.setHeader(+ 'cache-control',+ viewerId+ ? 'private, max-age=15, stale-while-revalidate=60'+ : 'public, max-age=15, s-maxage=30, stale-while-revalidate=60',+ );++ // Streak and badges ride along with the board so the page resolves the whole+ // signed-in view in one request. Reading them from a username-keyed profile+ // endpoint instead used to leave every user who has not picked a username+ // (the default for a fresh account) with no streak card at all.+ const [streak, badges] = viewerId+ ? await Promise.all([getStreak(viewerId), listBadges(viewerId)])+ : [null, []];return json(res, 200, {metric,@@ -228,5 +246,7 @@ export default wrap(async (req, res) => {hasMore: offset + limit < total,rows: pageRows,me,+ streak,+ badges,});});diff --git a/pages/screener.html b/pages/screener.htmlindex 308c62e45..16cde25df 100644--- a/pages/screener.html+++ b/pages/screener.html@@ -21,7 +21,7 @@<title data-i18n="screener.meta_title">Token Screener · three.ws</title><metaname="description"- content="Filter the top 250 cryptocurrencies live — search by name, isolate gainers or losers, set minimum market cap and volume, and sort every column. Find your next coin fast."+ content="Filter the top 250 cryptocurrencies live: search by name, isolate gainers or losers, set minimum market cap and volume, and sort every column. Find your next coin fast."data-i18n-attr="content:screener.meta_description"/><meta property="og:type" content="website" /><meta property="og:site_name" content="three.ws" />@@ -29,7 +29,7 @@<meta property="og:title" content="Token Screener · three.ws" data-i18n-attr="content:screener.meta_og_title"/><metaproperty="og:description"- content="Filter the top 250 cryptocurrencies live — search, isolate gainers or losers, set minimum market cap and volume, and sort every column."+ content="Filter the top 250 cryptocurrencies live: search, isolate gainers or losers, set minimum market cap and volume, and sort every column."data-i18n-attr="content:screener.meta_og_description"/><metaproperty="og:image"@@ -42,7 +42,7 @@<meta name="twitter:title" content="Token Screener · three.ws" data-i18n-attr="content:screener.meta_twitter_title"/><metaname="twitter:description"- content="Filter the top 250 cryptocurrencies live — search, isolate gainers or losers, set minimum market cap and volume, and sort every column."+ content="Filter the top 250 cryptocurrencies live: search, isolate gainers or losers, set minimum market cap and volume, and sort every column."data-i18n-attr="content:screener.meta_twitter_description"/><metaname="twitter:image"@@ -61,7 +61,7 @@<link rel="canonical" href="https://three.ws/screener" /><meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" /><meta property="og:locale" content="en_US" />- <meta property="og:image:alt" content="Token Screener — three.ws" />+ <meta property="og:image:alt" content="Token Screener on three.ws" /><script type="application/ld+json">{@@ -94,7 +94,7 @@</nav><h1 class="cv-h1" data-i18n="screener.token_screener">Token Screener</h1><p class="cv-sub" data-i18n="screener.filter_the_top_250_coins_by_market">- Filter the top 250 coins by market cap in real time — search by name, isolate+ Filter the top 250 coins by market cap in real time. Search by name, isolategainers or losers, set floors on market cap and volume, then sort any column. Everyrow opens the full coin profile.</p>@@ -122,10 +122,17 @@autocomplete="off"spellcheck="false"aria-label="Filter coins by name or symbol"+ data-i18n-attr="placeholder:screener.search_placeholder;aria-label:screener.search_arialabel"/></div>- <div class="hm-seg" role="group" aria-label="Direction filter" id="scr-dir">+ <div+ class="hm-seg"+ role="group"+ aria-label="Direction filter"+ id="scr-dir"+ data-i18n-attr="aria-label:screener.direction_arialabel"+ ><button type="button" data-dir="all" aria-pressed="true" data-i18n="screener.all">All</button><button type="button" data-dir="gainers" aria-pressed="false" data-i18n="screener.gainers">Gainers</button><button type="button" data-dir="losers" aria-pressed="false" data-i18n="screener.losers">Losers</button>@@ -133,7 +140,11 @@<label class="scr-field"><span data-i18n="screener.min_market_cap">Min market cap</span>- <select id="scr-mcap" aria-label="Minimum market cap">+ <select+ id="scr-mcap"+ aria-label="Minimum market cap"+ data-i18n-attr="aria-label:screener.min_market_cap_arialabel"+ ><option value="0" data-i18n="screener.any">Any</option><option value="10000000" data-i18n="screener.10m">$10M+</option><option value="100000000" data-i18n="screener.100m">$100M+</option>@@ -145,7 +156,11 @@<label class="scr-field"><span data-i18n="screener.min_24h_volume">Min 24h volume</span>- <select id="scr-vol" aria-label="Minimum 24h volume">+ <select+ id="scr-vol"+ aria-label="Minimum 24h volume"+ data-i18n-attr="aria-label:screener.min_volume_arialabel"+ ><option value="0" data-i18n="screener.any_2">Any</option><option value="1000000" data-i18n="screener.1m">$1M+</option><option value="10000000" data-i18n="screener.10m_2">$10M+</option>@@ -168,7 +183,7 @@<!-- Results table. Hydrated by src/screener.js. --><section id="scr-table" aria-label="Screened cryptocurrencies"></section>- <p class="cv-updated" id="scr-updated"></p>+ <p class="cv-updated" id="scr-updated" role="status"></p></main><script type="module" src="/src/screener.js"></script>diff --git a/src/coins-index.js b/src/coins-index.jsindex fa60291e1..3ef1fb3ef 100644--- a/src/coins-index.js+++ b/src/coins-index.js@@ -4,7 +4,14 @@// load-more pagination. Every row links to the rich /coin/:id detail page.import { formatUsd, formatPercent, escapeHtml as esc } from './shared/coin-format.js';-import { coinRow, COIN_COLUMNS, coinSortValue } from './shared/market-table.js';+import {+ coinRow,+ COIN_COLUMNS,+ coinSortValue,+ sortableHeaderCells,+ bindSortableHeaders,+ bindRowNavigation,+} from './shared/market-table.js';import { onPageReady } from './shell/page-lifecycle.js';const $ = (id) => document.getElementById(id);@@ -22,14 +29,11 @@ async function getJson(url) {// ── Global stats bar ────────────────────────────────────────────────────────const ICONS = {- trend:- '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>',+ trend: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>',bars: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/></svg>',pie: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.21 15.89A10 10 0 1 1 8 2.83"/><path d="M22 12A10 10 0 0 0 12 2v10z"/></svg>',- coins:- '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6"/><path d="M18.09 10.37A6 6 0 1 1 10.34 18"/><path d="M7 6h1v4"/><path d="m16.71 13.88.7.71-2.82 2.82"/></svg>',- gauge:- '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 14 4-4"/><path d="M3.34 19a10 10 0 1 1 17.32 0"/></svg>',+ coins: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6"/><path d="M18.09 10.37A6 6 0 1 1 10.34 18"/><path d="M7 6h1v4"/><path d="m16.71 13.88.7.71-2.82 2.82"/></svg>',+ gauge: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 14 4-4"/><path d="M3.34 19a10 10 0 1 1 17.32 0"/></svg>',activity:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>',};@@ -59,7 +63,9 @@ async function loadStats() {if (!el) return; // shell navigation left /coins before the retry landedel.innerHTML ='<div style="display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(170px,1fr))">' +- Array.from({ length: 6 }, () => '<div class="cv-skel" style="height:6rem"></div>').join('') ++ Array.from({ length: 6 }, () => '<div class="cv-skel" style="height:6rem"></div>').join(+ '',+ ) +'</div>';try {const { market, fear_greed } = await getJson('/api/coin/global');@@ -76,7 +82,11 @@ async function loadStats() {deltaClass: (market.market_cap_change_pct_24h ?? 0) >= 0 ? 'cv-up' : 'cv-down',icon: 'trend',}),- statCard({ label: '24h Volume', value: formatUsd(market.volume_24h_usd), icon: 'bars' }),+ statCard({+ label: '24h Volume',+ value: formatUsd(market.volume_24h_usd),+ icon: 'bars',+ }),);for (const [i, d] of (market.dominance || []).entries()) {cards.push(@@ -175,16 +185,11 @@ function renderTable() {return;}- const head = COIN_COLUMNS.map((col) => {- const active = col.key === state.sortKey;- const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';- // Every sortable header carries aria-sort (the inactive ones as "none"), so- // a screen reader reads the whole row as sortable rather than one column.- const sort = active ? (state.sortDir === 'asc' ? 'ascending' : 'descending') : 'none';- return `<th scope="col" tabindex="0" data-key="${col.key}" aria-sort="${sort}" class="${col.left ? 'left' : ''} ${col.hide || ''}">${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;- }).join('');+ const head = sortableHeaderCells(COIN_COLUMNS, state.sortKey, state.sortDir);- const rows = sortedCoins().map(coinRow).join('');+ const rows = sortedCoins()+ .map((c) => coinRow(c))+ .join('');// Footer: the button while more rows exist, an end-of-list line once the feed// is exhausted (a button that can never add another row is a dead control),@@ -208,34 +213,8 @@ function renderTable() {</div>${footer}`;- el.querySelectorAll('th[data-key]').forEach((th) => {- const activate = () => {- const key = th.dataset.key;- if (key === state.sortKey) {- state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';- } else {- state.sortKey = key;- state.sortDir = key === 'name' || key === 'rank' ? 'asc' : 'desc';- }- renderTable();- };- th.addEventListener('click', activate);- th.addEventListener('keydown', (e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- activate();- }- });- });-- // Whole row navigates; the name link inside stays a real anchor for- // middle-click / keyboard users.- el.querySelectorAll('tr[data-href]').forEach((tr) => {- tr.addEventListener('click', (e) => {- if (e.target.closest('a')) return;- location.href = tr.dataset.href;- });- });+ bindSortableHeaders(el, state, renderTable);+ bindRowNavigation(el);$('cv-load-more')?.addEventListener('click', loadMore);}@@ -247,7 +226,10 @@ async function loadCoins() {if (!el) return; // shell navigation left /coins before the retry landedel.innerHTML ='<div class="cv-table-wrap" style="padding:0.75rem">' +- Array.from({ length: 12 }, () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>').join('') ++ Array.from(+ { length: 12 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('') +'</div>';try {const { coins } = await getJson(`/api/coin/markets?page=1&per_page=${PER_PAGE}`);@@ -270,7 +252,9 @@ async function loadMore() {state.moreErrorStatus = null;renderTable();try {- const { coins } = await getJson(`/api/coin/markets?page=${state.page + 1}&per_page=${PER_PAGE}`);+ const { coins } = await getJson(+ `/api/coin/markets?page=${state.page + 1}&per_page=${PER_PAGE}`,+ );const seen = new Set(state.coins.map((c) => c.id));const fresh = coins.filter((c) => !seen.has(c.id));state.coins.push(...fresh);@@ -350,7 +334,8 @@ function wireSearch() {input.setAttribute('aria-expanded', 'true');// Screen readers follow the active option through aria-activedescendant;// data-active only moves the highlight visually.- if (active >= 0 && items[active]) input.setAttribute('aria-activedescendant', `cv-search-opt-${active}`);+ if (active >= 0 && items[active])+ input.setAttribute('aria-activedescendant', `cv-search-opt-${active}`);else input.removeAttribute('aria-activedescendant');}diff --git a/src/community/coin-lobby.js b/src/community/coin-lobby.jsindex 3f76a1e50..d9b355bf6 100644--- a/src/community/coin-lobby.js+++ b/src/community/coin-lobby.js@@ -61,13 +61,17 @@ export class CoinLobby {_build() {const root = el('div', 'clobby');root.setAttribute('role', 'dialog');- root.setAttribute('aria-label', 'Choose a coin world');+ root.setAttribute('aria-labelledby', 'clobby-title');this.root = root;const inner = el('div', 'clobby__inner');const head = el('header', 'clobby__head');const titles = el('div', 'clobby__titles');- titles.appendChild(el('h1', 'clobby__h1', 'Enter a coin world'));+ // h2, not h1: this is a dialog layered over the host page, which owns the+ // document's single h1. The .clobby__h1 class carries the visual weight.+ const title = el('h2', 'clobby__h1', 'Enter a coin world');+ title.id = 'clobby-title';+ titles.appendChild(title);titles.appendChild(el('p',diff --git a/src/screener.js b/src/screener.jsindex c931e4c69..f1d2ff560 100644--- a/src/screener.js+++ b/src/screener.js@@ -1,17 +1,32 @@-// /screener — client-side token screener over the live top-250 markets.-// Loads /api/coin/markets?page=1&per_page=250 once, then filters and sorts-// entirely in the browser: text search, gainers/losers, market-cap and volume-// floors, and click-to-sort columns reusing the shared cv-table pattern from-// coins-index.js. Every row links to the rich /coin/:id detail page.--import { formatUsd, formatPrice, formatPercent, escapeHtml as esc } from './shared/coin-format.js';+// /screener: a client-side token screener over the live top-250 markets.+// Loads /api/coin/markets?page=1&per_page=250&sparkline=0 once, then filters+// and sorts entirely in the browser: text search, gainers/losers, market-cap+// and volume floors, and click-to-sort columns. Rows, columns, sorting and+// row navigation come from src/shared/market-table.js, the same primitives+// /coins renders, so the two tables cannot drift apart. Every row links to the+// rich /coin/:id detail page.++import { escapeHtml as esc } from './shared/coin-format.js';+import {+ coinRow,+ COIN_COLUMNS,+ coinSortValue,+ sortableHeaderCells,+ bindSortableHeaders,+ bindRowNavigation,+} from './shared/market-table.js';const $ = (id) => document.getElementById(id);+// The screener renders no 7d chart column, so it asks the endpoint to leave the+// sparkline arrays out. Over 250 rows that is the difference between a ~215KB+// and a ~70KB response for exactly the same table.+const MARKETS_URL = '/api/coin/markets?page=1&per_page=250&sparkline=0';+async function getJson(url) {const res = await fetch(url, { headers: { accept: 'application/json' } });if (!res.ok) {- const err = new Error(`fetch ${url} → ${res.status}`);+ const err = new Error(`fetch ${url} -> ${res.status}`);err.status = res.status;throw err;}@@ -20,20 +35,16 @@ async function getJson(url) {// ── State ─────────────────────────────────────────────────────────────────────-const COLUMNS = [- { key: 'rank', label: '#', left: true, hide: 'hide-sm', num: true },- { key: 'name', label: 'Coin', left: true },- { key: 'price', label: 'Price', num: true },- { key: 'change_24h', label: '24h %', num: true },- { key: 'change_7d', label: '7d %', hide: 'hide-md', num: true },- { key: 'market_cap', label: 'Mkt Cap', hide: 'hide-lg', num: true },- { key: 'volume_24h', label: 'Vol (24h)', hide: 'hide-lg', num: true },-];-const state = {coins: [],loaded: false,- error: false,+ // A 429 is our own per-IP budget rather than an upstream outage, so the two+ // failures need different advice; null means the fetch has not failed.+ errorStatus: null,+ // Set when the endpoint served last-known-good rows because every live+ // provider was down. The table is real data, just not current, and saying so+ // beats a timestamp that claims otherwise.+ staleAsOf: null,sortKey: 'rank',sortDir: 'asc',q: '',@@ -56,17 +67,11 @@ function filtered() {});}-function sortValue(c, key) {- if (key === 'name') return (c.name || '').toLowerCase();- if (key === 'rank') return c.rank ?? Infinity;- return c[key] ?? -Infinity;-}-function sorted(rows) {const { sortKey, sortDir } = state;return [...rows].sort((a, b) => {- const va = sortValue(a, sortKey);- const vb = sortValue(b, sortKey);+ const va = coinSortValue(a, sortKey);+ const vb = coinSortValue(b, sortKey);const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;return sortDir === 'asc' ? cmp : -cmp;});@@ -74,28 +79,39 @@ function sorted(rows) {// ── Rendering ─────────────────────────────────────────────────────────────────-function pctCell(v, extraClass = '') {- if (v == null) return `<td class="pct dim ${extraClass}">—</td>`;- const up = v >= 0;- return `<td class="pct ${up ? 'cv-up' : 'cv-down'} ${extraClass}"><span aria-hidden="true">${up ? '▲' : '▼'}</span>${esc(formatPercent(v))}</td>`;-}-function updateCount(shown) {const el = $('scr-count');if (!el) return;- if (!state.loaded) {- el.textContent = '';- return;- }- el.textContent = `${shown.toLocaleString('en-US')} of ${state.coins.length.toLocaleString('en-US')} coins`;+ el.textContent = state.loaded+ ? `${shown.toLocaleString('en-US')} of ${state.coins.length.toLocaleString('en-US')} coins`+ : '';+}++// The failure the user hit decides the advice: retrying into our own rate limit+// only spends the next request they have, so that case asks for a pause first.+function whyFailed(status) {+ return status === 429+ ? 'You have loaded this feed too many times in a row. Give it a minute, then'+ : 'The market data provider did not answer.';+}++function renderSkeleton() {+ $('scr-table').innerHTML =+ '<div class="cv-table-wrap" style="padding:0.75rem">' ++ Array.from(+ { length: 14 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('') ++ '</div>';}function renderTable() {const el = $('scr-table');+ if (!el) return;- if (state.error) {- el.innerHTML =- '<div class="cv-empty">Market data is temporarily unavailable. Please try again shortly.</div>';+ if (state.errorStatus) {+ el.innerHTML = `<div class="cv-empty" role="status">The screener could not load the market table. ${whyFailed(state.errorStatus)} <button type="button" class="cv-linkbtn" data-act="retry">${state.errorStatus === 429 ? 'load it again' : 'Try again'}</button>.</div>`;+ el.querySelector('[data-act="retry"]')?.addEventListener('click', load);updateCount(0);return;}@@ -104,73 +120,49 @@ function renderTable() {const rows = sorted(filtered());updateCount(rows.length);- if (!rows.length) {+ if (!state.coins.length) {el.innerHTML =- '<div class="cv-empty">No coins match these filters. Try widening your market-cap or volume floor, or <button type="button" class="scr-empty-reset" id="scr-empty-reset">reset all filters</button>.</div>';- $('scr-empty-reset')?.addEventListener('click', resetFilters);+ '<div class="cv-empty" role="status">No coins are being reported right now. <button type="button" class="cv-linkbtn" data-act="retry">Refresh</button> to check again.</div>';+ el.querySelector('[data-act="retry"]')?.addEventListener('click', load);return;}- const head = COLUMNS.map((col) => {- const active = col.key === state.sortKey;- const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';- return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;- }).join('');-- const body = rows- .map((c) => {- const href = `/coin/${encodeURIComponent(c.id)}`;- return `- <tr data-href="${esc(href)}">- <td class="rank hide-sm cv-mono">${c.rank ?? '—'}</td>- <td class="left name-cell"><a href="${esc(href)}"><span class="inner">- ${c.image ? `<img src="${esc(c.image)}" alt="" loading="lazy" width="24" height="24" data-no-dark-filter />` : ''}- <span class="nm">${esc(c.name)}</span>- <span class="sym">${esc(c.symbol)}</span>- </span></a></td>- <td class="price">${esc(formatPrice(c.price))}</td>- ${pctCell(c.change_24h)}- ${pctCell(c.change_7d, 'hide-md')}- <td class="dim hide-lg">${esc(formatUsd(c.market_cap))}</td>- <td class="dim hide-lg">${esc(formatUsd(c.volume_24h))}</td>- </tr>`;- })- .join('');+ if (!rows.length) {+ el.innerHTML =+ '<div class="cv-empty" role="status">No coins match these filters. Try widening your market-cap or volume floor, or <button type="button" class="cv-linkbtn" data-act="reset">reset all filters</button>.</div>';+ el.querySelector('[data-act="reset"]')?.addEventListener('click', resetFilters);+ return;+ }el.innerHTML = `<div class="cv-table-wrap"><table class="cv-table">- <thead><tr>${head}</tr></thead>- <tbody>${body}</tbody>+ <thead><tr>${sortableHeaderCells(COIN_COLUMNS, state.sortKey, state.sortDir)}</tr></thead>+ <tbody>${rows.map((c) => coinRow(c, { sparkline: false })).join('')}</tbody></table></div>`;- el.querySelectorAll('th[data-key]').forEach((th) => {- const activate = () => {- const key = th.dataset.key;- if (key === state.sortKey) {- state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';- } else {- state.sortKey = key;- state.sortDir = key === 'name' || key === 'rank' ? 'asc' : 'desc';- }- renderTable();- };- th.addEventListener('click', activate);- th.addEventListener('keydown', (e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- activate();- }- });- });+ bindSortableHeaders(el, state, renderTable);+ bindRowNavigation(el);+}- el.querySelectorAll('tr[data-href]').forEach((tr) => {- tr.addEventListener('click', (e) => {- if (e.target.closest('a')) return;- location.href = tr.dataset.href;- });- });+// The footer line is the page's only claim about freshness, so it never says+// "Updated <now>" over rows the endpoint flagged as last-known-good.+function renderUpdated() {+ const el = $('scr-updated');+ if (!el) return;+ if (state.errorStatus || !state.loaded) {+ el.textContent = '';+ return;+ }+ if (state.staleAsOf) {+ const at = new Date(state.staleAsOf);+ const when = Number.isNaN(at.getTime()) ? null : at.toLocaleString('en-US');+ el.innerHTML = `<span class="cv-src-note" title="Every live market provider is unreachable, so these are the last rows this feed fetched successfully.">Live market data is unavailable${when ? `; showing the last rows fetched at ${esc(when)}` : '; showing the last rows fetched'}.</span> <button type="button" class="cv-linkbtn" data-act="refresh">Try for live prices</button>.`;+ el.querySelector('[data-act="refresh"]')?.addEventListener('click', load);+ return;+ }+ el.textContent = `Updated ${new Date().toLocaleTimeString('en-US')}`;}// ── Controls ──────────────────────────────────────────────────────────────────@@ -228,24 +220,23 @@ function wireControls() {// ── Load ──────────────────────────────────────────────────────────────────────async function load() {- const el = $('scr-table');- el.innerHTML =- '<div class="cv-table-wrap" style="padding:0.75rem">' +- Array.from(- { length: 14 },- () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',- ).join('') +- '</div>';+ // A retry starts from the same clean slate as the first load, so a recovered+ // upstream clears the error box instead of rendering behind it.+ state.errorStatus = null;+ state.staleAsOf = null;+ state.loaded = false;+ renderSkeleton();+ renderUpdated();try {- const { coins } = await getJson('/api/coin/markets?page=1&per_page=250');- state.coins = Array.isArray(coins) ? coins : [];+ const data = await getJson(MARKETS_URL);+ state.coins = Array.isArray(data.coins) ? data.coins : [];+ state.staleAsOf = data.stale ? data.as_of || null : null;state.loaded = true;- $('scr-updated').textContent = `Updated ${new Date().toLocaleTimeString('en-US')}`;- } catch {- state.error = true;- $('scr-updated').textContent = '';+ } catch (err) {+ state.errorStatus = err.status || 502;}renderTable();+ renderUpdated();}wireControls();diff --git a/src/shared/market-table.js b/src/shared/market-table.jsindex 953a8a01f..13ba65e99 100644--- a/src/shared/market-table.js+++ b/src/shared/market-table.js@@ -11,7 +11,10 @@ export function sparkline(prices) {const w = 120;const h = 32;const pts = prices- .map((p, i) => `${((i / (prices.length - 1)) * w).toFixed(1)},${(h - ((p - min) / range) * h).toFixed(1)}`)+ .map(+ (p, i) =>+ `${((i / (prices.length - 1)) * w).toFixed(1)},${(h - ((p - min) / range) * h).toFixed(1)}`,+ ).join(' ');const up = prices[prices.length - 1] >= prices[0];return `<svg width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" aria-hidden="true" style="display:inline-block"><polyline points="${pts}" fill="none" stroke="${up ? 'var(--cv-chart-green)' : 'var(--cv-chart-red)'}" stroke-width="1.5" stroke-linejoin="round"/></svg>`;@@ -23,7 +26,12 @@ export function pctCell(v, extraClass = '') {return `<td class="pct ${up ? 'cv-up' : 'cv-down'} ${extraClass}"><span aria-hidden="true">${up ? '▲' : '▼'}</span>${esc(formatPercent(v))}</td>`;}-export function coinRow(c) {+/**+ * One market-table row. `sparkline` renders the trailing 7d chart cell; pass+ * false on a table whose header row has no chart column (the /screener table),+ * or the body would carry one more cell than the head declares.+ */+export function coinRow(c, { sparkline: withSparkline = true } = {}) {const href = `/coin/${encodeURIComponent(c.id)}`;return `<tr data-href="${esc(href)}">@@ -38,7 +46,7 @@ export function coinRow(c) {${pctCell(c.change_7d, 'hide-md')}<td class="dim hide-lg">${esc(formatUsd(c.market_cap))}</td><td class="dim hide-lg">${esc(formatUsd(c.volume_24h))}</td>- <td class="hide-xl">${sparkline(c.sparkline)}</td>+ ${withSparkline ? `<td class="hide-xl">${sparkline(c.sparkline)}</td>` : ''}</tr>`;}@@ -52,8 +60,80 @@ export const COIN_COLUMNS = [{ key: 'volume_24h', label: 'Vol (24h)', hide: 'hide-lg', num: true },];+/**+ * Sortable header cells for a market table. Every column carries aria-sort+ * (the inactive ones as "none") so a screen reader reads the whole row as+ * sortable rather than one column, and the caller binds click/Enter/Space on+ * `th[data-key]`. Shared so /coins and /screener cannot drift apart on the+ * markup a keyboard or screen-reader user depends on.+ */+export function sortableHeaderCells(columns, sortKey, sortDir) {+ return columns+ .map((col) => {+ const active = col.key === sortKey;+ const arrow = active ? (sortDir === 'asc' ? '\u2191' : '\u2193') : '\u2195';+ const sort = active ? (sortDir === 'asc' ? 'ascending' : 'descending') : 'none';+ return `<th scope="col" tabindex="0" data-key="${col.key}" aria-sort="${sort}" class="${col.left ? 'left' : ''} ${col.hide || ''}">${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ })+ .join('');+}++/**+ * Bind sorting to the header cells of a rendered table. Clicking or pressing+ * Enter/Space on a header sorts by it, and re-activating the active header+ * flips the direction. Text columns open ascending, numeric ones descending,+ * which is the order a reader expects from each.+ */+export function bindSortableHeaders(root, state, rerender) {+ root.querySelectorAll('th[data-key]').forEach((th) => {+ const activate = (viaKeyboard) => {+ const key = th.dataset.key;+ if (key === state.sortKey) {+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';+ } else {+ state.sortKey = key;+ state.sortDir = key === 'name' || key === 'rank' ? 'asc' : 'desc';+ }+ rerender();+ // The rerender replaces the header row, so the element that was just+ // activated no longer exists and focus falls back to <body>. A keyboard+ // user would have to tab back in to flip the direction, which makes the+ // second press of a two-press interaction unreachable. Move focus onto+ // the replacement header for the same column.+ if (viaKeyboard) root.querySelector(`th[data-key="${key}"]`)?.focus();+ };+ th.addEventListener('click', () => activate(false));+ th.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ activate(true);+ }+ });+ });+}++/**+ * Make every rendered row navigate to its coin. The name link inside stays a+ * real anchor so middle-click, keyboard and "open in new tab" keep working;+ * clicking anywhere else on the row follows the same href.+ */+export function bindRowNavigation(root) {+ root.querySelectorAll('tr[data-href]').forEach((tr) => {+ tr.addEventListener('click', (e) => {+ if (e.target.closest('a')) return;+ location.href = tr.dataset.href;+ });+ });+}++// Unranked coins sort last, but the sentinel has to be finite: two of them+// compared as Infinity - Infinity yields NaN, and a comparator that returns NaN+// leaves the engine's sort free to scramble the whole table, not just those two+// rows.+const UNRANKED = Number.MAX_SAFE_INTEGER;+export function coinSortValue(c, key) {if (key === 'name') return (c.name || '').toLowerCase();- if (key === 'rank') return c.rank ?? Infinity;+ if (key === 'rank') return c.rank ?? UNRANKED;return c[key] ?? 0;}diff --git a/src/three-token-page.js b/src/three-token-page.jsindex cd1b54bfb..aa138137e 100644--- a/src/three-token-page.js+++ b/src/three-token-page.js@@ -10,7 +10,7 @@ import { createThreeTokenData, THREE_MINT } from './pump/three-token-data.js';import { mountBondingCurve } from './widgets/bonding-curve.js';import { openSwapModal } from './swap-jupiter.js';import { trackFunnelStep, ANALYTICS_EVENTS } from './analytics.js';-import { emptyStateHTML, ensureStateKitStyles } from './shared/state-kit.js';+import { emptyStateHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';import { paintVerifiedBadge } from './pump/verified-badge.js';const SOL_MINT = 'So11111111111111111111111111111111111111112';@@ -41,6 +41,31 @@ const fmtPct = (n) => {};const shortAddr = (a) => { const s = String(a || ''); return s.length > 9 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s; };const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+// Clipboard with a real fallback: navigator.clipboard is undefined on http+// origins and can be permission-denied, so drop to a selection copy before+// reporting failure. Returns whether the text actually made it to the clipboard.+async function copyText(text) {+ try {+ if (navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(text);+ return true;+ }+ } catch { /* fall through to the selection path */ }+ const ta = document.createElement('textarea');+ ta.value = text;+ ta.setAttribute('readonly', '');+ ta.style.cssText = 'position:fixed;top:0;left:-9999px;opacity:0';+ document.body.appendChild(ta);+ try {+ ta.select();+ return document.execCommand('copy');+ } catch {+ return false;+ } finally {+ ta.remove();+ }+}+const relTime = (sec) => {const d = Math.max(0, Math.floor(Date.now() / 1000 - Number(sec || 0)));if (d < 60) return `${d}s`;@@ -112,6 +137,7 @@ function injectStyles() {.tk-dot { width:7px; height:7px; border-radius:50%; background:#4ade80; box-shadow:0 0 8px #4ade80; }.tk-dot.off { background:#f87171; box-shadow:none; }.tk-empty { text-align:center; color:#7d7d86; font-size:13px; padding:40px 0; }+ .tk-stats-err { grid-column:1/-1; }.tk-skel { background:linear-gradient(90deg,#16161c,#1d1d24,#16161c); background-size:200% 100%; animation:tkSh 1.4s infinite; border-radius:10px; }@keyframes tkSh { from { background-position:200% 0; } to { background-position:-200% 0; } }.tk-foot { display:flex; gap:18px; flex-wrap:wrap; margin-top:26px; font-size:13px; }@@ -214,7 +240,16 @@ function renderBuybackRuns(runs) {}function renderBuyback(bb) {- if (!bb) return `<div class="tk-empty" style="padding:24px 0">Couldn’t load buyback data.</div>`;+ if (!bb) {+ return errorStateHTML({+ title: 'Buyback data is unavailable',+ body: 'The protocol stats feed didn’t respond. Every buyback is on-chain, so you can verify the treasury directly while this reconnects.',+ actions: [+ { label: 'Retry', id: 'bb-retry', primary: true },+ { label: 'Verify on Solscan', id: 'bb-solscan' },+ ],+ });+ }const revenue = fmtUsd(bb.revenue_usd);// The published promise — the headline a holder repeats. Defaults guard a// partial payload so the commitment always renders.@@ -262,10 +297,20 @@ function renderBuyback(bb) {// genuine live feed of on-chain trades.const TAPE_POLL_MS = 9_000;+const TAPE_EMPTY_HTML = () => emptyStateHTML({+ compact: true,+ live: true,+ icon: '',+ title: 'Live trades will appear here',+ body: 'As people buy and sell $THREE, each trade streams in here in real time.',+ tip: 'Live on-chain swaps from the $THREE DEX pool, refreshed every few seconds.',+});+function startTradeTape(tapeEl, statusEl) {let stopped = false;let timer = null;let everLoaded = false;+ let failStreak = 0;const seen = new Set();const setStatus = (online) => {@@ -279,6 +324,8 @@ function startTradeTape(tapeEl, statusEl) {// Drop the empty-state placeholder on the first real trade.const empty = tapeEl.querySelector('[data-empty]');if (empty) empty.remove();+ const stale = tapeEl.querySelector('[data-tape-error]');+ if (stale) stale.remove();const isBuy = t.is_buy ?? t.txType === 'buy';const usd = t.sol_value_usd != null ? fmtUsd(t.sol_value_usd) : null;@@ -316,12 +363,43 @@ function startTradeTape(tapeEl, statusEl) {const animate = everLoaded;for (let i = trades.length - 1; i >= 0; i--) addTrade(trades[i], animate);everLoaded = true;+ failStreak = 0;+ // A poll that succeeds but returns nothing is a quiet market, not a+ // fault: put the empty state back if an error frame is showing.+ const errBox = tapeEl.querySelector('[data-tape-error]');+ if (errBox && !tapeEl.querySelector('.tk-trade')) {+ tapeEl.innerHTML = `<div data-empty>${TAPE_EMPTY_HTML()}</div>`;+ }setStatus(true);} catch {+ failStreak += 1;setStatus(false);+ // Only claim an outage once nothing has ever loaded and two polls in a+ // row have failed. With rows on screen the last good frame stands.+ if (!everLoaded && failStreak >= 2 && !tapeEl.querySelector('[data-tape-error]')) {+ tapeEl.innerHTML = `<div data-tape-error>${errorStateHTML({+ title: 'Trade feed is unreachable',+ body: 'The $THREE swap feed didn’t respond. Trading itself is unaffected: the pool is live on-chain.',+ actions: [+ { label: 'Retry', id: 'tape-retry', primary: true },+ { label: 'View trades on Solscan ↗', id: 'tape-solscan' },+ ],+ })}</div>`;+ }}};+ tapeEl.addEventListener('click', (e) => {+ const act = e.target.closest('[data-sk-action]')?.dataset.skAction;+ if (act === 'tape-retry') {+ failStreak = 0;+ tapeEl.innerHTML = `<div data-empty>${TAPE_EMPTY_HTML()}</div>`;+ poll();+ } else if (act === 'tape-solscan') {+ window.open(`https://solscan.io/token/${THREE_MINT}`, '_blank', 'noopener');+ }+ });+setStatus(false);poll();timer = setInterval(poll, TAPE_POLL_MS);@@ -356,7 +434,7 @@ function boot() {// $THREE holder funnel, step 1: the token page is in view.trackFunnelStep('three', ANALYTICS_EVENTS.TOKEN_PAGE_VIEWED, {});- const wrap = document.createElement('div');+ const wrap = document.createElement('main');wrap.className = 'tk-wrap';wrap.innerHTML = `<div class="tk-head">@@ -365,7 +443,7 @@ function boot() {<div class="tk-titlerow"><h1 class="tk-title">$THREE</h1><span data-verified></span></div><p class="tk-sub">The protocol token powering the three.ws agent economy</p></div>- <button class="tk-ca" data-ca title="Copy contract address">${esc(shortAddr(THREE_MINT))} · copy</button>+ <button class="tk-ca" data-ca title="Copy contract address: ${esc(THREE_MINT)}">${esc(shortAddr(THREE_MINT))} · copy</button></div><div class="tk-stats" data-stats>${Array.from({ length: 4 }, () => `<div class="tk-stat"><div class="tk-skel" style="height:48px"></div></div>`).join('')}@@ -383,14 +461,7 @@ function boot() {<div class="tk-card"><h2 style="display:flex;align-items:center;justify-content:space-between">Live trades <span class="tk-status" data-tape-status></span></h2><div class="tk-tape" data-tape>- <div data-empty>${emptyStateHTML({- compact: true,- live: true,- icon: '',- title: 'Live trades will appear here',- body: 'As people buy and sell $THREE, each trade streams in here in real time.',- tip: 'Live on-chain swaps from the $THREE DEX pool, refreshed every few seconds.',- })}</div>+ <div data-empty>${TAPE_EMPTY_HTML()}</div></div></div></div>@@ -407,15 +478,20 @@ function boot() {`;document.body.appendChild(wrap);- // Copy CA- wrap.querySelector('[data-ca]').addEventListener('click', async (e) => {- try {- await navigator.clipboard.writeText(THREE_MINT);- const b = e.currentTarget;- const prev = b.textContent;- b.textContent = 'Copied ✓';- setTimeout(() => { b.textContent = prev; }, 1400);- } catch {}+ // Copy CA. The async clipboard is unavailable outside a secure context and+ // can be denied by permission policy, so fall back to a selection copy and,+ // failing that, tell the reader instead of silently doing nothing.+ const caBtn = wrap.querySelector('[data-ca]');+ const caLabel = caBtn.textContent;+ let caTimer = null;+ const flashCa = (text) => {+ caBtn.textContent = text;+ clearTimeout(caTimer);+ caTimer = setTimeout(() => { caBtn.textContent = caLabel; }, 1600);+ };+ caBtn.addEventListener('click', async () => {+ if (await copyText(THREE_MINT)) flashCa('Copied ✓');+ else flashCa('Copy failed');});// Buy — funnel step 2: buy intent.@@ -443,7 +519,16 @@ function boot() {statsEl.innerHTML = renderHeaderStats(p.token);paintVerifiedBadge(verifiedEl, p.token);}- else if (p.status === 'error') statsEl.innerHTML = `<div class="tk-empty" style="grid-column:1/-1">Couldn’t load $THREE market data. <a href="${PUMP_URL}" target="_blank" rel="noopener" style="color:#7CC4FF">View on pump.fun ↗</a></div>`;+ else if (p.status === 'error') {+ statsEl.innerHTML = `<div class="tk-stats-err">${errorStateHTML({+ title: 'Live market data is unavailable',+ body: 'The $THREE price feed didn’t respond. The market is unaffected: price, cap and volume are still live on pump.fun.',+ actions: [+ { label: 'Retry', id: 'stats-retry', primary: true },+ { label: 'View on pump.fun ↗', id: 'stats-pump' },+ ],+ })}</div>`;+ }});// Live trade tape.@@ -453,13 +538,31 @@ function boot() {// both from one protocol stats fetch.const bbEl = wrap.querySelector('[data-buyback]');const whyEl = wrap.querySelector('[data-why]');- fetch('/api/three-token/stats', { headers: { accept: 'application/json' } })- .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`stats ${r.status}`))))- .then((d) => {- bbEl.innerHTML = renderBuyback(d.buyback);- if (d.buyback?.commit_pct != null) whyEl.innerHTML = renderWhyHold(d.buyback.commit_pct);- })- .catch(() => { bbEl.innerHTML = renderBuyback(null); });+ const loadBuyback = () => {+ bbEl.innerHTML = '<div class="tk-skel" style="height:96px"></div>';+ return fetch('/api/three-token/stats', { headers: { accept: 'application/json' } })+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`stats ${r.status}`))))+ .then((d) => {+ bbEl.innerHTML = renderBuyback(d.buyback);+ if (d.buyback?.commit_pct != null) whyEl.innerHTML = renderWhyHold(d.buyback.commit_pct);+ })+ .catch(() => { bbEl.innerHTML = renderBuyback(null); });+ };+ bbEl.addEventListener('click', (e) => {+ const act = e.target.closest('[data-sk-action]')?.dataset.skAction;+ if (act === 'bb-retry') loadBuyback();+ else if (act === 'bb-solscan') window.open(`https://solscan.io/token/${THREE_MINT}`, '_blank', 'noopener');+ });+ loadBuyback();++ // Header stats recover through the same store the header reads from.+ statsEl.addEventListener('click', (e) => {+ const act = e.target.closest('[data-sk-action]')?.dataset.skAction;+ if (act === 'stats-retry') {+ statsEl.innerHTML = Array.from({ length: 4 }, () => '<div class="tk-stat"><div class="tk-skel" style="height:48px"></div></div>').join('');+ store.refresh();+ } else if (act === 'stats-pump') window.open(PUMP_URL, '_blank', 'noopener');+ });}if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);diff --git a/src/widgets/bonding-curve.js b/src/widgets/bonding-curve.jsindex a2b13d470..0d87c7567 100644--- a/src/widgets/bonding-curve.js+++ b/src/widgets/bonding-curve.js@@ -26,6 +26,7 @@import { hasThreeWsMark } from '../solana/vanity/brand.js';import { solToUsd } from '../shared/usd-price.js';+const UNKNOWN_VALUE = '\u2014'; // the card's placeholder for a value it cannot readconst LAMPORTS_PER_SOL = 1_000_000_000;const SOL_MINT = 'So11111111111111111111111111111111111111112';@@ -300,7 +301,9 @@ export function renderCardShell(view, cfg = {}) {? 'Graduated': view.status === 'bonding'? 'Bonding'- : 'No curve';+ : view.status === 'loading'+ ? 'Loading'+ : 'No curve';return `<div class="bcw-card ${statusClass}"><header class="bcw-head">@@ -356,7 +359,11 @@ const STYLES = `}.bcw-card {pointer-events: auto;+ /* 92vw keeps the floating/overlay mount off the viewport edges; max-width+ keeps an embedded mount inside its container, which at 320px is far+ narrower than 92vw once page and card padding are taken out. */width: min(420px, 92vw);+ max-width: 100%;box-sizing: border-box;padding: 18px 18px 16px;border-radius: 18px;@@ -452,6 +459,15 @@ const STYLES = `.bcw-by:hover { color: rgba(255, 255, 255, 0.6); }.bcw-empty-msg { margin: 2px 0 14px; font-size: 0.82rem; color: rgba(255, 255, 255, 0.5); }+.bcw-retry {+ appearance: none; margin-left: 6px; padding: 3px 10px; border-radius: 7px;+ border: 1px solid rgba(255, 255, 255, 0.18); background: rgba(255, 255, 255, 0.06);+ color: #f2f3f7; font: inherit; font-size: 0.78rem; font-weight: 600; cursor: pointer;+ transition: background 0.15s, border-color 0.15s;+}+.bcw-retry:hover { background: rgba(255, 255, 255, 0.12); border-color: rgba(255, 255, 255, 0.3); }+.bcw-retry:active { transform: translateY(1px); }+.bcw-retry:focus-visible { outline: 2px solid var(--bcw-accent); outline-offset: 2px; }.bcw-card.is-loading .bcw-pct-num,.bcw-card.is-loading .bcw-stats dd { color: transparent; background: rgba(255,255,255,0.08); border-radius: 6px; animation: bcw-shimmer 1.2s ease-in-out infinite; }@keyframes bcw-shimmer { 0%,100% { opacity: 0.5; } 50% { opacity: 1; } }@@ -523,6 +539,8 @@ export function mountBondingCurve(rootEl, opts = {}) {let timer = null;let raf = null;let displayedProgress = 0; // currently-rendered marker/percent position+ let everLoaded = false; // a poll has resolved at least once (good frame on screen)+ let failStreak = 0; // consecutive failed polls since the last good framelet view = { status: pollable ? 'loading' : 'empty', progress: 0 };// Initial paint — shell + empty/loading state.@@ -587,6 +605,41 @@ export function mountBondingCurve(rootEl, opts = {}) {raf = requestAnimationFrame(step);}+ // A first load that never lands leaves the shell shimmering under a "Loading"+ // badge forever, which reads as a slow network long after the fetch gave up.+ // Once two attempts have failed with no good frame yet, say so and offer the+ // retry. Later failures keep the last good frame instead (a blip, not an outage).+ function applyLoadError() {+ card.classList.remove('is-loading', 'is-bonding', 'is-grad');+ card.classList.add('is-empty');+ setTextSafe(els.status, 'Offline');+ if (els.pctNum) els.pctNum.textContent = UNKNOWN_VALUE;+ if (!els.meter || wrap.querySelector('[data-bcw-retry]')) return;+ const p = doc.createElement('p');+ p.className = 'bcw-empty-msg';+ p.setAttribute('role', 'alert');+ p.textContent = 'Couldn’t reach the bonding-curve feed. ';+ const btn = doc.createElement('button');+ btn.type = 'button';+ btn.className = 'bcw-retry';+ btn.dataset.bcwRetry = '';+ btn.textContent = 'Retry';+ btn.addEventListener('click', () => {+ p.remove();+ failStreak = 0;+ card.classList.add('is-loading');+ setTextSafe(els.status, 'Loading');+ poll();+ });+ p.appendChild(btn);+ els.meter.insertAdjacentElement('afterend', p);+ }++ function clearLoadError() {+ const btn = wrap.querySelector('[data-bcw-retry]');+ if (btn) btn.parentElement.remove();+ }+async function poll() {if (destroyed || stopped || !pollable) return;try {@@ -596,6 +649,9 @@ export function mountBondingCurve(rootEl, opts = {}) {]);if (destroyed) return;if (resp.status === 404) {+ everLoaded = true;+ failStreak = 0;+ clearLoadError();// A 404 is terminal: this mint has no bonding curve (graduated or// not a pump.fun token) and never will. Stop the interval instead// of re-polling forever — an interval against a curve-less mint is@@ -612,6 +668,9 @@ export function mountBondingCurve(rootEl, opts = {}) {if (!resp.ok) throw new Error(`HTTP ${resp.status}`);const data = await resp.json();if (destroyed) return;+ everLoaded = true;+ failStreak = 0;+ clearLoadError();view = computeView(data, solUsd);if (view.status === 'empty') {applyEmptyState(card, els);@@ -619,7 +678,10 @@ export function mountBondingCurve(rootEl, opts = {}) {renderValues(view);}} catch {- // Network blip — keep last good frame, retry on next tick.+ // Network blip: keep the last good frame and retry on the next tick.+ // With no good frame yet, surface the failure instead of shimmering on.+ failStreak += 1;+ if (!everLoaded && failStreak >= 2) applyLoadError();}}diff --git a/tests/market-category-lkg.test.js b/tests/market-category-lkg.test.jsindex 9375714c1..137e68fa4 100644--- a/tests/market-category-lkg.test.js+++ b/tests/market-category-lkg.test.js@@ -93,9 +93,9 @@ describe('fetchMarketsTable: upstream failure', () => {it('still throws for a category with no cached rows (cold cache stays honest)', async () => {fetchFirstMock.mockRejectedValue(new Error('markets-table: all providers failed'));- await expect(fetchMarketsTable({ page: 1, perPage: 100, category: 'brand-new' })).rejects.toThrow(- /all providers failed/,- );+ await expect(+ fetchMarketsTable({ page: 1, perPage: 100, category: 'brand-new' }),+ ).rejects.toThrow(/all providers failed/);});it('still throws for the uncategorized table however warm the cache is', async () => {@@ -106,26 +106,70 @@ describe('fetchMarketsTable: upstream failure', () => {);});- it('does not serve one category\'s rows for another', async () => {+ it("does not serve one category's rows for another", async () => {fetchFirstMock.mockResolvedValueOnce({ value: ROWS, source: 'coingecko' });await fetchMarketsTable({ page: 1, perPage: 100, category: 'aave-tokens' });fetchFirstMock.mockRejectedValue(new Error('markets-table: all providers failed'));- await expect(fetchMarketsTable({ page: 1, perPage: 100, category: 'layer-1' })).rejects.toThrow(- /all providers failed/,- );+ await expect(+ fetchMarketsTable({ page: 1, perPage: 100, category: 'layer-1' }),+ ).rejects.toThrow(/all providers failed/);});it('surfaces the upstream error when the cached entry is empty or malformed', async () => {cacheStore.set('coin:markets:lkg:aave-tokens:p1:pp100', { rows: [], at: Date.now() });fetchFirstMock.mockRejectedValue(new Error('markets-table: all providers failed'));- await expect(fetchMarketsTable({ page: 1, perPage: 100, category: 'aave-tokens' })).rejects.toThrow(- /all providers failed/,- );+ await expect(+ fetchMarketsTable({ page: 1, perPage: 100, category: 'aave-tokens' }),+ ).rejects.toThrow(/all providers failed/);++ cacheStore.set('coin:markets:lkg:aave-tokens:p1:pp100', {+ rows: 'not-an-array',+ at: Date.now(),+ });+ await expect(+ fetchMarketsTable({ page: 1, perPage: 100, category: 'aave-tokens' }),+ ).rejects.toThrow(/all providers failed/);+ });+});- cacheStore.set('coin:markets:lkg:aave-tokens:p1:pp100', { rows: 'not-an-array', at: Date.now() });- await expect(fetchMarketsTable({ page: 1, perPage: 100, category: 'aave-tokens' })).rejects.toThrow(- /all providers failed/,- );+/**+ * Sparkline opt-out. /screener renders 250 rows and no 7d chart column, so it+ * asks the endpoint to leave the price series out: measured against live+ * CoinGecko that is a 219,911-byte response versus 69,754 for the same rows.+ * The flag only shapes the CoinGecko rung (the fallbacks never carry a series),+ * and the two shapes must not share a last-known-good cache entry, or a+ * sparkline-less replay would blank the /coins chart column.+ */+describe('fetchMarketsTable: sparkline opt-out', () => {+ const geckoUrl = () => fetchFirstMock.mock.calls.at(-1)[0][0].url;++ it('requests the 7d series by default', async () => {+ fetchFirstMock.mockResolvedValue({ value: ROWS, source: 'coingecko' });+ await fetchMarketsTable({ page: 1, perPage: 250, category: '' });+ expect(geckoUrl()).toContain('sparkline=true');+ });++ it('drops the 7d series when the caller renders no chart column', async () => {+ fetchFirstMock.mockResolvedValue({ value: ROWS, source: 'coingecko' });+ await fetchMarketsTable({ page: 1, perPage: 250, category: '', sparkline: false });+ expect(geckoUrl()).toContain('sparkline=false');+ expect(geckoUrl()).toContain('price_change_percentage=24h,7d');+ });++ it('keeps the two row shapes in separate last-known-good entries', async () => {+ fetchFirstMock.mockResolvedValue({ value: ROWS, source: 'coingecko' });+ await fetchMarketsTable({ page: 1, perPage: 100, category: 'aave-tokens' });+ await fetchMarketsTable({+ page: 1,+ perPage: 100,+ category: 'aave-tokens',+ sparkline: false,+ });++ expect([...cacheStore.keys()].sort()).toEqual([+ 'coin:markets:lkg:aave-tokens:p1:pp100',+ 'coin:markets:lkg:aave-tokens:p1:pp100:nospark',+ ]);});});diff --git a/tests/market-fallbacks.test.js b/tests/market-fallbacks.test.jsindex b597642b1..37c2b0ee2 100644--- a/tests/market-fallbacks.test.js+++ b/tests/market-fallbacks.test.js@@ -128,10 +128,35 @@ describe('markets table row normalizer', () => {expect(row.price).toBeNull();expect(row.sparkline).toEqual([]);});++ // Number(null) is 0, so an absent field used to arrive as a confident zero:+ // CoinGecko reports market_cap_rank: null for coins it has not ranked, and+ // that became rank 0, which sorted the coin above Bitcoin at the top of the+ // /coins and /screener tables (observed live 2026-09-03 on+ // tradable-singapore-fintech-ssl-2). Absent stays absent.+ it('keeps an unreported number null instead of coercing it to zero', () => {+ const row = normalizeGeckoRow({+ id: 'tradable-singapore-fintech-ssl-2',+ symbol: 'pc0000023',+ name: 'Tradable Singapore Fintech SSL',+ market_cap_rank: null,+ current_price: 1,+ market_cap: 114_500_000,+ total_volume: null,+ price_change_percentage_24h_in_currency: null,+ price_change_percentage_7d_in_currency: undefined,+ });+ expect(row.rank).toBeNull();+ expect(row.volume_24h).toBeNull();+ expect(row.change_24h).toBeNull();+ expect(row.change_7d).toBeNull();+ // A genuine zero is still a zero.+ expect(normalizeGeckoRow({ id: 'z', total_volume: 0 }).volume_24h).toBe(0);+ });});describe('exchange spot ticker parsers', () => {- it('Kraken ticker → last trade price under Kraken\'s internal pair alias', () => {+ it("Kraken ticker → last trade price under Kraken's internal pair alias", () => {// Querying XBTUSD comes back keyed XXBTZUSD; the parser must not depend// on knowing the alias.const raw = { error: [], result: { XXBTZUSD: { a: ['64000.1'], c: ['63980.5', '0.01'] } } };@@ -139,7 +164,9 @@ describe('exchange spot ticker parsers', () => {});it('Coinbase spot → data.amount', () => {- expect(parseCoinbaseSpot({ data: { base: 'BTC', currency: 'USD', amount: '64010.55' } })).toBeCloseTo(64010.55);+ expect(+ parseCoinbaseSpot({ data: { base: 'BTC', currency: 'USD', amount: '64010.55' } }),+ ).toBeCloseTo(64010.55);});it('Bitfinex ticker array → LAST_PRICE at index 6', () => {@@ -156,7 +183,11 @@ describe('exchange spot ticker parsers', () => {it('maps exactly the headline assets, all three exchanges each', () => {for (const id of ['bitcoin', 'ethereum', 'solana']) {- expect(Object.keys(EXCHANGE_PAIRS[id]).sort()).toEqual(['bitfinex', 'coinbase', 'kraken']);+ expect(Object.keys(EXCHANGE_PAIRS[id]).sort()).toEqual([+ 'bitfinex',+ 'coinbase',+ 'kraken',+ ]);}});});@@ -195,6 +226,8 @@ describe('exchange candle chart normalizers', () => {expect(normalizeKrakenChart({ result: {} }, 1, now)).toBeNull();expect(normalizeKrakenChart(null, 1, now)).toBeNull();expect(normalizeCoinbaseChart({ message: 'NotFound' }, 1, now)).toBeNull();- expect(normalizeCoinbaseChart([[(now - 100 * hour) / 1000, 1, 2, 1, 2, 3]], 1, now)).toBeNull();+ expect(+ normalizeCoinbaseChart([[(now - 100 * hour) / 1000, 1, 2, 1, 2, 3]], 1, now),+ ).toBeNull();});});diff --git a/tests/market-table.test.js b/tests/market-table.test.jsnew file mode 100644index 000000000..8fcb74b32--- /dev/null+++ b/tests/market-table.test.js@@ -0,0 +1,92 @@+/**+ * Shared market-table primitives (src/shared/market-table.js), rendered by both+ * /coins and /screener. The two pages used to carry their own copies of this+ * markup and sorting, which is how they drifted apart on aria-sort; the tests+ * here pin the contract they now share.+ */++import { describe, it, expect } from 'vitest';+import {+ coinRow,+ COIN_COLUMNS,+ coinSortValue,+ sortableHeaderCells,+} from '../src/shared/market-table.js';++const ROW = {+ id: 'bitcoin',+ symbol: 'BTC',+ name: 'Bitcoin',+ image: 'https://img/btc.png',+ rank: 1,+ price: 64_000,+ change_24h: 0.58,+ change_7d: 1.71,+ market_cap: 1_290_000_000_000,+ volume_24h: 12_700_000_000,+ sparkline: [1, 2, 3],+};++const cells = (html) => (html.match(/<td/g) || []).length;++describe('coinRow', () => {+ it('renders the 7d chart cell by default', () => {+ const html = coinRow(ROW);+ expect(cells(html)).toBe(COIN_COLUMNS.length + 1);+ expect(html).toContain('<svg');+ });++ // A body row with one more cell than the header row shifts every column+ // under the wrong label, so the /screener table (no chart column) opts out.+ it('omits the chart cell so a 7-column header keeps 7 cells per row', () => {+ const html = coinRow(ROW, { sparkline: false });+ expect(cells(html)).toBe(COIN_COLUMNS.length);+ expect(html).not.toContain('<svg');+ });++ it('escapes remote strings and links to the coin detail page', () => {+ const html = coinRow({ ...ROW, id: 'a b', name: '<img onerror=x>' }, { sparkline: false });+ expect(html).toContain('/coin/a%20b');+ expect(html).not.toContain('<img onerror');+ expect(html).toContain('<img onerror=x>');+ });+});++describe('sortableHeaderCells', () => {+ it('marks the active column and gives every other column aria-sort="none"', () => {+ const html = sortableHeaderCells(COIN_COLUMNS, 'market_cap', 'desc');+ expect(html).toContain('data-key="market_cap" aria-sort="descending"');+ expect((html.match(/aria-sort="none"/g) || []).length).toBe(COIN_COLUMNS.length - 1);+ expect((html.match(/tabindex="0"/g) || []).length).toBe(COIN_COLUMNS.length);+ });++ it('flips the arrow with the direction', () => {+ expect(sortableHeaderCells(COIN_COLUMNS, 'rank', 'asc')).toContain('ascending');+ expect(sortableHeaderCells(COIN_COLUMNS, 'rank', 'desc')).toContain('descending');+ });+});++describe('coinSortValue', () => {+ const byRank = (rows) =>+ [...rows].sort((a, b) => coinSortValue(a, 'rank') - coinSortValue(b, 'rank'));++ it('sorts unranked coins last without producing a NaN comparison', () => {+ expect(coinSortValue({ rank: null }, 'rank') - coinSortValue({ rank: null }, 'rank')).toBe(+ 0,+ );+ const order = byRank([+ { id: 'unranked-a', rank: null },+ { id: 'btc', rank: 1 },+ { id: 'unranked-b', rank: null },+ { id: 'eth', rank: 2 },+ ]).map((c) => c.id);+ expect(order.slice(0, 2)).toEqual(['btc', 'eth']);+ expect(order.slice(2).sort()).toEqual(['unranked-a', 'unranked-b']);+ });++ it('sorts names case-insensitively and treats a missing number as zero', () => {+ expect(coinSortValue({ name: 'Bitcoin' }, 'name')).toBe('bitcoin');+ expect(coinSortValue({}, 'market_cap')).toBe(0);+ expect(coinSortValue({ market_cap: 5 }, 'market_cap')).toBe(5);+ });+});