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(yields): add DeFi yield-pool explorer with filtering, sorting, and charting capabilities
fudjia22302443585b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b417572c3..a045014c2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,11 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-07-11++- **DeFi Yields Explorer** (`/yields`) — Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.+- **Richer coin pages, plus new exchange, category, and DeFi-yields detail pages** — Every coin page now shows far more of what the data already offers: a 1h-to-1y price-performance matrix, a circulating-vs-max supply bar with the market-cap/FDV ratio, all-time high and low with the drawdown and recovery multiple, the community bullish/bearish sentiment split, GitHub and social activity, and a full exchange-listings table with spread, order-book depth, and a trust rating for each venue. Exchanges and crypto categories, which used to only send you off-site or filter a table, now have their own detail pages — an exchange page with a trust badge, wash-volume-adjusted volume, a volume-history chart, and its markets, and a category page with the sector's rank, stats, and full coin list. And a brand-new DeFi Yields explorer covers roughly 15,000 live pools across every chain and protocol, filterable and sortable, each with its own APY and TVL history chart. All of it is real, key-free data. (`/yields`) `[feature, improvement]`+## 2026-07-10- **Crypto News** (`/markets/news`) — Live crypto news aggregated natively from 192 publisher feeds in 18 languages — filter by category (Bitcoin, DeFi, security, regulation, and more), pick a language, search headlines, and open any story in a rich reader with summary, key points, sentiment, and related coverage.diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 1ad7d3949..827c29a94 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -77,9 +77,10 @@ bottom.| Autonomous trading experiment | policy [scripts/trading-experiment-setup.mjs](scripts/trading-experiment-setup.mjs), laddered exit [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`decideLadderedExit`), no-Mayhem gate [workers/agent-sniper/mayhem-gate.js](workers/agent-sniper/mayhem-gate.js), journal [workers/agent-sniper/journal.js](workers/agent-sniper/journal.js) → [api/sniper/journal.js](api/sniper/journal.js) | In-repo | One agent, ~10 SOL, newer pump.fun launches ($10k–$100k mcap, no Mayhem). Take-initials-at-2× laddered exit keeps a moon bag (never a 100% exit up), hard stop-loss underneath. Every decision journaled with its reasoning. UI-funded, simulate-first. See [docs/trading-experiment.md](docs/trading-experiment.md) || Trading Copilot (conversational) | client [src/agent-copilot.js](src/agent-copilot.js), hub tab [src/agent-wallet-hub/tabs/copilot.js](src/agent-wallet-hub/tabs/copilot.js), server [api/agents/copilot.js](api/agents/copilot.js) `→ POST /api/agents/:id/copilot` (SSE) | In-repo | Owner-only chat over an agent's Solana wallet: text/voice in, markdown replies, live **data cards** (portfolio, firewall, quote, smart-money, intel) and **confirm-before-execute** trade/limits cards. Read-only tools run server-side; state-changing intents return as proposals the browser re-quotes and runs through the existing spend guards + firewall + custody audit. Slash commands, copy/regenerate, localStorage persistence. See [docs/trading-copilot.md](docs/trading-copilot.md) || Real-funds risk acknowledgment | gate [public/risk-ack.js](public/risk-ack.js) `→ /legal/risk`, app wrapper [src/shared/risk-ack.js](src/shared/risk-ack.js), record endpoint [api/legal/risk-ack.js](api/legal/risk-ack.js), disclosure [public/legal/risk.html](public/legal/risk.html) | In-repo | Versioned, once-per-browser acceptance dialog every money-committing surface awaits before executing (trade, snipe, withdraw, swap, launch, x402, onramp — devnet exempt). Acceptances persist in `audit_log` (`risk-ack-accept`). See [docs/risk-acknowledgment.md](docs/risk-acknowledgment.md) |-| Global markets + coin detail pages | [pages/coins.html](pages/coins.html) + [src/coins-index.js](src/coins-index.js) `→ /coins`, [pages/coin.html](pages/coin.html) + [src/coin-page.js](src/coin-page.js) `→ /coin/:id`, backend [api/coin/](api/coin) (detail, ohlc, markets, news, global over [api/_lib/coingecko.js](api/_lib/coingecko.js)) | In-repo | CoinGecko-style markets index (global stats bar, sortable top-coins table, search, sparklines) + a rich detail page per coin (interactive chart, stats grid, related news, links). Design adopted from cryptocurrency.cv; accepts CoinGecko slugs or Solana mints. Docs: [docs/coin-pages.md](docs/coin-pages.md) |+| Global markets + coin detail pages | [pages/coins.html](pages/coins.html) + [src/coins-index.js](src/coins-index.js) `→ /coins`, [pages/coin.html](pages/coin.html) + [src/coin-page.js](src/coin-page.js) `→ /coin/:id`, backend [api/coin/](api/coin) (detail, tickers, ohlc, markets, news, global over [api/_lib/coingecko.js](api/_lib/coingecko.js)) | In-repo | CoinGecko-style markets index (global stats bar, sortable top-coins table, search, sparklines) + a rich detail page per coin: interactive chart, 1h→1y price-performance matrix, market-stats grid, circulating/max supply bar with Mcap/FDV ratio, ATH/ATL with drawdown & recovery multiple, community sentiment vote split, community + developer (GitHub) activity grids, a paginated exchange-listings table (`api/coin/tickers`, ±2% depth + trust) linking into exchange detail, related news, and full link pills (site/social/whitepaper/forum/chat/explorers). Design adopted from cryptocurrency.cv; accepts CoinGecko slugs or Solana mints. Docs: [docs/coin-pages.md](docs/coin-pages.md) || Market tools (heatmap, sentiment, gas, compare) | [pages/heatmap.html](pages/heatmap.html) + [src/heatmap.js](src/heatmap.js) `→ /heatmap`, [pages/fear-greed.html](pages/fear-greed.html) + [src/fear-greed.js](src/fear-greed.js) `→ /fear-greed`, [pages/gas.html](pages/gas.html) + [src/gas.js](src/gas.js) `→ /gas`, [pages/compare.html](pages/compare.html) + [src/compare.js](src/compare.js) `→ /compare`; backend [api/coin/fear-greed.js](api/coin/fear-greed.js), [api/coin/gas.js](api/coin/gas.js) | In-repo | Four tools extending Markets, same design system: treemap heatmap (market-cap-sized tiles), Fear & Greed gauge + history, live Ethereum gas tracker (keyless `eth_feeHistory`), and up-to-4-coin compare (overlay perf + stats). All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) || Market tools II (screener, categories, exchanges, derivatives, converter, DeFi, chains, stablecoins) | Pages+JS `→ /screener /categories /exchanges /derivatives /converter /defi /chains /stablecoins`; backend [api/coin/](api/coin) (categories, exchanges, derivatives, rates) over CoinGecko + [api/defi/](api/defi) (protocols, chains, stablecoins) over DeFiLlama | In-repo | Eight more Markets tools, same design system: token screener + category rankings + exchange/derivatives tables + crypto⇄fiat converter (CoinGecko), plus a DeFiLlama trio — DeFi TVL by protocol, chains by TVL, stablecoins with peg health. All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |+| Market detail pages (exchange, category) + DeFi yields | [pages/exchange.html](pages/exchange.html) + [src/exchange-page.js](src/exchange-page.js) `→ /exchange/:id` over [api/coin/exchange.js](api/coin/exchange.js), [pages/category.html](pages/category.html) + [src/category-page.js](src/category-page.js) `→ /category/:id` over [api/coin/category.js](api/coin/category.js) + [api/coin/markets.js](api/coin/markets.js) (`?category=`), [pages/yields.html](pages/yields.html) + [src/yields.js](src/yields.js) `→ /yields` over [api/defi/yields.js](api/defi/yields.js) | In-repo | Rich detail pages that turn list rows into full profiles. Exchange: trust badge, normalized-volume stat, BTC-volume history chart, and a per-pair markets table (spot + derivatives fallback), reached from `/exchanges` and the new Derivatives Exchanges table. Category: rank, sector stats, the full sortable coins table for that sector, and related categories, reached from `/categories`. Yields: an explorer over ~15k live DeFiLlama pools with chain/project/stablecoin/min-TVL filters, APY/TVL sort, URL-synced state, and a per-pool APY+TVL history chart on row expand. Docs: [docs/coin-pages.md](docs/coin-pages.md) || Crypto news + archive + markets hub | [pages/markets.html](pages/markets.html) + [src/markets-page.js](src/markets-page.js) `→ /markets`, [pages/markets-news.html](pages/markets-news.html) + [src/markets-news.js](src/markets-news.js) `→ /markets/news`, [pages/news-article.html](pages/news-article.html) + [src/news-article.js](src/news-article.js) `→ /markets/news/article`, [pages/news-archive.html](pages/news-archive.html) + [src/news-archive.js](src/news-archive.js) `→ /markets/archive`, [pages/news-digest.html](pages/news-digest.html) + [src/news-digest.js](src/news-digest.js) `→ /markets/digest`; backend [api/news/](api/news) (feed, article, archive, digest, rss) + hourly archiver [api/cron/news-archive-append.js](api/cron/news-archive-append.js) over [api/_lib/news.js](api/_lib/news.js) + [api/_lib/news-sources.js](api/_lib/news-sources.js), corpus on `gs://three-ws-news-archive` | In-repo | The Markets news wing + front door: live news aggregated natively from 192 publisher feeds (category tabs, search, sentiment, ticker chips), a rich article reader (server-side extraction, AI summary/key points with extractive fallback, related coverage), the largest open crypto-news archive (662,047 enriched articles, Sept 2017 → today, EN+中文, GCS-hosted), and the /markets hub aggregating global stats, the top-100 table, breaking news, and every market surface as a hero card. Docs: [docs/coin-pages.md](docs/coin-pages.md), [docs/api-reference.md](docs/api-reference.md) || Liquidations pulse (/coins) | Collector [services/liquidation-collector/](services/liquidation-collector) (standalone always-on Node service, ported from SperaxOS), proxy [api/coin/liquidations.js](api/coin/liquidations.js) `→ GET /api/coin/liquidations`, UI strip in [src/coins-index.js](src/coins-index.js) `→ /coins` | Live — collector on Cloud Run (`liquidation-collector`, min-instances 1, unthrottled CPU) since 2026-07-10 | Real-time long/short liquidation pain across Binance, Bybit, and OKX public futures WebSocket streams: dominant-side badge (LONG PAIN / SHORT SQUEEZE / BALANCED), 1h long-vs-short bars, and the 3 largest recent liquidations, polled every 30s (pauses on hidden tab). The collector holds long-lived WebSockets so it can't run as a Vercel function — deploy it separately and point `LIQUIDATION_COLLECTOR_URL` at it. No fallback data: the proxy 503s `collector_offline` (never fabricated numbers) when unset or unreachable, and the strip degrades to a quiet single-line offline state. Docs: [docs/api-reference.md#liquidations](docs/api-reference.md#liquidations) || BNB Chain campaign hub | [pages/bnb.html](pages/bnb.html) + [src/bnb.js](src/bnb.js) `→ /bnb`, pure helpers [src/bnb-hub-helpers.js](src/bnb-hub-helpers.js), live block-time API [api/bnb/block-time.js](api/bnb/block-time.js) over [api/_lib/bnb/chains.js](api/_lib/bnb/chains.js) `probeBlockTime` | In-repo · hub live, tracks rolling out | The campaign's front door: three feature cards (gasless agent onboarding, on-chain-gated 3D vault, real-time on-chain world), each claim traced to `prompts/bnb-chain/00-CONTEXT.md`'s verified facts (0.45s blocks — never 20k TPS or 250ms finality). Embeds a live block-time widget (real RPC measurement on every load). Each card self-detects liveness via a real HTTP probe against its track's route/API on the running deployment — a 404 renders a designed "coming soon" state, never a dead link — so cards auto-light-up as the sibling tracks below ship: gasless registration `→ /create-agent` + `api/bnb/register-agent.js` (prompt 03), vault `→ /vault` (prompt 12), on-chain world `→ /bnb-latency` (prompt 17) + the Explore on-chain toggle (prompt 16). Campaign root: [prompts/bnb-chain/](prompts/bnb-chain) |diff --git a/api/_lib/fetch-model.js b/api/_lib/fetch-model.jsindex 0a010cacb..84b4c0d1c 100644--- a/api/_lib/fetch-model.js+++ b/api/_lib/fetch-model.js@@ -41,7 +41,10 @@ function validateUrl(rawUrl) {* Fetch bytes from an untrusted URL with SSRF protection.** @param {string} rawUrl- * @param {{ maxBytes?: number, timeoutMs?: number }} opts+ * @param {{ maxBytes?: number, timeoutMs?: number, headers?: object }} opts+ * opts.headers merges over the defaults — callers fetching non-model content+ * (the news og:image resolver pulls publisher HTML) present their own+ * user-agent/accept instead of the model ones.* @returns {Promise<{ bytes: Uint8Array, url: string, contentType: string, filename: string }>}*/export async function fetchModel(rawUrl, opts = {}) {@@ -71,6 +74,7 @@ export async function fetchModel(rawUrl, opts = {}) {headers: {'user-agent': '3d-agent-mcp/1.0 (+https://three.ws/)',accept: 'model/gltf-binary, model/gltf+json, application/octet-stream, */*;q=0.5',+ ...(opts.headers || {}),},});diff --git a/api/_lib/news-archive-store.js b/api/_lib/news-archive-store.jsnew file mode 100644index 000000000..df1a4d7c9--- /dev/null+++ b/api/_lib/news-archive-store.js@@ -0,0 +1,119 @@+// GCS-backed access to the historical crypto-news archive+// (gs://three-ws-news-archive) — extracted from api/news/archive.js so the+// story pages (api/news/story-page.js) and the news sitemap can read the same+// month files through the same LRU cache instead of re-implementing the store.+//+// Data layout (public bucket, gzip at rest, transparently decoded):+// articles/YYYY-MM.jsonl one enriched article per line+// meta/stats.json corpus-wide statistics+// indexes/by-{date,source,ticker}.json+//+// The imported corpus ends 2025-12-03; api/cron/news-archive-append.js extends+// it hourly from the live feed. Never hardcode the end date — read+// meta/stats.json (last_article_date), which the appender keeps current.++const GCS_BASE = 'https://storage.googleapis.com/three-ws-news-archive';+const GCS_LIST =+ 'https://storage.googleapis.com/storage/v1/b/three-ws-news-archive/o?prefix=articles/&fields=items(name)&maxResults=500';++const MONTH_CACHE_MAX = 5;+const META_TTL_MS = 3600_000;++// month "YYYY-MM" → compact article records (newest month files are ~2–11 MB+// raw; compact form keeps only serving fields). LRU by Map insertion order.+const monthCache = new Map();+// small metadata caches: { value, expiresAt }+let statsCache = null;+let monthsCache = null;++const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);++export function compact(a) {+ return {+ id: a.id,+ title: a.title,+ link: str(a.link) || str(a.canonical_link),+ description: str(a.description) ? a.description.slice(0, 240) : null,+ image: str(a.image),+ author: str(a.author),+ source: a.source || a.source_key || 'unknown',+ source_key: a.source_key || 'unknown',+ category: a.category || 'general',+ pub_date: a.pub_date || a.first_seen || null,+ tickers: Array.isArray(a.tickers) ? a.tickers.slice(0, 8) : [],+ tags: Array.isArray(a.tags) ? a.tags.slice(0, 6) : [],+ sentiment: a.sentiment ? { label: a.sentiment.label, score: a.sentiment.score } : null,+ lang: a.meta?.language || 'en',+ is_breaking: !!a.meta?.is_breaking,+ market_context: a.market_context+ ? {+ btc_price: a.market_context.btc_price ?? null,+ eth_price: a.market_context.eth_price ?? null,+ fear_greed_index: a.market_context.fear_greed_index ?? null,+ }+ : null,+ };+}++async function fetchJson(url, timeoutMs = 15_000) {+ const resp = await fetch(url, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!resp.ok) throw new Error(`archive upstream ${resp.status}`);+ return resp.json();+}++export async function getStats() {+ if (statsCache && statsCache.expiresAt > Date.now()) return statsCache.value;+ const value = await fetchJson(`${GCS_BASE}/meta/stats.json`);+ statsCache = { value, expiresAt: Date.now() + META_TTL_MS };+ return value;+}++/** Queryable months, ascending YYYY-MM. */+export async function getMonths() {+ if (monthsCache && monthsCache.expiresAt > Date.now()) return monthsCache.value;+ const listing = await fetchJson(GCS_LIST);+ const value = (listing.items || [])+ .map((o) => {+ const m = /^articles\/(\d{4}-\d{2})\.jsonl$/.exec(o.name);+ return m ? m[1] : null;+ })+ .filter(Boolean)+ .sort(); // ascending YYYY-MM+ if (!value.length) throw new Error('archive month listing is empty');+ monthsCache = { value, expiresAt: Date.now() + META_TTL_MS };+ return value;+}++/** One month of compact records, newest-first, LRU-cached. */+export async function loadMonth(month) {+ if (monthCache.has(month)) {+ const records = monthCache.get(month);+ monthCache.delete(month);+ monthCache.set(month, records); // refresh LRU recency+ return records;+ }+ const resp = await fetch(`${GCS_BASE}/articles/${month}.jsonl`, {+ signal: AbortSignal.timeout(30_000),+ });+ if (!resp.ok) throw new Error(`month ${month} → ${resp.status}`);+ const text = await resp.text();+ const records = [];+ for (const line of text.split('\n')) {+ if (!line.trim()) continue;+ try {+ records.push(compact(JSON.parse(line)));+ } catch {+ // skip the malformed line, keep the month+ }+ }+ // newest-first inside the month so early-stop pagination is stable+ records.sort((a, b) => new Date(b.pub_date || 0) - new Date(a.pub_date || 0));+ monthCache.set(month, records);+ while (monthCache.size > MONTH_CACHE_MAX) {+ monthCache.delete(monthCache.keys().next().value);+ }+ return records;+}diff --git a/api/_lib/news-sources.js b/api/_lib/news-sources.jsindex 8f1f34476..a0172244b 100644--- a/api/_lib/news-sources.js+++ b/api/_lib/news-sources.js@@ -356,3 +356,14 @@ export function sourcePriority(key) {// Untiered: English long-tail before international, which is niche by design.return NEWS_SOURCES[key]?.language ? 4 : 3;}++/**+ * The "Featured" bar: the majors and mainstream desks whose editorial standards+ * carry the front of the briefing — tier1/tier2 upstream, or a credibility score+ * at or above 0.85. Backs /api/news/feed?featured=1.+ */+export function isFeaturedSource(key) {+ const s = NEWS_SOURCES[key];+ if (!s) return false;+ return s.tier === 'tier1' || s.tier === 'tier2' || (s.credibility || 0) >= 0.85;+}diff --git a/api/_lib/news-story.js b/api/_lib/news-story.jsnew file mode 100644index 000000000..a2d33f09e--- /dev/null+++ b/api/_lib/news-story.js@@ -0,0 +1,45 @@+// Resolve one news article by its canonical (month, id16) address — the+// lookup behind the story pages (/markets/news/<YYYY-MM>/<id>) and their+// sitemap. Live-feed cache first for recent months (richer record: image,+// author, feed-provided full text), then the archive month file, which covers+// the full corpus back to September 2017 with a single GCS fetch.++import { findArticle } from './news.js';+import { loadMonth } from './news-archive-store.js';++const MONTH_RE = /^20\d{2}-(0[1-9]|1[0-2])$/;+const ID_RE = /^[a-f0-9]{16}$/;++export function validStoryKey(month, id) {+ return MONTH_RE.test(String(month || '')) && ID_RE.test(String(id || ''));+}++function recentMonths() {+ const now = new Date();+ const cur = now.toISOString().slice(0, 7);+ now.setUTCDate(1);+ now.setUTCMonth(now.getUTCMonth() - 1);+ return [cur, now.toISOString().slice(0, 7)];+}++/**+ * @returns {Promise<{article: object, origin: 'live'|'archive'} | null>}+ * The live record wins for recent months (it carries image/author and, for+ * some publishers, the feed's full body); everything older comes from the+ * archive month file. A live hit is cross-checked against the requested month+ * so a stale URL can't serve a different month's story.+ */+export async function resolveStory(month, id) {+ if (!validStoryKey(month, id)) return null;++ if (recentMonths().includes(month)) {+ const live = await findArticle({ id }).catch(() => null);+ if (live && (live.pub_date || '').slice(0, 7) === month) {+ return { article: live, origin: 'live' };+ }+ }++ const records = await loadMonth(month).catch(() => null);+ const archived = records?.find((a) => a.id === id) || null;+ return archived ? { article: archived, origin: 'archive' } : null;+}diff --git a/api/_lib/news.js b/api/_lib/news.jsindex c339fa763..7ab501022 100644--- a/api/_lib/news.js+++ b/api/_lib/news.js@@ -24,7 +24,7 @@import { createHash } from 'node:crypto';import { XMLParser } from 'fast-xml-parser';-import { NEWS_SOURCES, sourcesForCategory, sourcesForLanguage, sourcePriority } from './news-sources.js';+import { NEWS_SOURCES, sourcesForCategory, sourcesForLanguage, sourcePriority, isFeaturedSource } from './news-sources.js';const FEED_TIMEOUT_MS = 7000;const FRESH_MS = 300_000; // refetch a source after 5 min@@ -171,6 +171,48 @@ function firstImage(html) {return m ? m[1] : null;}+/**+ * Feeds ship junk in their image slots: data:-URI placeholders (ZeroHedge sends+ * an inline SVG icon as media:content), 1×1 tracking pixels, protocol-relative+ * links, and plain-http URLs that an https page can't render (mixed content is+ * blocked, not downgraded). Only a real, loadable https URL survives this —+ * anything else becomes null so the card falls back cleanly instead of showing+ * a broken or junk preview.+ */+export function cleanImageUrl(raw) {+ let url = str(raw);+ if (!url) return null;+ if (url.startsWith('//')) url = `https:${url}`;+ if (/^http:\/\//i.test(url)) url = `https://${url.slice(7)}`;+ if (!/^https:\/\//i.test(url)) return null; // data:, blob:, ftp:, relative paths+ if (/(?:^|[/_.-])(?:1x1|pixel|spacer|blank|transparent)(?:[/_.-]|\.(?:gif|png)\b)/i.test(url)) return null;+ if (/feeds\.feedburner\.com\/~/i.test(url)) return null; // FeedBurner impression beacons+ return url;+}++/** First <meta property|name="…" content="…"> match, attribute order agnostic. */+export function metaContent(html, patterns) {+ for (const name of patterns) {+ const re = new RegExp(+ `<meta[^>]+(?:property|name)=["']${name}["'][^>]+content=["']([^"']+)["']|<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["']${name}["']`,+ 'i',+ );+ const m = String(html || '').match(re);+ if (m) return (m[1] || m[2] || '').trim() || null;+ }+ return null;+}++/**+ * The article page's own preview image — what the publisher would show on a+ * social share. Backs /api/news/image for articles whose feed carries no image.+ */+export function extractOgImage(html) {+ return cleanImageUrl(+ metaContent(html, ['og:image:secure_url', 'og:image', 'twitter:image', 'twitter:image:src']),+ );+}+function normalizeLink(it) {// RSS: <link>url</link>. Atom: <link href="..."/> possibly an array with// rel variants — prefer rel="alternate", else the first href.@@ -201,12 +243,19 @@ export function parseFeed(xml, sourceKey) {str(it?.['content:encoded']) ||str(it?.content?.['#text']) ||'';+ // First candidate that survives hygiene wins — a junk media:content+ // (ZeroHedge ships a data:-URI icon there) must not mask a real+ // thumbnail further down the chain.const image =- str(it?.['media:content']?.['@url']) ||- (Array.isArray(it?.['media:content']) ? str(it['media:content'][0]?.['@url']) : null) ||- str(it?.['media:thumbnail']?.['@url']) ||- str(it?.enclosure?.['@url']) ||- firstImage(it?.['content:encoded'] || rawDesc);+ [+ str(it?.['media:content']?.['@url']),+ Array.isArray(it?.['media:content']) ? str(it['media:content'][0]?.['@url']) : null,+ str(it?.['media:thumbnail']?.['@url']),+ str(it?.enclosure?.['@url']),+ firstImage(it?.['content:encoded'] || rawDesc),+ ]+ .map(cleanImageUrl)+ .find(Boolean) || null;const pubDate = str(it?.pubDate) || str(it?.published) || str(it?.updated) || str(it?.['dc:date']);const iso = pubDate && !Number.isNaN(Date.parse(pubDate)) ? new Date(pubDate).toISOString() : null;const author =@@ -475,10 +524,13 @@ function dedupe(articles) {* Chinese headlines into an English feed. They are opt-in: pass a language code* for one, or 'all' for the whole registry.*- * @param {object} opts { category, source, lang, q, limit, offset }+ * `featured` narrows the fan-out to the majors (tier1/tier2 or credibility+ * ≥ 0.85) — the "Featured" tab on /markets/news.+ *+ * @param {object} opts { category, source, lang, q, limit, offset, featured }* @returns {{ articles: Array, total: number, sources_ok: number, sources_total: number }}*/-export async function getNews({ category, source, lang = 'en', q, limit = 30, offset = 0 } = {}) {+export async function getNews({ category, source, lang = 'en', q, limit = 30, offset = 0, featured = false } = {}) {let keys;if (source && NEWS_SOURCES[source]) keys = [source];else if (source) return { articles: [], total: 0, sources_ok: 0, sources_total: 0 };@@ -488,6 +540,7 @@ export async function getNews({ category, source, lang = 'en', q, limit = 30, ofconst inLang = new Set(sourcesForLanguage(lang));keys = keys.filter((k) => inLang.has(k));}+ if (featured) keys = keys.filter(isFeaturedSource);}// A narrow selection — one source, or a small language/category slice — hasdiff --git a/api/coin/category.js b/api/coin/category.jsnew file mode 100644index 000000000..913b6b08b--- /dev/null+++ b/api/coin/category.js@@ -0,0 +1,109 @@+// GET /api/coin/category?id=<category-slug>+// ---------------------------------------------------------------------------+// Rich profile for one crypto sector — powers the /category/:id detail page.+// One cached fetch of CoinGecko /coins/categories?order=market_cap_desc serves+// every category: the entry is found by id, its ordinal in the mcap-ordered+// list becomes the rank, and the 8 nearest neighbours by rank become the+// related-categories strip. `share_of_total` is this category's market cap as+// a percentage of the SUM of all category market caps — categories overlap (a+// coin sits in many), so it is a share of the categorized market, not of total+// crypto market cap. The description comes from the upstream `content` field,+// stripped to plain text server-side like api/coin/detail.js.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { geckoFetch, htmlToText } from '../_lib/coingecko.js';++const CATEGORY_ID_RE = /^[a-z0-9-]{1,80}$/;++const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);++// The 8 rank-nearest categories around `index`, excluding the category itself.+// A window of 9 slots centred on the entry, clamped to the list edges, always+// yields 8 neighbours whenever the list has at least 9 categories.+function relatedByRank(ranked, index, want = 8) {+ const start = Math.max(0, Math.min(index - Math.floor(want / 2), ranked.length - (want + 1)));+ const out = [];+ for (let i = start; i < ranked.length && out.length < want; i++) {+ if (i === index) continue;+ const c = ranked[i];+ out.push({+ id: c.id,+ name: c.name || c.id,+ market_cap: num(c.market_cap),+ market_cap_change_24h: num(c.market_cap_change_24h),+ });+ }+ return out;+}++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.marketDataIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const id = (params.get('id') || '').trim().toLowerCase();+ if (!CATEGORY_ID_RE.test(id)) {+ return error(+ res,+ 400,+ 'bad_id',+ 'id must be a CoinGecko category slug (lowercase letters, digits, hyphens)',+ );+ }++ let raw;+ try {+ raw = await geckoFetch('/coins/categories?order=market_cap_desc', {+ ttlMs: 600_000,+ timeoutMs: 10_000,+ });+ if (!Array.isArray(raw)) throw new Error('unexpected upstream payload');+ } catch {+ return error(+ res,+ 502,+ 'upstream_error',+ 'category data is unavailable right now — retry shortly',+ );+ }++ const ranked = raw.filter((c) => c && typeof c.id === 'string');+ const index = ranked.findIndex((c) => c.id === id);+ if (index < 0) return error(res, 404, 'not_found', `no category found for "${id}"`);++ const c = ranked[index];+ const marketCap = num(c.market_cap);+ let categorizedTotal = 0;+ for (const r of ranked) {+ const mc = num(r.market_cap);+ if (mc != null) categorizedTotal += mc;+ }++ return json(+ res,+ 200,+ {+ category: {+ id: c.id,+ name: c.name || c.id,+ description: htmlToText(c.content || '').slice(0, 2000) || null,+ market_cap: marketCap,+ market_cap_change_24h: num(c.market_cap_change_24h),+ volume_24h: num(c.volume_24h),+ top_3_coins: Array.isArray(c.top_3_coins)+ ? c.top_3_coins.filter((u) => typeof u === 'string' && u).slice(0, 3)+ : [],+ rank: index + 1,+ share_of_total: marketCap != null && categorizedTotal > 0 ? (marketCap / categorizedTotal) * 100 : null,+ },+ related: relatedByRank(ranked, index),+ },+ {+ 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1800',+ },+ );+});diff --git a/api/coin/derivatives.js b/api/coin/derivatives.jsindex 9ee8af090..0ce097f8e 100644--- a/api/coin/derivatives.js+++ b/api/coin/derivatives.js@@ -1,4 +1,4 @@-// GET /api/coin/derivatives+// GET /api/coin/derivatives[?view=exchanges]// ---------------------------------------------------------------------------// Perpetual futures markets for the /derivatives page. Proxies CoinGecko// `/derivatives?include_tickers=unexpired`, keeps only perpetual contracts,@@ -6,13 +6,20 @@// and returns them sorted by 24h volume, capped at 100. Non-finite numbers// become null so the client renders an em dash instead of NaN. Cached 60s// in-memory + CDN.+//+// `?view=exchanges` returns the derivatives venues instead — CoinGecko+// `/derivatives/exchanges` ranked by open interest — feeding the Derivatives+// Exchanges section of the page; rows deep-link to /exchange/:id, where the+// detail endpoint's derivatives fallback serves them. Cached 5 min.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { geckoFetch } from '../_lib/coingecko.js';let _cache = null; // { value, expiresAt }+let _exCache = null; // { value, expiresAt }const TTL_MS = 60_000;+const EX_TTL_MS = 300_000;const num = (v) => {if (v == null || v === '') return null;@@ -49,6 +56,37 @@ async function build() {return value;}+async function buildExchanges() {+ const now = Date.now();+ if (_exCache && _exCache.expiresAt > now) return _exCache.value;++ // trade_volume_24h_btc arrives as a string on this endpoint — num() coerces.+ const raw = await geckoFetch('/derivatives/exchanges?order=open_interest_btc_desc&per_page=50', {+ ttlMs: EX_TTL_MS,+ });+ const rows = Array.isArray(raw) ? raw : [];++ const exchanges = rows+ .filter((e) => e && e.id)+ .map((e) => ({+ id: String(e.id),+ name: e.name || e.id,+ image: e.image || null,+ open_interest_btc: num(e.open_interest_btc),+ trade_volume_24h_btc: num(e.trade_volume_24h_btc),+ perpetual_pairs: num(e.number_of_perpetual_pairs),+ futures_pairs: num(e.number_of_futures_pairs),+ year_established: num(e.year_established),+ country: e.country || null,+ }));++ if (!exchanges.length) throw new Error('empty derivatives exchanges payload');++ const value = { exchanges, updated_at: now };+ _exCache = { value, expiresAt: now + EX_TTL_MS };+ return value;+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -56,6 +94,24 @@ export default wrap(async (req, res) => {const rl = await limits.marketDataIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);+ const view = new URL(req.url, 'http://x').searchParams.get('view');++ if (view === 'exchanges') {+ try {+ const payload = await buildExchanges();+ return json(res, 200, payload, {+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=900',+ });+ } catch {+ return error(+ res,+ 502,+ 'upstream_error',+ 'derivatives exchange data is unavailable right now — retry shortly',+ );+ }+ }+try {const payload = await build();return json(res, 200, payload, {diff --git a/api/coin/detail.js b/api/coin/detail.jsindex beb87550c..3b518807c 100644--- a/api/coin/detail.js+++ b/api/coin/detail.js@@ -16,11 +16,23 @@ const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);+const firstStr = (arr) => (Array.isArray(arr) ? (arr.map(str).find(Boolean) ?? null) : null);++// A stats object where every field is null or 0 carries no signal (CoinGecko+// reports all-zero developer/community blocks for coins with no tracked repo+// or socials) — collapse it to null so the page can hide the whole section.+function nullIfEmpty(obj) {+ return Object.values(obj).some((v) => v != null && v !== 0) ? obj : null;+}function shape(c) {const md = c.market_data || {};+ const dev = c.developer_data || {};+ const com = c.community_data || {};const links = c.links || {};const explorers = (links.blockchain_site || []).filter((u) => str(u)).slice(0, 3);+ const mcap = num(md.market_cap?.usd);+ const fdv = num(md.fully_diluted_valuation?.usd);// Contract addresses per chain — the page uses these to cross-link Solana// mints into the platform's own intel surfaces.const platforms = {};@@ -41,23 +53,35 @@ function shape(c) {reddit: str(links.subreddit_url),telegram: str(links.telegram_channel_identifier),github: str(links.repos_url?.github?.[0]),+ whitepaper: str(links.whitepaper),+ forum: firstStr(links.official_forum_url),+ chat: firstStr(links.chat_url),+ announcement: firstStr(links.announcement_url),+ repos: (links.repos_url?.github || []).filter((u) => str(u)).slice(0, 3),explorers,},platforms,market: {price: num(md.current_price?.usd),- market_cap: num(md.market_cap?.usd),- fdv: num(md.fully_diluted_valuation?.usd),+ market_cap: mcap,+ fdv,volume_24h: num(md.total_volume?.usd),high_24h: num(md.high_24h?.usd),low_24h: num(md.low_24h?.usd),change_24h_abs: num(md.price_change_24h),change_pct: {+ // 1h is only exposed per-currency; the multi-day windows are top-level.+ h1: num(md.price_change_percentage_1h_in_currency?.usd),h24: num(md.price_change_percentage_24h),d7: num(md.price_change_percentage_7d),+ d14: num(md.price_change_percentage_14d),d30: num(md.price_change_percentage_30d),+ d60: num(md.price_change_percentage_60d),+ d200: num(md.price_change_percentage_200d),y1: num(md.price_change_percentage_1y),},+ mcap_change_24h_pct: num(md.market_cap_change_percentage_24h),+ mcap_fdv_ratio: mcap != null && fdv ? Number((mcap / fdv).toFixed(4)) : null,circulating: num(md.circulating_supply),total: num(md.total_supply),max: num(md.max_supply),@@ -67,6 +91,33 @@ function shape(c) {atl: num(md.atl?.usd),atl_date: str(md.atl_date?.usd),},+ sentiment: {+ up_pct: num(c.sentiment_votes_up_percentage),+ down_pct: num(c.sentiment_votes_down_percentage),+ watchlist_users: num(c.watchlist_portfolio_users),+ },+ meta: {+ genesis_date: str(c.genesis_date),+ hashing_algorithm: str(c.hashing_algorithm),+ // 0 means "not applicable" upstream (most non-PoW coins), not a real cadence.+ block_time_minutes: num(c.block_time_in_minutes) || null,+ country_origin: str(c.country_origin),+ },+ developer: nullIfEmpty({+ stars: num(dev.stars),+ forks: num(dev.forks),+ subscribers: num(dev.subscribers),+ total_issues: num(dev.total_issues),+ closed_issues: num(dev.closed_issues),+ prs_merged: num(dev.pull_requests_merged),+ pr_contributors: num(dev.pull_request_contributors),+ commits_4w: num(dev.commit_count_4_weeks),+ }),+ community: nullIfEmpty({+ twitter_followers: num(com.twitter_followers),+ reddit_subscribers: num(com.reddit_subscribers),+ telegram_users: num(com.telegram_channel_user_count),+ }),last_updated: str(c.last_updated),};}@@ -92,7 +143,7 @@ export default wrap(async (req, res) => {const raw = contract? await geckoFetch(`/coins/solana/contract/${contract}`, { ttlMs: 60_000 }): await geckoFetch(- `/coins/${id}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false`,+ `/coins/${id}?localization=false&tickers=false&market_data=true&community_data=true&developer_data=true&sparkline=false`,{ ttlMs: 60_000 },);return json(res, 200, { coin: shape(raw) }, {diff --git a/api/coin/exchange.js b/api/coin/exchange.jsnew file mode 100644index 000000000..3527ff6f6--- /dev/null+++ b/api/coin/exchange.js@@ -0,0 +1,229 @@+// GET /api/coin/exchange?id=<slug>[&days=7|14|30|90|180|365][&view=chart]+// ---------------------------------------------------------------------------+// Rich profile for one exchange — powers the /exchange/:id detail page.+// Proxies CoinGecko `/exchanges/{id}` (profile + first 50 spot tickers) plus+// `/exchanges/{id}/volume_chart` for the BTC-denominated volume history, and+// converts to USD with the live BTC price (same /simple/price feed as+// api/coin/exchanges.js). When the id is a derivatives venue — CoinGecko keeps+// those on a separate namespace — the spot lookup 404s and we fall back to+// `/derivatives/exchanges/{id}` (open interest, perp/futures counts, contract+// tickers; no volume chart exists upstream for these). `?view=chart&days=N`+// returns only { volume_chart, btc_usd } so the page's range toggle is a light+// refetch. Descriptions are sanitized to plain text server-side. Cached+// in-memory via geckoFetch + CDN s-maxage.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { geckoFetch, htmlToText } from '../_lib/coingecko.js';++const ID_RE = /^[a-z0-9_-]{1,60}$/i;+const DAYS = new Set([1, 7, 14, 30, 90, 180, 365]);+const DETAIL_TTL_MS = 300_000;+const CHART_TTL_MS = 120_000;++// Coerces both numbers and CoinGecko's numeric strings (the derivatives+// endpoints and volume_chart return volumes as strings).+const num = (v) => {+ if (v == null || v === '') return null;+ const n = typeof v === 'number' ? v : Number(v);+ return Number.isFinite(n) ? n : null;+};+const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);+const httpUrl = (v) => (typeof v === 'string' && /^https?:\/\//.test(v) ? v : null);++// DEX tickers use raw contract addresses as base/target symbols — a 40-char+// hex string wrecks the pair column, so truncate anything address-length.+const truncSymbol = (s) => {+ const v = String(s ?? '');+ return v.length > 12 ? `${v.slice(0, 6)}…${v.slice(-4)}` : v;+};++function shapeSpotTicker(t) {+ return {+ base: str(t.base),+ target: str(t.target),+ pair: `${truncSymbol(t.base)}/${truncSymbol(t.target)}`,+ coin_id: str(t.coin_id),+ target_coin_id: str(t.target_coin_id),+ price_usd: num(t.converted_last?.usd),+ volume_usd: num(t.converted_volume?.usd),+ spread_pct: num(t.bid_ask_spread_percentage),+ trust: str(t.trust_score), // 'green' | 'yellow' | 'red' | null+ stale: !!(t.is_stale || t.is_anomaly),+ trade_url: httpUrl(t.trade_url),+ };+}++function shapeDerivativeTicker(t) {+ return {+ symbol: str(t.symbol),+ price: num(t.last),+ index: num(t.index),+ funding_rate: num(t.funding_rate),+ open_interest_usd: num(t.open_interest_usd),+ volume_24h_usd: num(t.converted_volume?.usd),+ spread: num(t.bid_ask_spread), // ratio, not percent+ expired_at: t.expired_at ?? null,+ trade_url: httpUrl(t.trade_url),+ };+}++function shapeSocials(d) {+ const other = [d.other_url_1, d.other_url_2, d.slack_url]+ .map(httpUrl)+ .filter(Boolean);+ return {+ twitter: str(d.twitter_handle),+ reddit_url: httpUrl(d.reddit_url),+ telegram_url: httpUrl(d.telegram_url),+ facebook_url: httpUrl(d.facebook_url),+ other_urls: other,+ };+}++// CoinGecko's `/exchanges/{id}` detail payload omits the normalized 24h volume+// (only the ranked list carries it), so it is enriched best-effort from the+// same `/exchanges` list the /exchanges page uses — shared geckoFetch cache,+// null when the venue sits outside the top 100.+function shapeSpotDetail(id, d, normalized) {+ const tickers = Array.isArray(d.tickers) ? d.tickers : [];+ return {+ type: 'spot',+ id,+ name: str(d.name) || id,+ image: httpUrl(d.image),+ year_established: num(d.year_established),+ country: str(d.country),+ description: htmlToText(d.description || '').slice(0, 2000),+ url: httpUrl(d.url),+ centralized: typeof d.centralized === 'boolean' ? d.centralized : null,+ trust_score: num(d.trust_score),+ trust_score_rank: num(d.trust_score_rank),+ trade_volume_24h_btc: num(d.trade_volume_24h_btc),+ trade_volume_24h_btc_normalized: normalized,+ socials: shapeSocials(d),+ tickers_count: tickers.length,+ tickers: tickers.slice(0, 50).map(shapeSpotTicker),+ };+}++function shapeDerivativesDetail(id, d) {+ const tickers = Array.isArray(d.tickers) ? d.tickers : [];+ return {+ type: 'derivatives',+ id,+ name: str(d.name) || id,+ image: httpUrl(d.image),+ year_established: num(d.year_established),+ country: str(d.country),+ description: htmlToText(d.description || '').slice(0, 2000),+ url: httpUrl(d.url),+ centralized: null, // upstream doesn't say for derivatives venues+ trust_score: null,+ trust_score_rank: null,+ trade_volume_24h_btc: num(d.trade_volume_24h_btc),+ trade_volume_24h_btc_normalized: null,+ open_interest_btc: num(d.open_interest_btc),+ number_of_perpetual_pairs: num(d.number_of_perpetual_pairs),+ number_of_futures_pairs: num(d.number_of_futures_pairs),+ socials: shapeSocials(d),+ tickers_count: tickers.length,+ tickers: tickers.slice(0, 50).map(shapeDerivativeTicker),+ };+}++// Upstream volume points arrive as [ts_ms, "13421.896…"] — strings.+function shapeVolumeChart(raw) {+ if (!Array.isArray(raw)) return [];+ return raw+ .map((p) => [Number(p?.[0]), Number.parseFloat(p?.[1])])+ .filter(([ts, v]) => Number.isFinite(ts) && Number.isFinite(v));+}++async function fetchBtcUsd() {+ try {+ const p = await geckoFetch('/simple/price?ids=bitcoin&vs_currencies=usd', { ttlMs: 60_000 });+ const v = num(p?.bitcoin?.usd);+ return v != null && v > 0 ? v : null;+ } catch {+ return null; // best-effort — the client falls back to BTC-only figures+ }+}++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.marketDataIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const id = (params.get('id') || '').trim().toLowerCase();+ if (!ID_RE.test(id)) {+ return error(res, 400, 'bad_id', 'id must be a CoinGecko exchange id (1–60 chars: letters, digits, _ or -)');+ }+ const daysRaw = Number(params.get('days') || 30);+ const days = DAYS.has(daysRaw) ? daysRaw : 30;+ const view = (params.get('view') || '').trim().toLowerCase();++ const headers = {+ 'cache-control': 'public, max-age=60, s-maxage=120, stale-while-revalidate=600',+ };++ // Light refetch for the chart range toggle — no profile, no tickers.+ if (view === 'chart') {+ try {+ const [raw, btcUsd] = await Promise.all([+ geckoFetch(`/exchanges/${id}/volume_chart?days=${days}`, { ttlMs: CHART_TTL_MS }),+ fetchBtcUsd(),+ ]);+ return json(res, 200, { volume_chart: shapeVolumeChart(raw), btc_usd: btcUsd }, headers);+ } catch (err) {+ if (err?.status === 404) {+ return error(res, 404, 'not_found', `no volume chart for exchange "${id}"`);+ }+ return error(res, 502, 'upstream_error', 'exchange data is unavailable right now — retry shortly');+ }+ }++ const [detailRes, chartRes, priceRes, listRes] = await Promise.allSettled([+ geckoFetch(`/exchanges/${id}`, { ttlMs: DETAIL_TTL_MS }),+ geckoFetch(`/exchanges/${id}/volume_chart?days=${days}`, { ttlMs: CHART_TTL_MS }),+ fetchBtcUsd(),+ geckoFetch('/exchanges?per_page=100&page=1', { ttlMs: 300_000 }),+ ]);+ const btcUsd = priceRes.status === 'fulfilled' ? priceRes.value : null;++ if (detailRes.status === 'fulfilled') {+ const list = listRes.status === 'fulfilled' && Array.isArray(listRes.value) ? listRes.value : [];+ const normalized = num(list.find((e) => e?.id === id)?.trade_volume_24h_btc_normalized);+ return json(res, 200, {+ detail: shapeSpotDetail(id, detailRes.value, normalized),+ volume_chart: chartRes.status === 'fulfilled' ? shapeVolumeChart(chartRes.value) : [],+ btc_usd: btcUsd,+ updated_at: Date.now(),+ }, headers);+ }++ if (detailRes.reason?.status !== 404) {+ return error(res, 502, 'upstream_error', 'exchange data is unavailable right now — retry shortly');+ }++ // Spot lookup 404'd — derivatives venues live on a separate CG namespace.+ try {+ const raw = await geckoFetch(`/derivatives/exchanges/${id}?include_tickers=unexpired`, {+ ttlMs: DETAIL_TTL_MS,+ });+ return json(res, 200, {+ detail: shapeDerivativesDetail(id, raw),+ volume_chart: null, // upstream has no volume history for derivatives venues+ btc_usd: btcUsd,+ updated_at: Date.now(),+ }, headers);+ } catch (err) {+ if (err?.status === 404) {+ return error(res, 404, 'not_found', `no exchange found for "${id}"`);+ }+ return error(res, 502, 'upstream_error', 'exchange data is unavailable right now — retry shortly');+ }+});diff --git a/api/coin/markets.js b/api/coin/markets.jsindex 70590ca06..6b70b72a0 100644--- a/api/coin/markets.js+++ b/api/coin/markets.js@@ -1,9 +1,12 @@// GET /api/coin/markets?page=1&per_page=100 → ranked market table rows// GET /api/coin/markets?q=<text> → coin search (id/name/symbol)+// GET /api/coin/markets?category=<slug>&… → table rows for one category// ----------------------------------------------------------------------------// Powers the /coins index. Table mode proxies CoinGecko /coins/markets with-// 7d sparklines (downsampled server-side so 100 rows stay ~50KB); search mode-// proxies /search for the type-ahead. Both cached in-memory + CDN.+// Powers the /coins index and the /category/:id coins table. Table mode+// proxies CoinGecko /coins/markets with 7d sparklines (downsampled+// server-side so 100 rows stay ~50KB), optionally scoped to a CoinGecko+// category id; search mode proxies /search for the type-ahead. Both cached+// in-memory + CDN.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -59,13 +62,20 @@ 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);+ // 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();+ if (category && !/^[a-z0-9-]{1,80}$/.test(category)) {+ return error(res, 400, 'bad_category', 'category must be a CoinGecko category id');+ }const raw = await geckoFetch(`/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=${perPage}&page=${page}` +- `&sparkline=true&price_change_percentage=24h,7d`,+ `&sparkline=true&price_change_percentage=24h,7d` ++ (category ? `&category=${encodeURIComponent(category)}` : ''),{ ttlMs: 60_000, timeoutMs: 10_000 },);if (!Array.isArray(raw)) throw new Error('unexpected upstream payload');- return json(res, 200, { coins: raw.map(shapeRow), page, per_page: perPage }, {+ return json(res, 200, { coins: raw.map(shapeRow), page, per_page: perPage, category: category || null }, {'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300',});} catch {diff --git a/api/coin/news.js b/api/coin/news.jsindex 0ac78c279..58aa049fa 100644--- a/api/coin/news.js+++ b/api/coin/news.js@@ -27,7 +27,11 @@ export default wrap(async (req, res) => {}// Response shape kept stable for src/coin-page.js (published_at naming).+ // id + published_at let the client build the canonical on-site story-page+ // link (src/shared/news-links.js storyPath) instead of bouncing users to+ // the publisher.const articles = result.articles.map((a) => ({+ id: a.id,title: a.title,link: a.link,description: a.description,diff --git a/api/coin/tickers.js b/api/coin/tickers.jsnew file mode 100644index 000000000..4a3dc10c6--- /dev/null+++ b/api/coin/tickers.js@@ -0,0 +1,86 @@+// GET /api/coin/tickers?id=<coingecko-id>&page=1+// ---------------------------------------------------------------------------+// Exchange listings for one coin — powers the Markets table on the /coin/:id+// detail page. Proxies CoinGecko /coins/{id}/tickers ordered by converted+// volume with ±2% depth, slims each ticker to what the table renders, and+// truncates contract-address pair symbols (DEX listings report raw 0x/base58+// addresses as symbols) so every pair stays legible. Cached in-memory 120s ++// CDN s-maxage.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { geckoFetch, isPlausibleCoinId } from '../_lib/coingecko.js';++const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);+const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);++// A pair symbol that is really a contract address (EVM 0x… or a base58 mint)+// renders as an unreadable wall of characters — shorten to a 6-char prefix.+const ADDRESS_SYMBOL_RE = /^(0x[0-9a-fA-F]{8,}|[1-9A-HJ-NP-Za-km-z]{32,64})$/;++function pairSymbol(s) {+ const v = str(s);+ if (!v) return null;+ return ADDRESS_SYMBOL_RE.test(v) ? `${v.slice(0, 6)}…` : v.toUpperCase();+}++function shapeTicker(t) {+ const base = pairSymbol(t.base);+ const target = pairSymbol(t.target);+ const tradeUrl = str(t.trade_url);+ return {+ exchange: {+ id: str(t.market?.identifier),+ name: str(t.market?.name),+ logo: str(t.market?.logo),+ },+ base,+ target,+ pair: base && target ? `${base}/${target}` : null,+ price_usd: num(t.converted_last?.usd),+ volume_usd: num(t.converted_volume?.usd),+ spread_pct: num(t.bid_ask_spread_percentage),+ depth_up_usd: num(t.cost_to_move_up_usd),+ depth_down_usd: num(t.cost_to_move_down_usd),+ trust: t.trust_score === 'green' || t.trust_score === 'yellow' || t.trust_score === 'red' ? t.trust_score : null,+ stale: Boolean(t.is_stale || t.is_anomaly),+ // Only ever hand the client an http(s) URL — trade_url is upstream-controlled.+ trade_url: tradeUrl && /^https?:\/\//i.test(tradeUrl) ? tradeUrl : null,+ coin_id: str(t.coin_id),+ target_coin_id: str(t.target_coin_id),+ last_traded: str(t.timestamp),+ };+}++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.marketDataIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const id = (params.get('id') || '').trim().toLowerCase();+ if (!isPlausibleCoinId(id)) {+ return error(res, 400, 'bad_id', 'id must be a CoinGecko coin id (lowercase slug)');+ }+ const page = parseInt(params.get('page') || '1', 10) || 1;+ if (page < 1 || page > 10) {+ return error(res, 400, 'bad_page', 'page must be an integer between 1 and 10');+ }++ try {+ const raw = await geckoFetch(+ `/coins/${id}/tickers?page=${page}&order=converted_volume_desc&depth=true&include_exchange_logo=true`,+ { ttlMs: 120_000, timeoutMs: 10_000 },+ );+ const tickers = (raw?.tickers || []).map(shapeTicker);+ return json(res, 200, { tickers, page, count: tickers.length }, {+ 'cache-control': 'public, max-age=60, s-maxage=120, stale-while-revalidate=600',+ });+ } catch (err) {+ if (err?.status === 404)+ return error(res, 404, 'not_found', `no coin found for "${id}"`);+ return error(res, 502, 'upstream_error', 'exchange listings are unavailable right now — retry shortly');+ }+});diff --git a/api/defi/yields.js b/api/defi/yields.jsnew file mode 100644index 000000000..1a6541289--- /dev/null+++ b/api/defi/yields.js@@ -0,0 +1,296 @@+// GET /api/defi/yields — DeFi yield pools for the /yields explorer.+// ---------------------------------------------------------------------------+// Two modes over DeFiLlama's keyless yields API (yields.llama.fi):+//+// List — GET /api/defi/yields?chain=&project=&stablecoin=&search=&minTvl=+// &sort=tvl|apy&limit=&offset=+// Fetches /pools (a multi-MB payload of ~15k pools), slims each pool+// to the fields the page renders, caches the slimmed set in-memory+// for 10 min, then filters / sorts / pages per request. The response+// also carries filter-agnostic facets (top chains + projects by pool+// TVL) for the page's dropdowns and whole-dataset stats.+//+// Chart — GET /api/defi/yields?pool=<uuid>+// Fetches /chart/{pool} (per-pool APY + TVL history) and downsamples+// it to ≤300 points. Unknown pools 404 rather than 502.+//+// DeFiLlama is the data source — see the page's attribution line.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const POOLS_UPSTREAM = 'https://yields.llama.fi/pools';+const CHART_UPSTREAM = 'https://yields.llama.fi/chart/';+const POOLS_TTL_MS = 600_000;+const CHART_TTL_MS = 600_000;+const CHART_CACHE_MAX = 100;+const DEFAULT_LIMIT = 100;+const MAX_LIMIT = 200;+const CHART_MAX_POINTS = 300;+// APY sorting and the median-APY stat only consider pools above this TVL floor:+// dust pools routinely report five-digit APYs on three digits of liquidity,+// which would otherwise bury every real pool under spam.+const APY_MIN_TVL = 10_000;+const FACET_CHAINS = 30;+const FACET_PROJECTS = 50;+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++const finite = (n) => (Number.isFinite(n) ? n : null);++// ── Pools cache ─────────────────────────────────────────────────────────────++let _pools = null; // { value: { pools, facets, stats, updated_at }, expiresAt }+let _poolsInflight = null; // dedupe concurrent multi-MB upstream fetches++function slimPool(p) {+ const tvl = Number(p?.tvlUsd);+ return {+ pool: p.pool,+ chain: typeof p.chain === 'string' ? p.chain : 'Unknown',+ project: typeof p.project === 'string' ? p.project : 'unknown',+ symbol: typeof p.symbol === 'string' ? p.symbol : '—',+ tvl_usd: tvl,+ apy: finite(Number(p.apy)),+ apy_base: finite(Number(p.apyBase)),+ apy_reward: finite(Number(p.apyReward)),+ apy_mean_30d: finite(Number(p.apyMean30d)),+ apy_change_1d: finite(Number(p.apyPct1D)),+ apy_change_7d: finite(Number(p.apyPct7D)),+ il_risk: typeof p.ilRisk === 'string' ? p.ilRisk : null,+ exposure: typeof p.exposure === 'string' ? p.exposure : null,+ stablecoin: p.stablecoin === true,+ outlook: typeof p.predictions?.predictedClass === 'string' ? p.predictions.predictedClass : null,+ outlook_confidence: finite(Number(p.predictions?.predictedProbability)),+ pool_meta: typeof p.poolMeta === 'string' && p.poolMeta ? p.poolMeta : null,+ };+}++function median(sorted) {+ if (!sorted.length) return null;+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+}++// Top-N (chain|project) facets by summed pool TVL, with pool counts, over the+// FULL dataset — the dropdowns must offer every major venue regardless of the+// caller's current filters.+function buildFacets(pools, key, topN) {+ const agg = new Map(); // name → { tvl, count }+ for (const p of pools) {+ const name = p[key];+ const cur = agg.get(name) || { tvl: 0, count: 0 };+ cur.tvl += p.tvl_usd;+ cur.count += 1;+ agg.set(name, cur);+ }+ return [...agg.entries()]+ .sort((a, b) => b[1].tvl - a[1].tvl)+ .slice(0, topN)+ .map(([name, { count }]) => ({ name, pool_count: count }));+}++async function loadPools() {+ const now = Date.now();+ if (_pools && _pools.expiresAt > now) return _pools.value;+ if (_poolsInflight) return _poolsInflight;++ _poolsInflight = (async () => {+ const resp = await fetch(POOLS_UPSTREAM, {+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(20_000),+ });+ if (!resp.ok) throw new Error(`llama yields ${resp.status}`);+ const raw = await resp.json();+ if (!Array.isArray(raw?.data)) throw new Error('unexpected upstream shape');++ const pools = [];+ for (const p of raw.data) {+ if (typeof p?.pool !== 'string') continue;+ const tvl = Number(p.tvlUsd);+ if (!Number.isFinite(tvl) || tvl < 0) continue;+ pools.push(slimPool(p));+ }+ // Default presentation order is TVL desc; sorting once at build time makes+ // every default-list request a pure slice.+ pools.sort((a, b) => b.tvl_usd - a.tvl_usd);++ const apys = pools+ .filter((p) => p.tvl_usd >= APY_MIN_TVL && p.apy != null)+ .map((p) => p.apy)+ .sort((a, b) => a - b);++ const value = {+ pools,+ facets: {+ chains: buildFacets(pools, 'chain', FACET_CHAINS),+ projects: buildFacets(pools, 'project', FACET_PROJECTS),+ },+ stats: {+ pool_count: pools.length,+ total_tvl: pools.reduce((sum, p) => sum + p.tvl_usd, 0),+ median_apy: median(apys),+ },+ updated_at: Date.now(),+ };+ _pools = { value, expiresAt: Date.now() + POOLS_TTL_MS };+ return value;+ })();++ try {+ return await _poolsInflight;+ } finally {+ _poolsInflight = null;+ }+}++// ── List mode ───────────────────────────────────────────────────────────────++function parseBool(v) {+ if (v == null) return undefined;+ const s = String(v).toLowerCase();+ if (s === 'true' || s === '1') return true;+ if (s === 'false' || s === '0') return false;+ return undefined;+}++function clampInt(v, { def, min, max }) {+ const n = parseInt(v ?? '', 10);+ if (!Number.isFinite(n)) return def;+ return Math.max(min, Math.min(max, n));+}++async function listMode(req, res, params) {+ const chain = (params.get('chain') || '').trim().toLowerCase();+ const project = (params.get('project') || '').trim().toLowerCase();+ const stablecoin = parseBool(params.get('stablecoin'));+ const search = (params.get('search') || '').trim().toLowerCase();+ const minTvl = Math.max(0, Number(params.get('minTvl')) || 0);+ const sort = params.get('sort') === 'apy' ? 'apy' : 'tvl';+ const limit = clampInt(params.get('limit'), { def: DEFAULT_LIMIT, min: 1, max: MAX_LIMIT });+ const offset = clampInt(params.get('offset'), { def: 0, min: 0, max: 1_000_000 });++ const { pools, facets, stats, updated_at } = await loadPools();++ let rows = pools.filter((p) => {+ if (chain && p.chain.toLowerCase() !== chain) return false;+ if (project && p.project.toLowerCase() !== project) return false;+ if (stablecoin !== undefined && p.stablecoin !== stablecoin) return false;+ if (minTvl && p.tvl_usd < minTvl) return false;+ if (search && !`${p.symbol} ${p.project} ${p.chain}`.toLowerCase().includes(search)) return false;+ return true;+ });++ if (sort === 'apy') {+ // Dust-pool guard: never let a $200 pool advertising 80,000% APY outrank+ // real venues. Only pools above the TVL floor are eligible for APY order.+ rows = rows+ .filter((p) => p.tvl_usd >= APY_MIN_TVL && p.apy != null)+ .sort((a, b) => b.apy - a.apy);+ }+ // sort === 'tvl' needs no work — the cache is already TVL desc.++ return json(+ res,+ 200,+ {+ pools: rows.slice(offset, offset + limit),+ total: rows.length,+ limit,+ offset,+ sort,+ facets,+ stats,+ updated_at,+ },+ { 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600' },+ );+}++// ── Chart mode ──────────────────────────────────────────────────────────────++const _charts = new Map(); // pool uuid → { value, expiresAt }++// Even stride over the series, always keeping the last point (the chart cares+// most about where the line ends).+function downsample(points, max) {+ if (points.length <= max) return points;+ const step = (points.length - 1) / (max - 1);+ const out = [];+ for (let i = 0; i < max; i++) out.push(points[Math.round(i * step)]);+ return out;+}++async function loadChart(pool) {+ const now = Date.now();+ const hit = _charts.get(pool);+ if (hit && hit.expiresAt > now) return hit.value;++ const resp = await fetch(`${CHART_UPSTREAM}${pool}`, {+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(15_000),+ });+ // DeFiLlama answers an unknown pool id with a non-200 or an empty data set;+ // both mean "no history for this pool", not an outage.+ if (resp.status === 404 || resp.status === 400) return null;+ if (!resp.ok) throw new Error(`llama chart ${resp.status}`);+ const raw = await resp.json();+ if (!Array.isArray(raw?.data)) throw new Error('unexpected upstream shape');++ const points = [];+ for (const d of raw.data) {+ const t = Date.parse(d?.timestamp);+ if (!Number.isFinite(t)) continue;+ points.push({ t, apy: finite(Number(d.apy)), tvl_usd: finite(Number(d.tvlUsd)) });+ }+ if (!points.length) return null;++ const value = { pool, points: downsample(points, CHART_MAX_POINTS), updated_at: now };+ if (_charts.size >= CHART_CACHE_MAX) {+ // Drop the stalest entry so a browse across many pools stays bounded.+ const oldest = [..._charts.entries()].sort((a, b) => a[1].expiresAt - b[1].expiresAt)[0];+ if (oldest) _charts.delete(oldest[0]);+ }+ _charts.set(pool, { value, expiresAt: now + CHART_TTL_MS });+ return value;+}++async function chartMode(req, res, pool) {+ if (!UUID_RE.test(pool)) {+ return error(res, 400, 'invalid_pool', 'pool must be a DeFiLlama pool uuid');+ }+ const value = await loadChart(pool.toLowerCase());+ if (!value) {+ return error(res, 404, 'pool_not_found', 'no APY/TVL history for this pool id');+ }+ return json(res, 200, value, {+ 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1200',+ });+}++// ── Handler ─────────────────────────────────────────────────────────────────++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.marketDataIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const pool = params.get('pool');++ try {+ if (pool) return await chartMode(req, res, pool);+ return await listMode(req, res, params);+ } catch (err) {+ // 4xx from the mode handlers (invalid uuid, unknown pool) already returned;+ // anything thrown here is upstream trouble.+ if (err?.status && err.status < 500) throw err;+ return error(+ res,+ 502,+ 'upstream_error',+ 'DeFi yield data is unavailable right now — retry shortly',+ );+ }+});diff --git a/api/news/archive.js b/api/news/archive.jsindex 10277663b..b49af738e 100644--- a/api/news/archive.js+++ b/api/news/archive.js@@ -12,7 +12,8 @@// it hourly from the live feed. Never hardcode the end date here — read// meta/stats.json (last_article_date), which the appender keeps current.//-// Data layout (public bucket, gzip at rest, transparently decoded):+// Data layout and month-file access live in api/_lib/news-archive-store.js+// (shared with the story pages and the news sitemap):// articles/YYYY-MM.jsonl one enriched article per line// meta/stats.json corpus-wide statistics// indexes/by-{date,source,ticker}.json@@ -54,29 +55,15 @@ import { priceFor } from '../_lib/x402-prices.js';import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { declareHttpDiscovery, withService } from '../_lib/x402/bazaar-helpers.js';import { installAccessControl } from '../_lib/x402/access-control.js';--const GCS_BASE = 'https://storage.googleapis.com/three-ws-news-archive';-const GCS_LIST =- 'https://storage.googleapis.com/storage/v1/b/three-ws-news-archive/o?prefix=articles/&fields=items(name)&maxResults=500';+import { getStats, getMonths, loadMonth } from '../_lib/news-archive-store.js';const MAX_MONTHS_PER_SCAN = 12;const MONTH_FETCH_CONCURRENCY = 3;-const MONTH_CACHE_MAX = 5;const ROUTE = '/api/news/archive';const PRICE_ATOMICS = priceFor('news-archive', '1000'); // $0.001/search (env: X402_PRICE_NEWS_ARCHIVE)const FREE_SEARCHES_PER_DAY = 60; // keep in sync with limits.newsArchiveFreeIp-// month "YYYY-MM" → compact article records (newest month files are ~2–11 MB-// raw; compact form keeps only serving fields). LRU by Map insertion order.-const monthCache = new Map();-// small metadata caches: { value, expiresAt }-let statsCache = null;-let monthsCache = null;-const META_TTL_MS = 3600_000;--const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);-function httpErr(status, code, message) {const e = new Error(message);e.status = status;@@ -84,92 +71,6 @@ function httpErr(status, code, message) {return e;}-function compact(a) {- return {- id: a.id,- title: a.title,- link: str(a.link) || str(a.canonical_link),- description: str(a.description) ? a.description.slice(0, 240) : null,- source: a.source || a.source_key || 'unknown',- source_key: a.source_key || 'unknown',- category: a.category || 'general',- pub_date: a.pub_date || a.first_seen || null,- tickers: Array.isArray(a.tickers) ? a.tickers.slice(0, 8) : [],- tags: Array.isArray(a.tags) ? a.tags.slice(0, 6) : [],- sentiment: a.sentiment ? { label: a.sentiment.label, score: a.sentiment.score } : null,- lang: a.meta?.language || 'en',- is_breaking: !!a.meta?.is_breaking,- market_context: a.market_context- ? {- btc_price: a.market_context.btc_price ?? null,- eth_price: a.market_context.eth_price ?? null,- fear_greed_index: a.market_context.fear_greed_index ?? null,- }- : null,- };-}--async function fetchJson(url, timeoutMs = 15_000) {- const resp = await fetch(url, {- headers: { accept: 'application/json' },- signal: AbortSignal.timeout(timeoutMs),- });- if (!resp.ok) throw new Error(`archive upstream ${resp.status}`);- return resp.json();-}--async function getStats() {- if (statsCache && statsCache.expiresAt > Date.now()) return statsCache.value;- const value = await fetchJson(`${GCS_BASE}/meta/stats.json`);- statsCache = { value, expiresAt: Date.now() + META_TTL_MS };- return value;-}--async function getMonths() {- if (monthsCache && monthsCache.expiresAt > Date.now()) return monthsCache.value;- const listing = await fetchJson(GCS_LIST);- const value = (listing.items || [])- .map((o) => {- const m = /^articles\/(\d{4}-\d{2})\.jsonl$/.exec(o.name);- return m ? m[1] : null;- })- .filter(Boolean)- .sort(); // ascending YYYY-MM- if (!value.length) throw new Error('archive month listing is empty');- monthsCache = { value, expiresAt: Date.now() + META_TTL_MS };- return value;-}--async function loadMonth(month) {- if (monthCache.has(month)) {- const records = monthCache.get(month);- monthCache.delete(month);- monthCache.set(month, records); // refresh LRU recency- return records;- }- const resp = await fetch(`${GCS_BASE}/articles/${month}.jsonl`, {- signal: AbortSignal.timeout(30_000),- });- if (!resp.ok) throw new Error(`month ${month} → ${resp.status}`);- const text = await resp.text();- const records = [];- for (const line of text.split('\n')) {- if (!line.trim()) continue;- try {- records.push(compact(JSON.parse(line)));- } catch {- // skip the malformed line, keep the month- }- }- // newest-first inside the month so early-stop pagination is stable- records.sort((a, b) => new Date(b.pub_date || 0) - new Date(a.pub_date || 0));- monthCache.set(month, records);- while (monthCache.size > MONTH_CACHE_MAX) {- monthCache.delete(monthCache.keys().next().value);- }- return records;-}-function buildPredicate({ q, ticker, source, category, sentiment, lang, startDate, endDate }) {const needle = q ? q.toLowerCase() : null;const tickerUpper = ticker ? ticker.toUpperCase() : null;diff --git a/api/news/article.js b/api/news/article.jsindex d864fd015..16820cf46 100644--- a/api/news/article.js+++ b/api/news/article.js@@ -18,7 +18,7 @@import { lookup } from 'node:dns/promises';import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { getNews, findArticle, extractTickers, lexiconSentiment, stripHtml, stripJsonFence } from '../_lib/news.js';+import { getNews, findArticle, extractTickers, lexiconSentiment, stripHtml, stripJsonFence, metaContent } from '../_lib/news.js';import { llmComplete, llmConfigured } from '../_lib/llm.js';const FETCH_TIMEOUT_MS = 10_000;@@ -59,18 +59,7 @@ async function assertPublicUrl(urlString) {}// ── Extraction ───────────────────────────────────────────────────────────────--function metaContent(html, patterns) {- for (const name of patterns) {- const re = new RegExp(- `<meta[^>]+(?:property|name)=["']${name}["'][^>]+content=["']([^"']+)["']|<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["']${name}["']`,- 'i',- );- const m = html.match(re);- if (m) return (m[1] || m[2] || '').trim() || null;- }- return null;-}+// metaContent lives in _lib/news.js, shared with the /api/news/image resolver.function extractParagraphs(html) {// Prefer semantic containers; fall back to the whole document.diff --git a/api/news/feed.js b/api/news/feed.jsindex 36f63552f..2ab21456e 100644--- a/api/news/feed.js+++ b/api/news/feed.js@@ -12,6 +12,8 @@// carries international feeds in 17 languages; they are opt-in so// the default feed does not interleave languages.// q case-insensitive full-text filter (title/description/tickers)+// featured '1' narrows sources to the majors (tier1/tier2 or credibility+// ≥ 0.85) — the Featured tab on /markets/news// limit 1–50 (default 30)// offset pagination offset// meta=1 include the source registry + category + language lists@@ -36,6 +38,7 @@ export default wrap(async (req, res) => {const source = (params.get('source') || '').trim().toLowerCase() || undefined;const q = (params.get('q') || '').trim().slice(0, 80) || undefined;const lang = (params.get('lang') || 'en').trim().toLowerCase();+ const featured = params.get('featured') === '1';const limit = Math.min(Math.max(1, parseInt(params.get('limit') || '30', 10) || 30), 50);const offset = Math.max(0, parseInt(params.get('offset') || '0', 10) || 0);@@ -57,7 +60,7 @@ export default wrap(async (req, res) => {});}- const result = await getNews({ category, source, lang, q, limit, offset });+ const result = await getNews({ category, source, lang, q, limit, offset, featured });const body = {articles: result.articles,@@ -77,6 +80,7 @@ export default wrap(async (req, res) => {key,name: s.name,category: s.category,+ ...(s.tier ? { tier: s.tier } : {}),...(s.language ? { language: s.language } : {}),}));}diff --git a/api/news/image.js b/api/news/image.jsnew file mode 100644index 000000000..6f06d9e31--- /dev/null+++ b/api/news/image.js@@ -0,0 +1,101 @@+// GET /api/news/image?url=<article link>+// ---------------------------------------------------------------------------+// Preview-image resolver for articles whose publisher feed ships no image+// (~20% of the live feed: Seeking Alpha, AMBCrypto, CNBC, Al Jazeera, and+// others publish text-only RSS). The card renders its fallback tile+// immediately, points an <img> here, and this endpoint:+//+// 1. Verifies the URL is a real article currently in the aggregator cache —+// this is NOT an open resolver; a link we never served 404s without a+// single upstream byte being fetched.+// 2. If the cached article already carries an image (a later feed refresh+// picked one up), 302s straight to the same-origin proxy.+// 3. Otherwise fetches the article page itself (SSRF-hardened fetcher:+// scheme allowlist, DNS + private-IP blocklist, byte cap, timeout),+// extracts its og:image / twitter:image, and 302s to /api/img — which+// serves the bytes same-origin, immune to hotlink-referrer blocks.+// 4. If the page has no usable preview image, answers 404 (negatively+// cached) and the card keeps its designed fallback tile.+//+// Both outcomes are cached: in-process per article link, and at the CDN via+// cache-control on the redirect/404 — one resolution per article, ever.++import { wrap, cors, method, json, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { findArticle, extractOgImage } from '../_lib/news.js';+import { fetchModel } from '../_lib/fetch-model.js';++const PAGE_TIMEOUT_MS = 6_000;+const PAGE_MAX_BYTES = 768 * 1024; // og tags live in <head>; cap the download hard+const CACHE_TTL_MS = 24 * 3600_000;+const CACHE_MAX = 3000;++const _resolved = new Map(); // article link → { image: string|null, expiresAt }++function remember(link, image) {+ _resolved.set(link, { image, expiresAt: Date.now() + CACHE_TTL_MS });+ if (_resolved.size > CACHE_MAX) _resolved.delete(_resolved.keys().next().value);+ return image;+}++async function resolvePreviewImage(article) {+ const hit = _resolved.get(article.link);+ if (hit && hit.expiresAt > Date.now()) return hit.image;+ try {+ const page = await fetchModel(article.link, {+ maxBytes: PAGE_MAX_BYTES,+ timeoutMs: PAGE_TIMEOUT_MS,+ headers: {+ // Same polite, identifying UA the aggregator uses for the feeds —+ // it clears more publisher WAFs than a tool UA does.+ 'user-agent': 'Mozilla/5.0 (compatible; three.ws-news/1.0; +https://three.ws)',+ accept: 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.5',+ },+ });+ const ct = page?.contentType || '';+ if (!ct.includes('html')) return remember(article.link, null);+ return remember(article.link, extractOgImage(new TextDecoder().decode(page.bytes)));+ } catch {+ // Publisher blocked or timed out — negative-cache so the next card render+ // doesn't re-pay the fetch; the feed refresh may still deliver an image.+ return remember(article.link, null);+ }+}++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.imgProxyIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'too many image requests');++ const link = (new URL(req.url, 'http://x').searchParams.get('url') || '').trim();+ if (!link) return error(res, 400, 'missing_url', 'url is required');++ // Only articles the aggregator actually served are resolvable — anything+ // else is a probe, not a news card. The 404s are deliberately cacheable+ // (json(), not error()) so an imageless article costs one resolution, not+ // one per render.+ const article = await findArticle({ link });+ if (!article) {+ return json(+ res, 404,+ { error: 'unknown_article', error_description: 'not a current article from the news feed' },+ { 'cache-control': 'public, max-age=300, s-maxage=600' },+ );+ }++ const image = article.image || (await resolvePreviewImage(article));+ if (!image) {+ return json(+ res, 404,+ { error: 'no_preview_image', error_description: 'the publisher page carries no preview image' },+ { 'cache-control': 'public, max-age=1800, s-maxage=3600' },+ );+ }++ res.statusCode = 302;+ res.setHeader('location', `/api/img?url=${encodeURIComponent(image)}&seed=${encodeURIComponent(article.source || 'news')}`);+ res.setHeader('cache-control', 'public, max-age=3600, s-maxage=86400');+ res.end();+});diff --git a/api/news/story-page.js b/api/news/story-page.jsnew file mode 100644index 000000000..4e46e50cb--- /dev/null+++ b/api/news/story-page.js@@ -0,0 +1,268 @@+// GET /markets/news/<YYYY-MM>/<id16>[-slug] → /api/news/story-page?month=&id=+// ---------------------------------------------------------------------------+// Server-rendered story page — the indexable permalink for every article in+// the live feed AND the 660k+ historical archive. The query-param reader+// (/markets/news/article?url=…) stays noindex; THIS page is what crawlers and+// link previews get: real <title>/description/canonical/OpenGraph tags,+// NewsArticle JSON-LD, and a crawler-visible article body (headline, byline,+// story summary, ticker links into /coin/:id, market context at publication,+// source attribution) rendered into the same shell the client reader hydrates.+//+// The client module (src/news-article.js) finds the embedded #art-seed JSON,+// keeps the server-rendered content on screen, and upgrades it in place with+// the full extraction + AI analysis from /api/news/article. No JS → a crawler+// still reads a complete, honest page.++import { readFile } from 'node:fs/promises';+import path from 'node:path';+import { wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { resolveStory, validStoryKey } from '../_lib/news-story.js';+import { storyPath, tickerHref, TICKER_COIN_IDS } from '../../src/shared/news-links.js';++const ORIGIN = env.APP_ORIGIN || 'https://three.ws';+const CACHE_TTL_MS = 10 * 60_000;+const CACHE_MAX = 300;++const _pages = new Map(); // `${month}/${id}` → { html, status, expiresAt }+let _shell = null;++function esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++async function loadShell() {+ if (_shell) return _shell;+ // dist/ in production (the built shell with hashed asset paths); pages/ in+ // a source-only checkout so tests and `node server` before a build still work.+ for (const file of [+ path.join(process.cwd(), 'dist', 'news-article.html'),+ path.join(process.cwd(), 'pages', 'news-article.html'),+ ]) {+ try {+ _shell = await readFile(file, 'utf8');+ return _shell;+ } catch {+ // try next+ }+ }+ throw new Error('news-article shell not found (dist/ or pages/)');+}++// Replace the content="…" of every <meta> whose property/name matches `key`,+// tolerating either attribute order. Values are pre-escaped by the caller.+function setMetaContent(html, key, value) {+ return html.replace(/<meta\b[^>]*>/g, (tag) =>+ new RegExp(`(?:property|name)=["']${key}["']`).test(tag)+ ? tag.replace(/content=["'][^"']*["']/, () => `content="${value}"`)+ : tag,+ );+}++function fmtDate(iso) {+ const d = new Date(iso);+ return Number.isNaN(d.getTime())+ ? null+ : d.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' });+}++function fmtUsd(n) {+ if (typeof n !== 'number' || !Number.isFinite(n)) return null;+ return `$${n.toLocaleString('en-US', { maximumFractionDigits: n >= 1000 ? 0 : 2 })}`;+}++function jsonLd(a, canonicalAbs, ogImage) {+ const graph = {+ '@context': 'https://schema.org',+ '@graph': [+ {+ '@type': 'NewsArticle',+ headline: a.title,+ datePublished: a.pub_date || undefined,+ image: [a.image || ogImage],+ inLanguage: a.lang === 'zh' ? 'zh' : 'en',+ author: { '@type': 'Organization', name: a.source },+ publisher: { '@type': 'Organization', name: 'three.ws', url: ORIGIN },+ mainEntityOfPage: { '@type': 'WebPage', '@id': canonicalAbs },+ isBasedOn: a.link || undefined,+ description: a.description || undefined,+ about: (a.tickers || []).map((t) => ({ '@type': 'Thing', name: t })),+ },+ {+ '@type': 'BreadcrumbList',+ itemListElement: [+ { '@type': 'ListItem', position: 1, name: 'Home', item: `${ORIGIN}/` },+ { '@type': 'ListItem', position: 2, name: 'Markets', item: `${ORIGIN}/markets` },+ { '@type': 'ListItem', position: 3, name: 'News', item: `${ORIGIN}/markets/news` },+ { '@type': 'ListItem', position: 4, name: a.title, item: canonicalAbs },+ ],+ },+ ],+ };+ return JSON.stringify(graph).replace(/</g, '\\u003c');+}++function marketContextHtml(mc) {+ if (!mc) return '';+ const parts = [];+ if (fmtUsd(mc.btc_price)) parts.push(`BTC ${fmtUsd(mc.btc_price)}`);+ if (fmtUsd(mc.eth_price)) parts.push(`ETH ${fmtUsd(mc.eth_price)}`);+ if (mc.fear_greed_index != null) parts.push(`Fear & Greed ${esc(mc.fear_greed_index)}`);+ if (!parts.length) return '';+ return `<p class="art-provider">Market at publication: ${parts.join(' · ')}</p>`;+}++function crawlerBodyHtml(a) {+ const sentiment = a.sentiment?.label || 'neutral';+ const badgeCls = sentiment.includes('positive') ? 'bullish' : sentiment.includes('negative') ? 'bearish' : '';+ const date = fmtDate(a.pub_date);+ const chips = (a.tickers || [])+ .map((t) => {+ const known = TICKER_COIN_IDS[t];+ return `<a class="nw-chip" href="${esc(tickerHref(t))}" aria-label="${known ? `${esc(t)} price and profile` : `More ${esc(t)} coverage`}">${esc(t)}</a>`;+ })+ .join('');+ return `+ ${a.image ? `<div class="art-hero"><img src="${esc(a.image)}" alt="" data-fallback="${esc((a.source || '?').slice(0, 2).toUpperCase())}" /></div>` : ''}+ <h1 class="art-title">${esc(a.title)}</h1>+ <div class="art-byline">+ <span class="src">${esc(a.source)}</span>+ ${a.author ? `<span>${esc(a.author)}</span>` : ''}+ ${date ? `<time datetime="${esc(a.pub_date)}">${esc(date)}</time>` : ''}+ <span class="art-badge ${badgeCls}">${badgeCls === 'bullish' ? '▲' : badgeCls === 'bearish' ? '▼' : '◆'} ${esc(sentiment.replace('_', ' '))}</span>+ </div>+ ${chips ? `<div class="nw-chips" style="margin:0 0 1.25rem">${chips}</div>` : ''}+ <div class="art-summary-card">+ <h2>Story</h2>+ <p>${esc(a.description || a.title)}</p>+ ${marketContextHtml(a.market_context)}+ </div>+ <p style="margin:1.75rem 0 0">+ ${a.link ? `<a class="art-cta" href="${esc(a.link)}" target="_blank" rel="noopener noreferrer">Read at ${esc(a.source)}</a>` : ''}+ </p>+ <p style="margin-top:0.75rem"><a class="mkt-more" href="/markets/news">← All crypto news</a> · <a class="mkt-more" href="/markets/archive">Search the archive</a></p>`;+}++/** Pure shell → page transform, exported for tests. */+export function renderStoryHtml(shell, a) {+ const canonical = storyPath(a);+ const canonicalAbs = `${ORIGIN}${canonical}`;+ const description = (a.description || `${a.title} — ${a.source} coverage on the three.ws crypto news reader.`).slice(0, 300);+ const ogFallback = `${ORIGIN}/api/page-og?s=crypto&t=${encodeURIComponent(a.title.slice(0, 80))}&d=${encodeURIComponent(description.slice(0, 160))}&p=${encodeURIComponent(canonical)}`;+ const ogImage = a.image || ogFallback;+ const date = fmtDate(a.pub_date);+ const title = `${a.title} — ${a.source}${date ? `, ${date}` : ''} · three.ws`;++ let html = shell.replace(/<title>[\s\S]*?<\/title>/, () => `<title>${esc(title)}</title>`);+ html = setMetaContent(html, 'description', esc(description));+ html = setMetaContent(html, 'robots', 'index, follow');+ html = setMetaContent(html, 'og:title', esc(a.title));+ html = setMetaContent(html, 'og:description', esc(description));+ html = setMetaContent(html, 'og:image', esc(ogImage));+ html = setMetaContent(html, 'og:url', esc(canonicalAbs));+ html = setMetaContent(html, 'og:image:alt', esc(a.title));+ html = setMetaContent(html, 'twitter:title', esc(a.title));+ html = setMetaContent(html, 'twitter:description', esc(description));+ html = setMetaContent(html, 'twitter:image', esc(ogImage));+ html = html.replace(/(<link[^>]*rel="canonical"[^>]*href=")[^"]*(")/, (_, pre, post) => `${pre}${esc(canonicalAbs)}${post}`);+ html = html.replace(+ /<script type="application\/ld\+json">[\s\S]*?<\/script>/,+ () => `<script type="application/ld+json">${jsonLd(a, canonicalAbs, ogImage)}</script>`,+ );+ const articleMeta =+ (a.pub_date ? `\t<meta property="article:published_time" content="${esc(a.pub_date)}">\n` : '') ++ `\t<meta property="article:section" content="${esc(a.category || 'general')}">\n` ++ (a.tickers || []).map((t) => `\t<meta property="article:tag" content="${esc(t)}">`).join('\n');+ html = html.replace('</head>', () => `${articleMeta}\n</head>`);++ // Seed for the client reader (instant paint + the /api/news/article call),+ // then the crawler-visible body it hydrates over.+ const seed = {+ id: a.id,+ url: a.link,+ title: a.title,+ source: a.source,+ image: a.image || null,+ author: a.author || null,+ description: a.description || null,+ pub_date: a.pub_date || null,+ tickers: a.tickers || [],+ sentiment: a.sentiment || null,+ market_context: a.market_context || null,+ canonical,+ };+ html = html.replace(+ /<article id="art-root"[^>]*>[\s\S]*?<\/article>/,+ () =>+ `<script type="application/json" id="art-seed">${JSON.stringify(seed).replace(/</g, '\\u003c')}</script>\n` ++ `\t\t\t<article id="art-root" aria-live="polite">${crawlerBodyHtml(a)}</article>`,+ );+ return html;+}++function notFoundHtml(shell, month) {+ const body = `+ <h1 class="art-title">Story not found</h1>+ <div class="cv-empty">+ <p><strong>This article isn’t in the ${esc(month || '')} archive.</strong></p>+ <p>It may have been published in a different month, or the link is incomplete.</p>+ <p><a class="arc-btn" href="/markets/archive">Search the 660k-article archive</a>+ <a class="arc-btn ghost" href="/markets/news">Latest crypto news</a></p>+ </div>`;+ return shell+ .replace(/<title>[\s\S]*?<\/title>/, () => `<title>Story not found · Crypto News · three.ws</title>`)+ .replace(/<article id="art-root"[^>]*>[\s\S]*?<\/article>/, () => `<article id="art-root">${body}</article>`);+}++export default wrap(async (req, res) => {+ if (req.method !== 'GET' && req.method !== 'HEAD') {+ res.statusCode = 405;+ res.setHeader('allow', 'GET, HEAD');+ res.end('Method Not Allowed');+ return;+ }+ const params = new URL(req.url, 'http://x').searchParams;+ const month = (params.get('month') || req.query?.month || '').trim();+ const id = (params.get('id') || req.query?.id || '').trim().toLowerCase();++ const shell = await loadShell();+ res.setHeader('content-type', 'text/html; charset=utf-8');++ if (!validStoryKey(month, id)) {+ res.statusCode = 404;+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=300');+ res.end(notFoundHtml(shell, month));+ return;+ }++ const key = `${month}/${id}`;+ const hit = _pages.get(key);+ if (hit && hit.expiresAt > Date.now()) {+ res.statusCode = hit.status;+ res.setHeader('cache-control', 'public, max-age=300, s-maxage=3600, stale-while-revalidate=86400');+ res.end(hit.html);+ return;+ }++ const resolved = await resolveStory(month, id);+ // A resolvable story always has a canonical path; a dated-but-unlinkable+ // record (no id/date after compaction) can't reach here because the route+ // carries both. Missing → an honest 404, cached briefly.+ const status = resolved && storyPath(resolved.article) ? 200 : 404;+ const html = status === 200 ? renderStoryHtml(shell, resolved.article) : notFoundHtml(shell, month);++ _pages.set(key, { html, status, expiresAt: Date.now() + (status === 200 ? CACHE_TTL_MS : 60_000) });+ if (_pages.size > CACHE_MAX) _pages.delete(_pages.keys().next().value);++ res.statusCode = status;+ res.setHeader(+ 'cache-control',+ status === 200 ? 'public, max-age=300, s-maxage=3600, stale-while-revalidate=86400' : 'public, max-age=60, s-maxage=300',+ );+ res.end(html);+});diff --git a/api/sitemap.js b/api/sitemap.jsindex 2e74e09a9..8b68e7b7b 100644--- a/api/sitemap.js+++ b/api/sitemap.js@@ -72,6 +72,9 @@ export default async function handler(req, res) {{ loc: `${ORIGIN}/sitemap/avatars.xml`, lastmod: fmtDate(avatarsTs || today) },{ loc: `${ORIGIN}/sitemap/widgets.xml`, lastmod: fmtDate(widgetsTs || today) },{ loc: `${ORIGIN}/sitemap/profiles.xml`, lastmod: fmtDate(usersTs || subdomainsTs || today) },+ // Story pages for recent news — the archive appender refreshes hourly,+ // so the newest articles are always crawlable within the hour.+ { loc: `${ORIGIN}/sitemap/news.xml`, lastmod: today },];const body =diff --git a/api/sitemap/[type].js b/api/sitemap/[type].jsindex 0cb605303..24d933fac 100644--- a/api/sitemap/[type].js+++ b/api/sitemap/[type].js@@ -13,6 +13,8 @@ import path from 'node:path';import { sql } from '../_lib/db.js';import { env } from '../_lib/env.js';import { reportServerError, redactUrl } from '../_lib/http.js';+import { getMonths, loadMonth } from '../_lib/news-archive-store.js';+import { storyPath } from '../../src/shared/news-links.js';const ORIGIN = env.APP_ORIGIN;const MAX_URLS = 45_000;@@ -173,12 +175,42 @@ async function profilesSitemap() {}));}+// Story pages (/markets/news/<YYYY-MM>/<id>-<slug>) for the newest archive+// months. The full 660k-article corpus would blow the 50k/URL cap many times+// over — recent months are where crawl demand is, and older stories are+// reachable through the archive UI and inter-article links. Months come from+// the same GCS store the archive endpoint serves, so this stays in lockstep+// with what actually resolves.+const NEWS_SITEMAP_MONTHS = 3;++async function newsSitemap() {+ const months = await getMonths();+ const recent = months.slice(-NEWS_SITEMAP_MONTHS).reverse(); // newest first+ const out = [];+ for (const month of recent) {+ const records = await loadMonth(month).catch(() => []);+ for (const a of records) {+ const loc = storyPath(a);+ if (!loc) continue; // undated/id-less corpus rows have no story page+ out.push({+ loc: `${ORIGIN}${loc}`,+ lastmod: fmtDate(a.pub_date),+ changefreq: 'monthly',+ priority: '0.6',+ });+ if (out.length >= MAX_URLS) return out;+ }+ }+ return out;+}+const BUILDERS = {core: coreSitemap,agents: agentsSitemap,avatars: avatarsSitemap,widgets: widgetsSitemap,profiles: profilesSitemap,+ news: newsSitemap,};export default async function handler(req, res) {diff --git a/data/changelog.json b/data/changelog.jsonindex 6b8c6f1c2..8de397aa3 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-11",+ "title": "Richer coin pages, plus new exchange, category, and DeFi-yields detail pages",+ "summary": "Every coin page now shows far more of what the data already offers: a 1h-to-1y price-performance matrix, a circulating-vs-max supply bar with the market-cap/FDV ratio, all-time high and low with the drawdown and recovery multiple, the community bullish/bearish sentiment split, GitHub and social activity, and a full exchange-listings table with spread, order-book depth, and a trust rating for each venue. Exchanges and crypto categories, which used to only send you off-site or filter a table, now have their own detail pages — an exchange page with a trust badge, wash-volume-adjusted volume, a volume-history chart, and its markets, and a category page with the sector's rank, stats, and full coin list. And a brand-new DeFi Yields explorer covers roughly 15,000 live pools across every chain and protocol, filterable and sortable, each with its own APY and TVL history chart. All of it is real, key-free data.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/yields"+ },{"date": "2026-07-10","title": "Crypto news now aggregates 192 publisher feeds, in 18 languages",diff --git a/data/pages.json b/data/pages.jsonindex 83c84d950..bfd4263f0 100644--- a/data/pages.json+++ b/data/pages.json@@ -1274,6 +1274,14 @@"changefreq": "hourly","added": "2026-07-08"},+ {+ "path": "/yields",+ "title": "DeFi Yields Explorer",+ "description": "Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.",+ "priority": 0.7,+ "changefreq": "hourly",+ "added": "2026-07-11"+ },{"path": "/bnb","title": "BNB Chain — Three Genuinely-Unique Demos",diff --git a/docs/coin-pages.md b/docs/coin-pages.mdindex 55a9e54d5..aaf3328ec 100644--- a/docs/coin-pages.md+++ b/docs/coin-pages.md@@ -40,19 +40,42 @@ editorial serif headings, hairline borders, mono numerals, light/dark themes.24h / 7d / 30d change chips, plus the coin's categories.- **Interactive chart** — SVG line chart across 24H / 7D / 30D / 90D / 1Y witha crosshair tooltip showing exact price and time.+- **Price performance matrix** — colored 1h / 24h / 7d / 14d / 30d / 60d /+ 200d / 1y change cells, so the whole return curve is legible at a glance.- **Market stats** — market cap, 24h volume, circulating/total supply,all-time high and low (dated), 24h high/low.+- **Supply** — a circulating-vs-max (or total) supply bar with the percentage+ in circulation, the market-cap / FDV ratio, and 24h market-cap change.+- **All-time high / low** — value and date for each, the drawdown from ATH,+ and the recovery multiple from ATL.+- **Community sentiment** — the CoinGecko bullish/bearish vote split and the+ number of users watching the coin. Hidden when the coin has no votes.+- **Community & development** — Twitter / Reddit / Telegram followings and+ GitHub stars, forks, watchers, issues, merged PRs, contributors, and+ commits in the last four weeks. Each block hides when untracked.+- **Markets** — a paginated exchange-listings table (from+ [`/api/coin/tickers`](../api/coin/tickers.js)): exchange (linking to its+ [detail page](#exchangeid--exchange-detail)), pair (deep-linking to the+ live trade page on that venue), price, spread, +2% / −2% order-book depth,+ 24h volume, and a color-coded trust rating. Stale/anomalous rows are dimmed.- **Related news** — live articles mentioning the coin, from the nativethree.ws aggregator (192 publisher feeds, `api/_lib/news.js`).- **About + links** — plain-text description, official site / social /- explorer pills, and per-chain contract addresses with one-click copy.+ explorer pills, plus whitepaper, forum, chat, announcement, and extra-repo+ links, and per-chain contract addresses with one-click copy.- **three.ws integration** — coins with a Solana contract cross-link into[Alpha Copilot](/alpha-copilot) and the [live trade feed](/trades). Amint-shaped id that isn't on the market data source points to its[launch profile](/launches) and [Coin Intelligence](/coin-intel) instead.-Unknown ids, upstream outages, loading, and empty news all have designed-states — the page never renders a blank void.+The detail endpoint ([`api/coin/detail.js`](../api/coin/detail.js)) requests+CoinGecko's community and developer blocks and slims the multi-hundred-KB+payload to exactly these fields; all-zero developer/community blocks (coins+with no tracked repo or socials) collapse to `null` so the page hides the+whole section rather than render a wall of zeros.++Unknown ids, upstream outages, loading, and empty news/markets all have+designed states — the page never renders a blank void.## The market tools@@ -105,11 +128,15 @@ data" rule:`/api/coin/markets` (no new endpoint).- **`/categories`** — every crypto sector ranked by market cap with 24h change,volume, and the top coins in each. New `/api/coin/categories` (CoinGecko- `/coins/categories`).+ `/coins/categories`). Each row opens a [category detail+ page](#categoryid--category-detail).- **`/exchanges`** — top exchanges by trust score and 24h volume (USD, derived- from the live BTC price). New `/api/coin/exchanges`.+ from the live BTC price). New `/api/coin/exchanges`. Each row opens an+ [exchange detail page](#exchangeid--exchange-detail).- **`/derivatives`** — perpetual-futures markets: price, funding rate, open- interest, volume, filterable by index. New `/api/coin/derivatives`.+ interest, volume, filterable by index, plus a **Derivatives Exchanges** table+ (open interest, perp/futures counts) whose rows open the exchange detail page.+ `/api/coin/derivatives` (`?view=exchanges` for the venues).- **`/converter`** — convert any crypto ⇄ any major fiat at live rates(USD-anchored math covers all four directions). New `/api/coin/rates`(CoinGecko `/exchange_rates`) + `/api/coin/markets`/`detail`.@@ -119,6 +146,39 @@ data" rule:`/api/defi/chains` (DeFiLlama).- **`/stablecoins`** — stablecoins by circulating market cap with live peghealth and backing mechanism. New `/api/defi/stablecoins` (DeFiLlama).+- **`/yields`** — an explorer over ~15,000 live DeFi yield pools: filter by+ chain, project, stablecoin exposure, and minimum TVL; sort by APY or TVL+ (the APY sort ignores sub-$10k dust pools to keep the ranking honest); open+ any row for its full APY + TVL history in a dual-axis chart. Filters sync to+ the URL for shareable views. New `/api/defi/yields` (DeFiLlama+ `yields.llama.fi/pools` + `/chart/{pool}`).++## Detail pages++Beyond `/coin/:id`, two list surfaces now have their own rich detail pages,+reached by clicking a row.++### `/exchange/:id` — exchange detail++A full profile for one exchange (or derivatives venue): logo, trust-score+badge, rank, country, year established, centralized/DEX flag, and description;+stat cards for 24h volume (BTC + USD), **normalized** 24h volume (adjusted to+discount wash trading), markets count, and trust rank; an interactive+BTC-volume history chart (7D–365D, crosshair with BTC + USD); and a markets+table of the venue's pairs (each pair deep-linking to `/coin/:id` and to the+live trade page), with price, spread, 24h volume, and trust. Derivatives venues+show open interest and perp/futures pair counts with a contract table instead.+New `/api/coin/exchange` (CoinGecko `/exchanges/{id}` + `/volume_chart`, falling+back to `/derivatives/exchanges/{id}`).++### `/category/:id` — category detail++A sector page: rank ("#N by market cap"), description, and stat cards for+market cap, 24h change, 24h volume, and share of the categorized market; the+full sortable coins table for that category (reusing the shared markets table,+so every row deep-links to `/coin/:id`); and a strip of related categories.+Reuses `/api/coin/markets?category=<id>` for the table and new+`/api/coin/category` for the header + neighbours.## News & the markets hub@@ -199,12 +259,16 @@ All data is real and fetched at runtime — nothing is hardcoded or sampled:| Endpoint | Upstream | Cache || ----------------------- | ---------------------------------------------------------- | ------------ |-| `/api/coin/detail` | CoinGecko `/coins/{id}` or `/coins/solana/contract/{mint}` | 60 s |+| `/api/coin/detail` | CoinGecko `/coins/{id}` or `/coins/solana/contract/{mint}` (with community + developer blocks) | 60 s |+| `/api/coin/tickers` | CoinGecko `/coins/{id}/tickers` (exchange listings, ±2% depth) | 120 s || `/api/coin/ohlc` | CoinGecko `/coins/{id}/market_chart` | 120 s |-| `/api/coin/markets` | CoinGecko `/coins/markets`, `/search` | 60 s / 300 s |+| `/api/coin/markets` | CoinGecko `/coins/markets` (optional `category=`), `/search` | 60 s / 300 s || `/api/coin/categories` | CoinGecko `/coins/categories` | 300 s |+| `/api/coin/category` | CoinGecko `/coins/categories` (one category + rank + neighbours) | 600 s || `/api/coin/exchanges` | CoinGecko `/exchanges` + `/simple/price` (BTC) | 300 s |-| `/api/coin/derivatives` | CoinGecko `/derivatives` | 60 s |+| `/api/coin/exchange` | CoinGecko `/exchanges/{id}` (+ `/volume_chart`) or `/derivatives/exchanges/{id}` fallback | 120 s |+| `/api/coin/derivatives` | CoinGecko `/derivatives` (`?view=exchanges` → `/derivatives/exchanges`) | 60 s / 300 s |+| `/api/defi/yields` | DeFiLlama `yields.llama.fi/pools` (+ `/chart/{pool}`) | 300 s / 600 s || `/api/coin/rates` | CoinGecko `/exchange_rates` | 300 s || `/api/defi/protocols` | DeFiLlama `/protocols` (CEX excluded) | 300 s || `/api/defi/chains` | DeFiLlama `/v2/chains` | 300 s |@@ -238,9 +302,12 @@ text before they reach the client.| Gas tracker | [`pages/gas.html`](../pages/gas.html) + [`src/gas.js`](../src/gas.js) || Compare | [`pages/compare.html`](../pages/compare.html) + [`src/compare.js`](../src/compare.js) || Screener / Categories | `pages/screener.html`, `pages/categories.html` (+ `src/*.js`, `src/*.css`) |+| Category detail | [`pages/category.html`](../pages/category.html) + `src/category-page.js` + `src/category-page.css`, API [`api/coin/category.js`](../api/coin/category.js) || Exchanges / Derivatives | `pages/exchanges.html`, `pages/derivatives.html` (+ `src/*.js`, `src/*.css`) |+| Exchange detail | [`pages/exchange.html`](../pages/exchange.html) + `src/exchange-page.js` + `src/exchange-page.css`, API [`api/coin/exchange.js`](../api/coin/exchange.js) || Converter | `pages/converter.html` + `src/converter.js` + `src/converter.css` || DeFi / Chains / Stablecoins | `pages/{defi,chains,stablecoins}.html` (+ `src/*.js`, `src/*.css`), APIs in [`api/defi/`](../api/defi) |+| DeFi Yields | [`pages/yields.html`](../pages/yields.html) + `src/yields.js` + `src/yields.css`, API [`api/defi/yields.js`](../api/defi/yields.js) || Markets hub | [`pages/markets.html`](../pages/markets.html) + [`src/markets-page.js`](../src/markets-page.js) || Crypto news | [`pages/markets-news.html`](../pages/markets-news.html) + [`src/markets-news.js`](../src/markets-news.js) || Article reader | [`pages/news-article.html`](../pages/news-article.html) + [`src/news-article.js`](../src/news-article.js) |diff --git a/pages/category.html b/pages/category.htmlnew file mode 100644index 000000000..58499e698--- /dev/null+++ b/pages/category.html@@ -0,0 +1,94 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Crypto Category · three.ws</title>+ <meta+ name="description"+ content="A crypto sector at a glance — live market cap, 24h move, trading volume, and the ranked coins that make it up, with related categories to explore."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/categories" />+ <meta property="og:title" content="Crypto Category · three.ws" />+ <meta+ property="og:description"+ content="A crypto sector at a glance — live market cap, 24h move, volume, and the ranked coins that make it up."+ />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Crypto Category · three.ws" />+ <meta+ name="twitter:description"+ content="A crypto sector at a glance — live market cap, 24h move, volume, and the ranked coins that make it up."+ />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/category-page.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/categories" />+ <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="Crypto Category — three.ws" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container" id="cat-main" aria-busy="true">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/markets">Markets</a>+ <span class="sep" aria-hidden="true">›</span>+ <a href="/categories">Categories</a>+ <span class="sep" aria-hidden="true">›</span>+ <span class="here" id="cat-crumb">…</span>+ </nav>++ <!-- Hero: category name, market-cap rank, description. Hydrated by src/category-page.js. -->+ <section id="cat-hero" aria-label="Category overview"></section>++ <!-- Market cap / 24h change / volume / share-of-market stat cards. -->+ <section id="cat-stats" class="cv-section" aria-label="Category statistics"></section>++ <!-- Sortable table of the coins in this category, from /api/coin/markets. -->+ <section id="cat-coins" class="cv-section" aria-label="Coins in this category"></section>++ <!-- Rank-nearest related categories. -->+ <section id="cat-related" class="cv-section" aria-label="Related categories"></section>++ <!-- Deep link into the full markets table scoped to this sector. -->+ <section id="cat-footer-link" class="cv-section"></section>+ </main>++ <script type="module" src="/src/category-page.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/coin.html b/pages/coin.htmlindex c01f9b903..89b78ab29 100644--- a/pages/coin.html+++ b/pages/coin.html@@ -37,6 +37,346 @@<link rel="stylesheet" href="/nav.css" /><link rel="stylesheet" href="/src/coin-pages.css" /><link rel="stylesheet" href="/footer.css" />+ <style>+ /* /coin/:id enrichment sections — same token/card system as coin-pages.css,+ scoped here because only this page renders them. */++ /* ── Price performance matrix ── */+ .cv-perf-grid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.5rem;+ }+ @media (min-width: 768px) {+ .cv-perf-grid {+ grid-template-columns: repeat(8, 1fr);+ }+ }+ .cv-perf-cell {+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ background: var(--cv-surface-2);+ padding: 0.625rem 0.375rem;+ text-align: center;+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ transition: border-color 0.15s, box-shadow 0.15s;+ }+ .cv-perf-cell:hover {+ border-color: var(--cv-border-hover);+ box-shadow: var(--cv-shadow-card);+ }+ .cv-perf-cell .win {+ font-size: 0.6875rem;+ font-weight: 500;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--cv-text-3);+ }+ .cv-perf-cell .val {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--cv-text-2);+ }+ .cv-perf-cell.up {+ background: var(--cv-green-soft);+ }+ .cv-perf-cell.up .val {+ color: var(--cv-green);+ }+ .cv-perf-cell.down {+ background: var(--cv-red-soft);+ }+ .cv-perf-cell.down .val {+ color: var(--cv-red);+ }++ /* ── Supply bar ── */+ .cv-supply-card {+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ box-shadow: var(--cv-shadow-card);+ padding: 1.25rem;+ }+ .cv-supply-row {+ display: flex;+ flex-wrap: wrap;+ justify-content: space-between;+ gap: 0.5rem 1rem;+ font-size: 0.8125rem;+ color: var(--cv-text-2);+ }+ .cv-supply-track {+ height: 10px;+ border-radius: 999px;+ background: var(--cv-surface-3);+ overflow: hidden;+ margin: 0.625rem 0 0;+ }+ .cv-supply-fill {+ height: 100%;+ border-radius: 999px;+ background: var(--cv-accent);+ transition: width 0.4s ease;+ }+ .cv-supply-meta {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem 1.5rem;+ margin-top: 0.875rem;+ font-size: 0.8125rem;+ color: var(--cv-text-3);+ }+ .cv-supply-meta strong {+ color: var(--cv-text);+ font-weight: 600;+ }+ .cv-supply-meta strong.cv-up {+ color: var(--cv-green);+ }+ .cv-supply-meta strong.cv-down {+ color: var(--cv-red);+ }++ /* ── ATH / ATL cards ── */+ .cv-extremes-grid {+ display: grid;+ gap: 0.75rem;+ }+ @media (min-width: 640px) {+ .cv-extremes-grid {+ grid-template-columns: repeat(2, 1fr);+ }+ }+ .cv-extreme {+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ box-shadow: var(--cv-shadow-card);+ padding: 1.25rem;+ transition: box-shadow 0.2s, border-color 0.2s;+ }+ .cv-extreme:hover {+ box-shadow: var(--cv-shadow-card-hover);+ border-color: var(--cv-border-hover);+ }+ .cv-extreme .label {+ font-size: 0.7rem;+ font-weight: 500;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--cv-text-3);+ margin: 0 0 0.25rem;+ }+ .cv-extreme .value {+ font-size: 1.375rem;+ font-weight: 700;+ color: var(--cv-text);+ margin: 0;+ }+ .cv-extreme .sub {+ font-size: 0.8125rem;+ color: var(--cv-text-3);+ margin: 0.25rem 0 0;+ }++ /* ── Sentiment vote split ── */+ .cv-sent-card {+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ box-shadow: var(--cv-shadow-card);+ padding: 1.25rem;+ }+ .cv-sent-row {+ display: flex;+ justify-content: space-between;+ gap: 1rem;+ font-size: 0.875rem;+ font-weight: 600;+ margin-bottom: 0.5rem;+ }+ .cv-sent-bar {+ display: flex;+ height: 10px;+ border-radius: 999px;+ overflow: hidden;+ background: var(--cv-surface-3);+ }+ .cv-sent-bar .up {+ background: var(--cv-green);+ transition: width 0.4s ease;+ }+ .cv-sent-bar .down {+ background: var(--cv-red);+ transition: width 0.4s ease;+ }+ .cv-sent-watch {+ font-size: 0.8125rem;+ color: var(--cv-text-3);+ margin: 0.875rem 0 0;+ }+ .cv-sent-watch strong {+ color: var(--cv-text);+ font-weight: 600;+ }++ /* ── Community & developer grids ── */+ .cv-dc-wrap {+ display: grid;+ gap: 2rem;+ }+ @media (min-width: 768px) {+ .cv-dc-wrap.two {+ grid-template-columns: 1fr 1fr;+ gap: 1.5rem;+ }+ }+ .cv-dc-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.75rem;+ }+ @media (min-width: 640px) {+ .cv-dc-grid {+ grid-template-columns: repeat(3, 1fr);+ }+ }++ /* ── Markets (tickers) table ── */+ .cv-mkt-x {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ color: inherit;+ text-decoration: none;+ }+ .cv-mkt-x img {+ width: 20px;+ height: 20px;+ border-radius: 50%;+ flex-shrink: 0;+ background: var(--cv-surface-3);+ }+ .cv-mkt-x .nm {+ font-weight: 500;+ color: var(--cv-text);+ max-width: 140px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ a.cv-mkt-x:hover .nm,+ a.cv-mkt-x:focus-visible .nm {+ color: var(--cv-accent);+ }+ a.cv-mkt-x:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+ border-radius: var(--cv-radius-sm);+ }+ .cv-mkt-pair {+ color: var(--cv-text-2);+ text-decoration: none;+ transition: color 0.15s;+ }+ a.cv-mkt-pair:hover,+ a.cv-mkt-pair:focus-visible {+ color: var(--cv-accent);+ }+ a.cv-mkt-pair:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+ border-radius: var(--cv-radius-sm);+ }+ .cv-trust {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ font-size: 0.8125rem;+ color: var(--cv-text-2);+ }+ .cv-trust .dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ flex-shrink: 0;+ }+ .cv-trust .dot.green {+ background: var(--cv-green);+ }+ .cv-trust .dot.yellow {+ background: #eab308; /* no yellow token in the cv palette */+ }+ .cv-trust .dot.red {+ background: var(--cv-red);+ }+ .cv-table tr.cv-stale td {+ opacity: 0.55;+ }+ .cv-mkt-error {+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ background: var(--cv-surface);+ color: var(--cv-text-2);+ padding: 2rem 1.5rem;+ text-align: center;+ font-size: 0.875rem;+ }+ .cv-mkt-error button,+ .cv-load-more {+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-weight: 600;+ color: var(--cv-text);+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ padding: 0.5rem 1.125rem;+ transition: border-color 0.15s, background 0.15s;+ }+ .cv-load-more {+ display: block;+ margin: 1rem auto 0;+ }+ .cv-mkt-error button:hover,+ .cv-load-more:hover {+ border-color: var(--cv-border-hover);+ background: var(--cv-surface-3);+ }+ .cv-mkt-error button:focus-visible,+ .cv-load-more:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+ }+ .cv-load-more[disabled] {+ opacity: 0.6;+ cursor: default;+ }++ /* Sub-heading inside the community/developer split. */+ .cv-h3 {+ font-size: 0.8125rem;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--cv-text-3);+ margin: 0 0 0.75rem;+ }++ @media (prefers-reduced-motion: reduce) {+ .cv-perf-cell,+ .cv-extreme,+ .cv-supply-fill,+ .cv-sent-bar .up,+ .cv-sent-bar .down {+ transition: none;+ }+ }+ </style></head><body><header><div id="nav-container"></div></header>@@ -58,9 +398,27 @@<!-- Interactive price chart with time-range selector. --><section id="cv-chart" aria-label="Price chart"></section>+ <!-- Price performance matrix: 1h → 1y colored change cells. -->+ <section id="cv-perf" class="cv-section" aria-label="Price performance"></section>+<!-- Market stats grid. --><section id="cv-stats" class="cv-section" aria-label="Market stats"></section>+ <!-- Circulating vs max supply bar + Mkt Cap/FDV ratio. -->+ <section id="cv-supply" class="cv-section" aria-label="Supply"></section>++ <!-- ATH/ATL cards with drawdown and recovery multiple. -->+ <section id="cv-extremes" class="cv-section" aria-label="All-time high and low"></section>++ <!-- Bullish/bearish vote split + watchlist count. Hidden when unvoted. -->+ <section id="cv-sentiment" class="cv-section" aria-label="Community sentiment"></section>++ <!-- Community followings + developer repo activity. Hidden when untracked. -->+ <section id="cv-devcom" class="cv-section" aria-label="Community and developer activity"></section>++ <!-- Exchange listings table from /api/coin/tickers, paginated. -->+ <section id="cv-markets" class="cv-section" aria-label="Markets"></section>+<!-- Related news from the live aggregator. --><section id="cv-news" class="cv-section" aria-label="Related news"></section>diff --git a/pages/exchange.html b/pages/exchange.htmlnew file mode 100644index 000000000..0f0537d01--- /dev/null+++ b/pages/exchange.html@@ -0,0 +1,93 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Exchange · three.ws</title>+ <meta+ name="description"+ content="A rich profile for any crypto exchange — trust score, 24h volume, open interest, markets, and volume history. Real CoinGecko data, no API key."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/exchanges" />+ <meta property="og:title" content="Exchange · three.ws" />+ <meta+ property="og:description"+ content="Trust score, 24h trading volume, markets, and volume history for any crypto exchange. Real CoinGecko data."+ />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Exchange · three.ws" />+ <meta+ name="twitter:description"+ content="Trust score, 24h trading volume, markets, and volume history for any crypto exchange."+ />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/exchange-page.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/exchanges" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container" id="ex-main" aria-busy="true">+ <!-- Breadcrumbs -->+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/markets">Markets</a>+ <span class="sep" aria-hidden="true">/</span>+ <a href="/exchanges">Exchanges</a>+ <span class="sep" aria-hidden="true">/</span>+ <span class="here" id="ex-crumb-name">…</span>+ </nav>++ <!-- Hero: logo, name, trust score, rank, meta chips, description, links. -->+ <section id="ex-hero" aria-label="Exchange overview"></section>++ <!-- Stat cards: 24h volume, normalized volume / open interest, markets, rank. -->+ <section id="ex-stats" class="cv-section" aria-label="Exchange stats"></section>++ <!-- Volume history chart (spot venues only). -->+ <section id="ex-chart" aria-label="Volume chart"></section>++ <!-- Markets / contracts table. -->+ <section id="ex-markets" class="cv-section" aria-label="Markets"></section>++ <p class="cv-updated" id="ex-updated" hidden></p>+ </main>++ <script type="module" src="/src/exchange-page.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/markets-news.html b/pages/markets-news.htmlindex 8faf9b74e..318f212cf 100644--- a/pages/markets-news.html+++ b/pages/markets-news.html@@ -18,18 +18,18 @@</script><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>Crypto News · three.ws</title>+ <title>Crypto News Briefing · three.ws</title><metaname="description"- content="Live crypto news aggregated from 192 publisher feeds — CoinDesk, The Block, Decrypt, CoinTelegraph and more. Filter by category, search headlines, and open any story in a rich reader."+ content="Your crypto briefing — live headlines from 192 publisher feeds, an AI-clustered daily digest, breaking-news ticker, and saved stories. Filter by Featured, Trending, DeFi, Bitcoin, Ethereum, and more."/><meta property="og:type" content="website" /><meta property="og:site_name" content="three.ws" /><meta property="og:url" content="https://three.ws/markets/news" />- <meta property="og:title" content="Crypto News · three.ws" />+ <meta property="og:title" content="Crypto News Briefing · three.ws" /><metaproperty="og:description"- content="Live crypto news aggregated from 192 publisher feeds, filterable by category and searchable — with a rich reader for every story."+ content="Your crypto briefing — live headlines from 192 publisher feeds, an AI daily digest, breaking ticker, and saved stories."/><metaproperty="og:image"@@ -39,10 +39,10 @@<meta property="og:image:height" content="630" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:site" content="@trythreews" />- <meta name="twitter:title" content="Crypto News · three.ws" />+ <meta name="twitter:title" content="Crypto News Briefing · three.ws" /><metaname="twitter:description"- content="Live crypto news aggregated from 192 publisher feeds, filterable by category and searchable."+ content="Your crypto briefing — live headlines from 192 publisher feeds, an AI daily digest, breaking ticker, and saved stories."/><metaname="twitter:image"@@ -67,25 +67,72 @@<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="Crypto News — three.ws" />- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Crypto News","description":"Live crypto news aggregated from 192 publisher feeds — filterable by category, searchable, with a rich reader for every story.","url":"https://three.ws/markets/news","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}]}</script>+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Crypto News Briefing","description":"Your crypto briefing — live headlines aggregated from 192 publisher feeds, an AI-clustered daily digest, a breaking-news ticker, and saved stories.","url":"https://three.ws/markets/news","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}]}</script></head><body><header><div id="nav-container"></div></header><script src="/nav.js"></script>- <main class="cv-container">+ <main class="cv-container nwb"><nav class="cv-crumbs" aria-label="Breadcrumb"><a href="/markets">Markets</a><span class="sep">/</span><span class="here">News</span></nav>- <h1 class="cv-h1">Crypto News</h1>- <p class="cv-sub">- Live headlines aggregated from 192 publisher feeds across the industry — majors,- research desks, on-chain analysts, exchanges, and regulators. Click any story for a- rich reader with summary, key points, and related coverage.- </p>++ <!-- Briefing masthead: title + date left, search/filters/AI right. -->+ <header class="nwb-head">+ <div class="nwb-head-id">+ <h1 class="cv-h1">Your briefing</h1>+ <p class="nwb-date" id="nwb-date"></p>+ </div>+ <div class="nwb-head-tools">+ <div class="cv-search nwb-search">+ <input+ id="nw-search"+ type="search"+ placeholder="Search news… (e.g., Ethereum ETF, DeFi hack)"+ aria-label="Search news"+ autocomplete="off"+ />+ </div>+ <div class="nwb-controls">+ <select id="nw-lang" class="nw-select" aria-label="Filter by language">+ <option value="en">English</option>+ </select>+ <select id="nw-source" class="nw-select" aria-label="Filter by source">+ <option value="">All sources</option>+ </select>+ <a class="nwb-ask" href="/markets/digest">+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M8 1.5c-3.6 0-6.5 2.5-6.5 5.6 0 1.8 1 3.4 2.5 4.4v3l2.8-1.6c.4.1.8.1 1.2.1 3.6 0 6.5-2.5 6.5-5.9S11.6 1.5 8 1.5z"/></svg>+ Ask AI about this+ </a>+ </div>+ </div>+ </header>++ <!-- Primary briefing tabs. Hydrated by src/markets-news.js. -->+ <div id="nw-tabs" class="nwb-tabs" role="group" aria-label="Briefing sections"></div>++ <!-- Full category picker, revealed by the "All" tab. -->+ <div id="nwb-cats" class="nw-tabs nwb-cats" role="group" aria-label="All news categories" hidden></div>++ <!-- Breaking-news ticker. Hidden until a story <45 min old exists. -->+ <div id="nwb-breaking" class="nwb-break" role="region" aria-label="Breaking news" hidden></div>++ <!-- Today's AI Briefing — narratives from /api/news/digest. -->+ <section id="nwb-brief" class="nwb-brief" aria-label="Today's AI briefing" hidden></section>++ <p id="nw-count" class="nw-count" role="status"></p>++ <!-- Top stories (hero + rail), trending narratives, saved stories, and+ the latest grid all render inside. Hydrated by src/markets-news.js. -->+ <section id="nw-feed" class="cv-section nwb-feed" aria-label="News feed" aria-live="polite"></section>++ <div style="display: flex; justify-content: center; margin: 1.5rem 0 0">+ <button id="nw-more" class="cv-load-more" type="button" hidden>Load more stories</button>+ </div><!-- Sibling market surfaces. -->- <nav class="cv-tools" aria-label="Market tools">+ <nav class="cv-tools" aria-label="Market tools" style="margin-top: 2rem"><a class="cv-pill" href="/markets">Markets Hub</a><a class="cv-pill" href="/markets/news" aria-current="page">News</a><a class="cv-pill" href="/markets/digest">Digest</a>@@ -97,40 +144,9 @@<a class="cv-pill" href="/gas">Gas</a></nav>- <!-- Category tabs. Hydrated by src/markets-news.js. -->- <div id="nw-tabs" class="nw-tabs" role="group" aria-label="News categories"></div>-- <!-- Search + language + source filters. -->- <div class="nw-toolbar">- <div class="cv-search">- <input- id="nw-search"- type="search"- placeholder="Search headlines — bitcoin etf, solana, hack…"- aria-label="Search news"- autocomplete="off"- />- </div>- <select id="nw-lang" class="nw-select" aria-label="Filter by language">- <option value="en">English</option>- </select>- <select id="nw-source" class="nw-select" aria-label="Filter by source">- <option value="">All sources</option>- </select>- </div>-- <p id="nw-count" class="nw-count" role="status"></p>-- <!-- Lead story + article grid. Hydrated by src/markets-news.js. -->- <section id="nw-feed" class="cv-section" aria-label="News feed" aria-live="polite"></section>-- <div style="display: flex; justify-content: center; margin: 1.5rem 0 0">- <button id="nw-more" class="cv-load-more" type="button" hidden>Load more stories</button>- </div>-<!-- Archive cross-link. --><section class="cv-section" aria-label="Historical archive">- <div class="art-preview-note" style="margin-top: 2rem">+ <div class="art-preview-note" style="margin-top: 1.25rem"><span aria-hidden="true">🗞</span><span>Looking for older coverage? Thediff --git a/pages/yields.html b/pages/yields.htmlnew file mode 100644index 000000000..793a14910--- /dev/null+++ b/pages/yields.html@@ -0,0 +1,226 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>DeFi Yields · three.ws</title>+ <meta+ name="description"+ content="Explore live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoins and TVL, sort by APY or size, and open any pool for its full APY and TVL history. Data from DeFiLlama."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/yields" />+ <meta property="og:title" content="DeFi Yields · three.ws" />+ <meta+ property="og:description"+ content="Explore live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoins and TVL, sort by APY or size, and chart any pool's APY and TVL history."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=DeFi+Yields&d=Explore+live+DeFi+yield+pools+across+every+chain+and+protocol+%E2%80%94+filter+by+chain%2C+project%2C+stablecoins+and+TVL%2C+sort+by+APY+or+size%2C+and+chart+any+pool%27s+history&p=%2Fyields"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="DeFi Yields · three.ws" />+ <meta+ name="twitter:description"+ content="Explore live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoins and TVL, sort by APY or size, and chart any pool's history."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=DeFi+Yields&d=Explore+live+DeFi+yield+pools+across+every+chain+and+protocol+%E2%80%94+filter+by+chain%2C+project%2C+stablecoins+and+TVL%2C+sort+by+APY+or+size%2C+and+chart+any+pool%27s+history&p=%2Fyields"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/yields.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/yields" />+ <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="DeFi Yields — three.ws" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "DeFi Yields",+ "description": "Explore live DeFi yield pools across every chain and protocol. Filter by chain, project, stablecoins and minimum TVL, sort by APY or TVL, and open any pool to chart its APY and TVL history. Data sourced from DeFiLlama.",+ "url": "https://three.ws/yields",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=DeFi+Yields&d=Explore+live+DeFi+yield+pools+across+every+chain+and+protocol%2C+filter+by+chain%2C+project%2C+stablecoins+and+TVL%2C+and+chart+any+pool%27s+history&p=%2Fyields"+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/markets">Markets</a><span class="sep">/</span+ ><span class="here">DeFi Yields</span>+ </nav>+ <h1 class="cv-h1">DeFi Yields</h1>+ <p class="cv-sub">+ Live yield pools across every chain and protocol. Filter by chain, project,+ stablecoins and minimum TVL, sort by APY or size, then open any pool to chart its+ full APY and TVL history.+ </p>++ <!-- Whole-dataset stats. Hydrated by src/yields.js. -->+ <section class="cv-stats-grid yl-stats" aria-label="DeFi yield overview" id="yl-stats">+ <div class="cv-stat-card">+ <div>+ <p class="label">Pools Tracked</p>+ <p class="value" id="yl-stat-pools"><span class="cv-skel yl-stat-skel"></span></p>+ </div>+ <span class="icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/></svg>+ </span>+ </div>+ <div class="cv-stat-card">+ <div>+ <p class="label">Total TVL</p>+ <p class="value" id="yl-stat-tvl"><span class="cv-skel yl-stat-skel"></span></p>+ </div>+ <span class="icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>+ </span>+ </div>+ <div class="cv-stat-card">+ <div>+ <p class="label">Median APY</p>+ <p class="value" id="yl-stat-apy"><span class="cv-skel yl-stat-skel"></span></p>+ </div>+ <span class="icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>+ </span>+ </div>+ </section>++ <!-- Filter controls. Wired by src/yields.js. All state syncs to the URL. -->+ <div class="scr-controls yl-controls">+ <div class="cv-search yl-search" id="yl-search">+ <span class="mag" aria-hidden="true">+ <svg+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ >+ <circle cx="11" cy="11" r="8" />+ <path d="m21 21-4.3-4.3" />+ </svg>+ </span>+ <input+ id="yl-search-input"+ type="search"+ placeholder="Filter by symbol, project or chain…"+ autocomplete="off"+ spellcheck="false"+ aria-label="Filter pools by symbol, project or chain"+ />+ </div>++ <label class="scr-field">+ <span>Chain</span>+ <select id="yl-chain" aria-label="Filter by chain">+ <option value="">All chains</option>+ </select>+ </label>++ <label class="scr-field">+ <span>Project</span>+ <select id="yl-project" aria-label="Filter by project">+ <option value="">All projects</option>+ </select>+ </label>++ <label class="scr-field">+ <span>Min TVL</span>+ <select id="yl-mintvl" aria-label="Minimum total value locked">+ <option value="0">Any</option>+ <option value="10000">$10K+</option>+ <option value="100000">$100K+</option>+ <option value="1000000">$1M+</option>+ <option value="10000000">$10M+</option>+ </select>+ </label>++ <label class="yl-toggle">+ <input type="checkbox" id="yl-stable" />+ <span>Stablecoins only</span>+ </label>++ <div class="hm-seg yl-seg" role="group" aria-label="Sort order" id="yl-sort">+ <button type="button" data-sort="tvl" aria-pressed="true">TVL</button>+ <button type="button" data-sort="apy" aria-pressed="false">APY</button>+ </div>++ <button type="button" class="scr-reset" id="yl-reset">Reset</button>+ </div>++ <div class="scr-meta">+ <span id="yl-count" class="scr-count" aria-live="polite"></span>+ <div class="cv-pills">+ <a class="cv-pill" href="/screener">Screener</a>+ <a class="cv-pill" href="/markets">Markets</a>+ <a class="cv-pill" href="/heatmap">Heatmap</a>+ </div>+ </div>++ <!-- Results table. Hydrated by src/yields.js. -->+ <section id="yl-table" aria-label="DeFi yield pools"></section>++ <div class="yl-more-wrap" id="yl-more-wrap" hidden>+ <button type="button" class="yl-more" id="yl-more">Load more pools</button>+ </div>++ <p class="cv-updated" id="yl-updated"></p>+ <p class="yl-attribution">+ Yield data from+ <a href="https://defillama.com/yields" rel="noopener noreferrer" target="_blank">DeFiLlama</a>. APY figures+ are protocol-reported and vary with pool conditions — not financial advice.+ </p>+ </main>++ <script type="module" src="/src/yields.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex b57a0c0d9..fa910c41d 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,32 @@{- "generated_at": "2026-07-10T18:59:18.164Z",+ "generated_at": "2026-07-11T00:26:13.847Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-07-11",+ "type": "launch",+ "title": "DeFi Yields Explorer",+ "summary": "Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.",+ "link": "/yields",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-11",+ "type": "update",+ "title": "Richer coin pages, plus new exchange, category, and DeFi-yields detail pages",+ "summary": "Every coin page now shows far more of what the data already offers: a 1h-to-1y price-performance matrix, a circulating-vs-max supply bar with the market-cap/FDV ratio, all-time high and low with the drawdown and recovery multiple, the community bullish/bearish sentiment split, GitHub and social activity, and a full exchange-listings table with spread, order-book depth, and a trust rating for each venue. Exchanges and crypto categories, which used to only send you off-site or filter a table, now have their own detail pages — an exchange page with a trust badge, wash-volume-adjusted volume, a volume-history chart, and its markets, and a category page with the sector's rank, stats, and full coin list. And a brand-new DeFi Yields explorer covers roughly 15,000 live pools across every chain and protocol, filterable and sortable, each with its own APY and TVL history chart. All of it is real, key-free data.",+ "link": "/yields",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-07-10","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex ddbb10279..a042289b3 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,22 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>DeFi Yields Explorer</title>+ <link>https://three.ws/yields</link>+ <guid isPermaLink="false">2026-07-11:DeFi Yields Explorer</guid>+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.</description>+ </item>+ <item>+ <title>Richer coin pages, plus new exchange, category, and DeFi-yields detail pages</title>+ <link>https://three.ws/yields</link>+ <guid isPermaLink="false">2026-07-11:Richer coin pages, plus new exchange, category, and DeFi-yields detail pages</guid>+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Every coin page now shows far more of what the data already offers: a 1h-to-1y price-performance matrix, a circulating-vs-max supply bar with the market-cap/FDV ratio, all-time high and low with the drawdown and recovery multiple, the community bullish/bearish sentiment split, GitHub and social activity, and a full exchange-listings table with spread, order-book depth, and a trust rating for each venue. Exchanges and crypto categories, which used to only send you off-site or filter a table, now have their own detail pages — an exchange page with a trust badge, wash-volume-adjusted volume, a volume-history chart, and its markets, and a category page with the sector's rank, stats, and full coin list. And a brand-new DeFi Yields explorer covers roughly 15,000 live pools across every chain and protocol, filterable and sortable, each with its own APY and TVL history chart. All of it is real, key-free data.</description>+ </item><item><title>Crypto News</title><link>https://three.ws/markets/news</link>diff --git a/public/features.json b/public/features.jsonindex c38351e1b..da0088fbd 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-10T18:59:18.151Z",+ "generated_at": "2026-07-11T00:26:13.834Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1566,6 +1566,16 @@"tags": [],"showcase": false},+ {+ "path": "/yields",+ "title": "DeFi Yields Explorer",+ "description": "Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.",+ "added": "2026-07-11",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/bnb","title": "BNB Chain — Three Genuinely-Unique Demos",diff --git a/public/llms-full.txt b/public/llms-full.txtindex ecdc12bd2..dade2c4fe 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -951,6 +951,12 @@ URL: https://three.ws/stablecoinsEvery major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.+### DeFi Yields Explorer++URL: https://three.ws/yields++Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.+### BNB Chain — Three Genuinely-Unique DemosURL: https://three.ws/bnbdiff --git a/public/llms.txt b/public/llms.txtindex c610e7e7f..6314cbe14 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -174,6 +174,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [DeFi TVL & Top Protocols](https://three.ws/defi): Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.- [Blockchain TVL by Chain](https://three.ws/chains): A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.- [Stablecoins Market Cap & Peg Health](https://three.ws/stablecoins): Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.+- [DeFi Yields Explorer](https://three.ws/yields): Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.- [BNB Chain — Three Genuinely-Unique Demos](https://three.ws/bnb): The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.- [BNB Chain Live Block Race — 0.45s vs Base, Ethereum, Solana](https://three.ws/bnb-latency): A live, honest race: BNB Chain, Base, Ethereum, and Solana block times measured fresh off real public RPCs every few seconds, with a rolling sparkline per lane. No wallet, no payment, no hardcoded numbers — a lane that goes quiet shows 'reconnecting' while the others keep racing.- [Vault — Buy & Unlock Encrypted 3D Models on BNB Chain](https://three.ws/vault): Browse encrypted 3D listings, buy access with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle, then unlock and view the model — decrypted entirely client-side, the raw key never leaves your browser.diff --git a/public/nav-data.js b/public/nav-data.jsindex 4933c2c0c..b16d24138 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -412,6 +412,11 @@ export const NAV_GROUPS = [href: '/stablecoins',desc: 'Stablecoin market caps and peg health across every major issuer',},+ {+ title: 'DeFi Yields',+ href: '/yields',+ desc: 'Explore ~15k live yield pools — APY, TVL, and per-pool history from DeFiLlama',+ },{title: 'Coin Intelligence',href: '/coin-intel',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex d1be26a28..2b5cb7021 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 415 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 416 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 415 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 416 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -718,7 +718,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>105</span></h2>+ <h2>Crypto<span class="sm-count" data-count>106</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -1198,6 +1198,13 @@<span class="sm-desc">Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.</span></a></li>+ <li>+ <a href="/yields">+ <span class="sm-title">DeFi Yields Explorer</span>+ <span class="sm-path">/yields</span>+ <span class="sm-desc">Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.</span>+ </a>+ </li><li><a href="/bnb"><span class="sm-title">BNB Chain — Three Genuinely-Unique Demos</span>diff --git a/scripts/check-news-tmp.mjs b/scripts/check-news-tmp.mjsnew file mode 100644index 000000000..08f734d3e--- /dev/null+++ b/scripts/check-news-tmp.mjs@@ -0,0 +1,63 @@+import { chromium } from 'playwright';++const BASE = 'http://localhost:8090';+const OUT = '/tmp/claude-1000/-workspaces-three-ws/7202a201-2f6a-47fa-a984-64069f93d10d/scratchpad';+const browser = await chromium.launch();+const errors = [];+const page = await browser.newPage({ viewport: { width: 1440, height: 1100 } });+page.on('console', (m) => {+ if (m.type() === 'error') errors.push(m.text().slice(0, 200));+});+page.on('pageerror', (e) => errors.push(`PAGEERROR: ${e.message.slice(0, 200)}`));++await page.goto(`${BASE}/markets/news`, { waitUntil: 'networkidle', timeout: 60000 });+await page.waitForTimeout(3000);+await page.screenshot({ path: `${OUT}/news-desktop.png`, fullPage: false });++// Count real vs fallback media+const stats = await page.evaluate(() => {+ const imgs = [...document.querySelectorAll('.nw-media img, .nw-hero-media img')];+ return {+ title: document.querySelector('.cv-h1')?.textContent,+ date: document.getElementById('nwb-date')?.textContent,+ tabs: [...document.querySelectorAll('.nwb-tab span')].map((s) => s.textContent),+ breakingVisible: !document.getElementById('nwb-breaking').hidden,+ briefVisible: !document.getElementById('nwb-brief').hidden,+ briefPoints: document.querySelectorAll('.nwb-brief-list li').length,+ heroCount: document.querySelectorAll('.nw-hero').length,+ railRows: document.querySelectorAll('.nwb-rail .nw-row').length,+ gridCards: document.querySelectorAll('.nw-grid .nw-card').length,+ imgsLoaded: imgs.filter((i) => i.complete && i.naturalWidth > 0).length,+ imgsTotal: imgs.length,+ fallbackTiles: document.querySelectorAll('.nw-fallback').length,+ stars: document.querySelectorAll('.nw-star').length,+ };+});+console.log(JSON.stringify(stats, null, 1));++// Exercise tabs: featured, trending, saved+for (const tab of ['featured', 'trending', 'saved', 'all']) {+ await page.click(`[data-tab="${tab}"]`);+ await page.waitForTimeout(tab === 'trending' ? 8000 : 2500);+ await page.screenshot({ path: `${OUT}/news-${tab}.png` });+ console.log(tab, 'url:', page.url());+}+// star a story then check saved+await page.click('[data-tab="headlines"]');+await page.waitForTimeout(2500);+await page.click('.nw-star');+await page.click('[data-tab="saved"]');+await page.waitForTimeout(500);+console.log('saved rows after star:', await page.locator('.nwb-saved .nw-row').count());+await page.screenshot({ path: `${OUT}/news-saved-after-star.png` });++// mobile+const mob = await browser.newPage({ viewport: { width: 375, height: 800 } });+await mob.goto(`${BASE}/markets/news`, { waitUntil: 'networkidle', timeout: 60000 });+await mob.waitForTimeout(2500);+await mob.screenshot({ path: `${OUT}/news-mobile.png`, fullPage: false });+const hscroll = await mob.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1);+console.log('mobile horizontal scroll:', hscroll);++console.log('CONSOLE ERRORS:', errors.length ? errors : 'none');+await browser.close();diff --git a/scripts/check-overflow-tmp.mjs b/scripts/check-overflow-tmp.mjsnew file mode 100644index 000000000..327d7e957--- /dev/null+++ b/scripts/check-overflow-tmp.mjs@@ -0,0 +1,19 @@+import { chromium } from 'playwright';+const browser = await chromium.launch();+const page = await browser.newPage({ viewport: { width: 375, height: 800 } });+await page.goto('http://localhost:8090/markets/news', { waitUntil: 'networkidle', timeout: 60000 });+await page.waitForTimeout(2500);+const offenders = await page.evaluate(() => {+ const docW = document.documentElement.clientWidth;+ const out = [];+ for (const el of document.querySelectorAll('*')) {+ const r = el.getBoundingClientRect();+ if (r.right > docW + 1 && r.width > 20) {+ out.push(`${el.tagName}.${[...el.classList].join('.')} right=${Math.round(r.right)} w=${Math.round(r.width)}`);+ }+ if (out.length > 12) break;+ }+ return out;+});+console.log(offenders.join('\n'));+await browser.close();diff --git a/src/categories.js b/src/categories.jsindex 10bce3b05..4b7b10669 100644--- a/src/categories.js+++ b/src/categories.js@@ -137,7 +137,7 @@ function renderTable() {const rows = sortedCategories().map((c) => {- const href = `/coins?category=${encodeURIComponent(c.id)}`;+ const href = `/category/${encodeURIComponent(c.id)}`;return `<tr data-href="${esc(href)}"><td class="rank hide-sm cv-mono">${c.rank ?? '—'}</td>diff --git a/src/category-page.css b/src/category-page.cssnew file mode 100644index 000000000..397bf0e3b--- /dev/null+++ b/src/category-page.css@@ -0,0 +1,281 @@+/*+ * /category/:id — crypto sector detail page. Reuses the shared cv-* token,+ * card, table, and stat-card system from coin-pages.css; this file adds only+ * the page-specific pieces: the hero head with its stacked coin avatars, the+ * stat-card info tooltip, the related-category cards, and the footer link.+ */++/* ── Hero ──────────────────────────────────────────────────────────────────── */++.cat-hero-head {+ display: flex;+ align-items: center;+ gap: 1rem;+ margin-bottom: 1.25rem;+}++.cat-hero-avatars {+ display: inline-flex;+ align-items: center;+ flex-shrink: 0;+}+.cat-hero-avatars img {+ width: 34px;+ height: 34px;+ border-radius: 50%;+ background: var(--cv-surface-3);+ border: 2px solid var(--cv-surface);+ object-fit: cover;+}+.cat-hero-avatars img + img {+ margin-left: -12px;+}++.cat-hero-title {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem;+}+.cat-hero-title h1 {+ font-family: var(--cv-font-serif);+ font-size: 1.875rem;+ font-weight: 700;+ margin: 0;+ color: var(--cv-text);+ line-height: 1.1;+}+@media (min-width: 768px) {+ .cat-hero-title h1 {+ font-size: 2.25rem;+ }+}+.cat-hero-kicker {+ margin: 0.375rem 0 0;+ font-size: 0.7rem;+ font-weight: 500;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--cv-text-3);+}++.cat-desc {+ max-width: 68ch;+ margin-bottom: 0.5rem;+}++/* ── Stat cards ────────────────────────────────────────────────────────────── */++.cat-stat-grid {+ display: grid;+ gap: 1rem;+ grid-template-columns: 1fr;+}+@media (min-width: 560px) {+ .cat-stat-grid {+ grid-template-columns: repeat(2, 1fr);+ }+}+@media (min-width: 900px) {+ .cat-stat-grid {+ grid-template-columns: repeat(4, 1fr);+ }+}++/* Color the 24h-change value — beats `.cv-stat-card .value`'s base color. */+.cv-stat-card .value.cv-up {+ color: var(--cv-green);+}+.cv-stat-card .value.cv-down {+ color: var(--cv-red);+}++/* Info tooltip on the "share of categorized market" card. */+.cat-info {+ display: inline-flex;+ align-items: center;+ position: relative;+ margin-left: 0.3rem;+ color: var(--cv-text-3);+ cursor: help;+ vertical-align: middle;+}+.cat-info svg {+ width: 0.875rem;+ height: 0.875rem;+ display: block;+}+.cat-info:hover,+.cat-info:focus-visible {+ color: var(--cv-accent);+ outline: none;+}+.cat-info::after {+ content: attr(data-tip);+ position: absolute;+ bottom: calc(100% + 8px);+ left: 50%;+ transform: translateX(-50%) translateY(4px);+ width: max-content;+ max-width: 15rem;+ padding: 0.5rem 0.625rem;+ border-radius: var(--cv-radius-md);+ background: var(--cv-text);+ color: var(--cv-surface);+ font-size: 0.75rem;+ font-weight: 400;+ line-height: 1.35;+ letter-spacing: 0;+ text-transform: none;+ white-space: normal;+ box-shadow: var(--cv-shadow-card-hover);+ opacity: 0;+ pointer-events: none;+ transition:+ opacity 0.15s ease,+ transform 0.15s ease;+ z-index: 5;+}+.cat-info:hover::after,+.cat-info:focus-visible::after {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+}++/* ── Coins table header row ────────────────────────────────────────────────── */++.cat-coins-bar {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 1rem;+ margin-bottom: 1rem;+}+.cat-coins-count {+ font-size: 0.8125rem;+ color: var(--cv-text-3);+ flex-shrink: 0;+}++.cat-table-error {+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ background: var(--cv-surface);+ color: var(--cv-text-2);+ padding: 2rem 1.5rem;+ text-align: center;+ font-size: 0.875rem;+}+.cat-table-error button {+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-weight: 600;+ color: var(--cv-text);+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ padding: 0.5rem 1.125rem;+ transition:+ border-color 0.15s,+ background 0.15s;+}+.cat-table-error button:hover {+ border-color: var(--cv-border-hover);+ background: var(--cv-surface-3);+}+.cat-table-error button:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++/* ── Related categories ────────────────────────────────────────────────────── */++.cat-rel-grid {+ display: grid;+ gap: 0.75rem;+ grid-template-columns: 1fr;+}+@media (min-width: 560px) {+ .cat-rel-grid {+ grid-template-columns: repeat(2, 1fr);+ }+}+@media (min-width: 900px) {+ .cat-rel-grid {+ grid-template-columns: repeat(4, 1fr);+ }+}+.cat-rel-card {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ padding: 0.875rem 1rem;+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ background: var(--cv-surface);+ box-shadow: var(--cv-shadow-card);+ text-decoration: none;+ transition:+ box-shadow 0.2s,+ border-color 0.2s,+ transform 0.2s;+}+.cat-rel-card:hover {+ box-shadow: var(--cv-shadow-card-hover);+ border-color: var(--cv-border-hover);+ transform: translateY(-2px);+}+.cat-rel-card:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}+.cat-rel-card .nm {+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--cv-text);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.cat-rel-card:hover .nm {+ color: var(--cv-accent);+}+.cat-rel-card .mc {+ font-size: 0.875rem;+ color: var(--cv-text-2);+}+.cat-rel-card .chg {+ font-size: 0.8125rem;+ font-weight: 500;+}+.cat-rel-card .chg.dim {+ color: var(--cv-text-3);+}++/* ── Footer link ───────────────────────────────────────────────────────────── */++.cat-footer-link {+ font-size: 0.875rem;+ color: var(--cv-text-3);+ margin: 0;+}+.cat-footer-link a {+ color: var(--cv-accent);+ text-decoration: none;+ font-weight: 500;+}+.cat-footer-link a:hover,+.cat-footer-link a:focus-visible {+ text-decoration: underline;+}++@media (prefers-reduced-motion: reduce) {+ .cat-rel-card,+ .cat-info::after {+ transition: none;+ }+ .cat-rel-card:hover {+ transform: none;+ }+}diff --git a/src/category-page.js b/src/category-page.jsnew file mode 100644index 000000000..779c81095--- /dev/null+++ b/src/category-page.js@@ -0,0 +1,406 @@+// /category/:id — crypto sector detail page. A hero (name, market-cap rank,+// description) over four stat cards, then the sortable table of coins that make+// up the sector, and a strip of the rank-nearest related categories. The sector+// profile comes from /api/coin/category?id=<slug>; the coins table proxies+// /api/coin/markets?category=<slug> (same shared coin-row shape as /coins). All+// real endpoints, cached server-side — never mocked.++import { formatUsd, formatPercent, escapeHtml as esc } from './shared/coin-format.js';+import { coinRow, COIN_COLUMNS, coinSortValue } from './shared/market-table.js';++const $ = (id) => document.getElementById(id);++const CATEGORY_ID_RE = /^[a-z0-9-]{1,80}$/;++// The slug lives in the path (/category/layer-1) with a ?id= query fallback so+// the page still resolves if it is ever served without the pretty rewrite.+function categoryIdFromLocation() {+ const m = location.pathname.match(/^\/category\/([a-z0-9-]{1,80})$/);+ if (m) return m[1].toLowerCase();+ const q = (new URLSearchParams(location.search).get('id') || '').trim().toLowerCase();+ return CATEGORY_ID_RE.test(q) ? q : null;+}++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── Hero ─────────────────────────────────────────────────────────────────────++function avatarStack(coins) {+ if (!coins || !coins.length) return '';+ const imgs = coins+ .map((u) => `<img src="${esc(u)}" alt="" loading="lazy" width="34" height="34" data-no-dark-filter />`)+ .join('');+ return `<span class="cat-hero-avatars" aria-hidden="true">${imgs}</span>`;+}++function renderHero(cat) {+ $('cat-crumb').textContent = cat.name;+ const rankChip =+ cat.rank != null+ ? `<span class="cv-rank-badge">#${cat.rank} by market cap</span>`+ : '';+ const desc = cat.description+ ? `<div class="cv-prose cat-desc">${cat.description+ .split(/\n{2,}/)+ .filter((p) => p.trim())+ .slice(0, 4)+ .map((p) => `<p>${esc(p.trim())}</p>`)+ .join('')}</div>`+ : '';+ $('cat-hero').innerHTML = `+ <div class="cat-hero-head">+ ${avatarStack(cat.top_3_coins)}+ <div style="min-width:0">+ <div class="cat-hero-title">+ <h1>${esc(cat.name)}</h1>+ ${rankChip}+ </div>+ <p class="cat-hero-kicker">Crypto category</p>+ </div>+ </div>+ ${desc}`;+}++// ── Stat cards ───────────────────────────────────────────────────────────────++const ICONS = {+ cap: '<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>',+ 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>',+ vol: '<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>',+ 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>',+};++function statCard({ label, value, valueClass, delta, deltaClass, icon, tip }) {+ const tipEl = tip+ ? `<span class="cat-info" tabindex="0" role="note" aria-label="${esc(tip)}" data-tip="${esc(tip)}">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>+ </span>`+ : '';+ return `+ <div class="cv-stat-card">+ <div style="min-width:0">+ <p class="label">${esc(label)}${tipEl}</p>+ <p class="value cv-mono ${valueClass || ''}">${esc(value)}</p>+ ${delta ? `<p class="delta ${deltaClass || ''}">${esc(delta)}</p>` : ''}+ </div>+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>+ </div>`;+}++function renderStats(cat) {+ const change = cat.market_cap_change_24h;+ const changeStr =+ change != null && Number.isFinite(change)+ ? `${change >= 0 ? '▲' : '▼'} ${formatPercent(change)}`+ : '—';+ const cards = [+ statCard({ label: 'Market Cap', value: formatUsd(cat.market_cap), icon: 'cap' }),+ statCard({+ label: '24h Change',+ value: changeStr,+ valueClass: change == null ? '' : change >= 0 ? 'cv-up' : 'cv-down',+ icon: 'trend',+ }),+ statCard({ label: '24h Volume', value: formatUsd(cat.volume_24h), icon: 'vol' }),+ statCard({+ label: 'Share of categorized market',+ value: cat.share_of_total != null ? `${cat.share_of_total.toFixed(1)}%` : '—',+ icon: 'pie',+ tip: "Categories overlap, so shares don't sum to 100%.",+ }),+ ];+ $('cat-stats').innerHTML = `<div class="cat-stat-grid">${cards.join('')}</div>`;+}++// ── Coins table ──────────────────────────────────────────────────────────────++const PER_PAGE = 100;+const MAX_PAGE = 20; // markets.js caps page at 20++const table = {+ coins: [],+ page: 0,+ loading: false,+ done: false,+ error: false,+ sortKey: 'rank',+ sortDir: 'asc',+};++let currentId = null;++function tableSkeleton() {+ $('cat-coins').innerHTML = `+ <h2 class="cv-h2">Coins in this category</h2>+ <div class="cv-table-wrap" style="padding:0.75rem">+ ${Array.from({ length: 10 }, () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>').join('')}+ </div>`;+}++function renderTable() {+ const el = $('cat-coins');+ const { coins, loading, error, done } = table;++ if (!coins.length && loading) {+ tableSkeleton();+ return;+ }+ if (!coins.length && error) {+ el.innerHTML = `+ <h2 class="cv-h2">Coins in this category</h2>+ <div class="cat-table-error">+ <p style="margin:0 0 0.75rem">The coins in this category are temporarily unavailable.</p>+ <button type="button" id="cat-coins-retry">Retry</button>+ </div>`;+ $('cat-coins-retry')?.addEventListener('click', () => {+ table.error = false;+ table.page = 0;+ table.done = false;+ loadCoins();+ });+ return;+ }+ if (!coins.length) {+ el.innerHTML = `+ <h2 class="cv-h2">Coins in this category</h2>+ <div class="cv-empty">+ <p style="margin:0 0 0.5rem">No coins tracked in this category yet.</p>+ <p style="margin:0">Browse every sector on the <a href="/categories">categories index</a>.</p>+ </div>`;+ return;+ }++ const head = COIN_COLUMNS.map((col) => {+ const active = col.key === table.sortKey;+ const arrow = active ? (table.sortDir === 'asc' ? '↑' : '↓') : '↕';+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${table.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ }).join('');++ const sorted = [...coins].sort((a, b) => {+ const va = coinSortValue(a, table.sortKey);+ const vb = coinSortValue(b, table.sortKey);+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;+ return table.sortDir === 'asc' ? cmp : -cmp;+ });++ el.innerHTML = `+ <div class="cat-coins-bar">+ <h2 class="cv-h2" style="margin:0">Coins in this category</h2>+ <span class="cat-coins-count">${coins.length.toLocaleString('en-US')} shown</span>+ </div>+ <div class="cv-table-wrap">+ <table class="cv-table">+ <thead><tr>${head}<th class="hide-xl" aria-hidden="true">7d Chart</th></tr></thead>+ <tbody>${sorted.map(coinRow).join('')}</tbody>+ </table>+ </div>+ ${done ? '' : `<button type="button" class="cv-load-more" id="cat-coins-more"${loading ? ' disabled' : ''}>${loading ? 'Loading…' : 'Load more coins'}</button>`}`;++ el.querySelectorAll('th[data-key]').forEach((th) => {+ const activate = () => {+ const key = th.dataset.key;+ if (key === table.sortKey) {+ table.sortDir = table.sortDir === 'asc' ? 'desc' : 'asc';+ } else {+ table.sortKey = key;+ table.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();+ }+ });+ });++ el.querySelectorAll('tr[data-href]').forEach((tr) => {+ tr.addEventListener('click', (e) => {+ if (e.target.closest('a')) return;+ location.href = tr.dataset.href;+ });+ });++ $('cat-coins-more')?.addEventListener('click', loadCoins);+}++async function loadCoins() {+ if (table.loading || table.done) return;+ table.loading = true;+ renderTable();+ try {+ const next = table.page + 1;+ const { coins } = await getJson(+ `/api/coin/markets?category=${encodeURIComponent(currentId)}&per_page=${PER_PAGE}&page=${next}`,+ );+ const rows = coins || [];+ table.page = next;+ table.coins.push(...rows);+ // A short page (upstream returned fewer than a full page) or the page+ // ceiling ends pagination.+ if (rows.length < PER_PAGE || next >= MAX_PAGE) table.done = true;+ table.error = false;+ } catch {+ table.error = true;+ }+ table.loading = false;+ renderTable();+}++// ── Related categories ───────────────────────────────────────────────────────++function renderRelated(related) {+ const el = $('cat-related');+ if (!related?.length) {+ el.innerHTML = '';+ return;+ }+ const cards = related+ .map((r) => {+ const change = r.market_cap_change_24h;+ const has = change != null && Number.isFinite(change);+ const cls = !has ? 'dim' : change >= 0 ? 'cv-up' : 'cv-down';+ const chg = has ? `${change >= 0 ? '▲' : '▼'} ${formatPercent(change)}` : '—';+ return `+ <a class="cat-rel-card" href="/category/${encodeURIComponent(r.id)}">+ <span class="nm">${esc(r.name)}</span>+ <span class="mc cv-mono">${esc(formatUsd(r.market_cap))}</span>+ <span class="chg ${cls}">${esc(chg)}</span>+ </a>`;+ })+ .join('');+ el.innerHTML = `+ <h2 class="cv-h2">Related categories</h2>+ <div class="cat-rel-grid">${cards}</div>`;+}++// ── Footer link ──────────────────────────────────────────────────────────────++function renderFooterLink(id) {+ $('cat-footer-link').innerHTML = `+ <p class="cat-footer-link">+ Want the full markets table filtered to this sector?+ <a href="/coins?category=${encodeURIComponent(id)}">Open it in the coins screener →</a>+ </p>`;+}++// ── Not-found / error states ─────────────────────────────────────────────────++function clearBelowHero() {+ $('cat-stats').innerHTML = '';+ $('cat-coins').innerHTML = '';+ $('cat-related').innerHTML = '';+ $('cat-footer-link').innerHTML = '';+}++function renderNotFound(id) {+ $('cat-crumb').textContent = 'Not found';+ $('cat-hero').innerHTML = `+ <h1 class="cv-h1">Category not found</h1>+ <div class="cv-empty" style="text-align:left">+ <p style="margin:0 0 0.75rem">Could not find a crypto category for “${esc(id)}”. The sector may+ not be tracked by the market data source, or the id is misspelled.</p>+ <p style="margin:0">Browse every sector on the <a href="/categories">categories index</a>.</p>+ </div>`;+ clearBelowHero();+}++function renderError() {+ $('cat-crumb').textContent = 'Unavailable';+ $('cat-hero').innerHTML = `+ <h1 class="cv-h1">Category data unavailable</h1>+ <div class="cv-empty" style="text-align:left">+ <p style="margin:0">The market data source is temporarily unreachable. This usually clears in+ under a minute — <a href="javascript:location.reload()">reload the page</a> or head back to the+ <a href="/categories">categories index</a>.</p>+ </div>`;+ clearBelowHero();+}++// ── SEO / document metadata ──────────────────────────────────────────────────++function updateMeta(cat) {+ const title = `${cat.name} — Crypto Category · three.ws`;+ document.title = title;+ const set = (sel, attr, val) => document.querySelector(sel)?.setAttribute(attr, val);+ const bits = [];+ if (cat.market_cap != null) bits.push(`${formatUsd(cat.market_cap)} market cap`);+ if (cat.rank != null) bits.push(`ranked #${cat.rank}`);+ const desc = `The ${cat.name} crypto sector${bits.length ? ` — ${bits.join(', ')}` : ''}. Live market cap, 24h move, volume, and the coins that make it up.`;+ set('meta[name="description"]', 'content', desc);+ set('meta[property="og:title"]', 'content', title);+ set('meta[property="og:description"]', 'content', desc);+ set('meta[name="twitter:title"]', 'content', title);+ set('meta[name="twitter:description"]', 'content', desc);+ const url = `https://three.ws/category/${cat.id}`;+ set('meta[property="og:url"]', 'content', url);+ let canon = document.querySelector('link[rel="canonical"]');+ if (!canon) {+ canon = document.createElement('link');+ canon.rel = 'canonical';+ document.head.appendChild(canon);+ }+ canon.href = url;+}++// ── Boot ─────────────────────────────────────────────────────────────────────++function heroSkeleton() {+ $('cat-hero').innerHTML = `+ <div class="cat-hero-head">+ <div class="cv-skel" style="width:88px;height:34px;border-radius:999px"></div>+ <div style="flex:1;min-width:0">+ <div class="cv-skel" style="width:16rem;height:2.25rem"></div>+ <div class="cv-skel" style="width:8rem;height:1rem;margin-top:0.75rem"></div>+ </div>+ </div>`;+ $('cat-stats').innerHTML = `<div class="cat-stat-grid">${Array.from(+ { length: 4 },+ () => '<div class="cv-skel" style="height:6rem"></div>',+ ).join('')}</div>`;+}++async function main() {+ const id = categoryIdFromLocation();+ const root = $('cat-main');+ if (!id) {+ location.replace('/categories');+ return;+ }+ currentId = id;+ renderFooterLink(id);+ heroSkeleton();+ tableSkeleton();++ let data;+ try {+ data = await getJson(`/api/coin/category?id=${encodeURIComponent(id)}`);+ } catch (err) {+ root.removeAttribute('aria-busy');+ if (err.status === 404 || err.status === 400) renderNotFound(id);+ else renderError();+ return;+ }++ root.removeAttribute('aria-busy');+ const cat = data.category;+ updateMeta(cat);+ renderHero(cat);+ renderStats(cat);+ renderRelated(data.related);++ // The coins table streams in independently of the sector profile.+ loadCoins();+}++main();diff --git a/src/coin-page.js b/src/coin-page.jsindex ff4835379..3ef4aa7cc 100644--- a/src/coin-page.js+++ b/src/coin-page.js@@ -1,8 +1,11 @@// /coin/:id — rich coin detail page, adopted from the cryptocurrency.cv coin// pages: header (icon / name / rank / price / 24h-7d-30d chips), interactive-// SVG price chart with time ranges and a crosshair tooltip, market-stats grid,-// related news, about text, and link pills. Data comes from the /api/coin/*-// proxies (CoinGecko + the native three.ws news aggregator) — never mocked.+// SVG price chart with time ranges and a crosshair tooltip, a 1h→1y price+// performance matrix, market-stats grid, supply bar, ATH/ATL cards, sentiment+// vote split, community/developer activity grids, a paginated exchange-listings+// table, related news, about text, and link pills. Data comes from the+// /api/coin/* proxies (CoinGecko + the native three.ws news aggregator) —+// never mocked.import {formatUsd,@@ -364,6 +367,12 @@ function renderLinks(coin) {if (l.reddit) pills.push(pill(l.reddit, 'Reddit'));if (l.telegram) pills.push(pill(`https://t.me/${l.telegram}`, 'Telegram'));if (l.github) pills.push(pill(l.github, 'GitHub'));+ // Extra tracked repos beyond the primary GitHub link.+ for (const url of (l.repos || []).slice(1, 3)) pills.push(pill(url, 'GitHub'));+ if (l.whitepaper) pills.push(pill(l.whitepaper, 'Whitepaper'));+ if (l.forum) pills.push(pill(l.forum, 'Forum'));+ if (l.chat) pills.push(pill(l.chat, 'Chat'));+ if (l.announcement) pills.push(pill(l.announcement, 'Announcements'));for (const url of (l.explorers || []).slice(0, 2)) pills.push(pill(url, 'Explorer'));// three.ws integration: a Solana contract gets first-party intel links.@@ -412,6 +421,276 @@ function renderLinks(coin) {});}+// ── Price performance matrix ─────────────────────────────────────────────────++const PERF_WINDOWS = [+ ['1h', 'h1'],+ ['24h', 'h24'],+ ['7d', 'd7'],+ ['14d', 'd14'],+ ['30d', 'd30'],+ ['60d', 'd60'],+ ['200d', 'd200'],+ ['1y', 'y1'],+];++function renderPerf(coin) {+ const cp = coin.market?.change_pct || {};+ const cells = PERF_WINDOWS.map(([label, key]) => {+ const v = cp[key];+ const has = v != null && Number.isFinite(v);+ const dir = !has ? '' : v >= 0 ? 'up' : 'down';+ const val = has ? `${v >= 0 ? '▲' : '▼'} ${Math.abs(v).toFixed(2)}%` : '—';+ return `+ <div class="cv-perf-cell ${dir}">+ <span class="win">${esc(label)}</span>+ <span class="val">${esc(val)}</span>+ </div>`;+ }).join('');+ $('cv-perf').innerHTML = `<h2 class="cv-h2">Price Performance</h2><div class="cv-perf-grid">${cells}</div>`;+}++// ── Supply ───────────────────────────────────────────────────────────────────++function renderSupply(coin) {+ const m = coin.market || {};+ const el = $('cv-supply');+ const circ = m.circulating;+ const cap = m.max ?? m.total;+ if (circ == null && m.total == null && m.max == null && m.mcap_fdv_ratio == null) {+ el.innerHTML = '';+ return;+ }+ const pct = circ != null && cap ? Math.min(100, (circ / cap) * 100) : null;+ const capWord = m.max != null ? 'max' : 'total';+ el.innerHTML = `+ <h2 class="cv-h2">Supply</h2>+ <div class="cv-supply-card">+ <div class="cv-supply-row">+ <span>Circulating <strong>${esc(formatSupply(circ))}${coin.symbol ? ` ${esc(coin.symbol)}` : ''}</strong></span>+ ${cap != null ? `<span>${m.max != null ? 'Max' : 'Total'} Supply <strong>${esc(formatSupply(cap))}</strong></span>` : ''}+ </div>+ ${pct != null ? `<div class="cv-supply-track"><div class="cv-supply-fill" style="width:${pct.toFixed(1)}%"></div></div>` : ''}+ <div class="cv-supply-meta">+ ${pct != null ? `<span><strong>${pct.toFixed(1)}%</strong> of ${capWord} in circulation</span>` : ''}+ ${m.mcap_fdv_ratio != null ? `<span>Mkt Cap / FDV <strong>${m.mcap_fdv_ratio.toFixed(2)}</strong></span>` : ''}+ ${m.mcap_change_24h_pct != null ? `<span>Mkt Cap 24h <strong class="cv-${m.mcap_change_24h_pct >= 0 ? 'up' : 'down'}">${esc(formatPercent(m.mcap_change_24h_pct))}</strong></span>` : ''}+ </div>+ </div>`;+}++// ── All-time high / low ──────────────────────────────────────────────────────++function renderExtremes(coin) {+ const m = coin.market || {};+ const el = $('cv-extremes');+ if (m.ath == null && m.atl == null) {+ el.innerHTML = '';+ return;+ }+ const mult = m.price != null && m.atl ? m.price / m.atl : null;+ const cards = [];+ if (m.ath != null) {+ const draw =+ m.ath_change_pct != null+ ? ` · <span class="cv-down">${esc(formatPercent(m.ath_change_pct))}</span> from ATH`+ : '';+ cards.push(`+ <div class="cv-extreme">+ <p class="label">All-Time High</p>+ <p class="value">${esc(formatPrice(m.ath))}</p>+ <p class="sub">${m.ath_date ? esc(formatDateShort(m.ath_date)) : ''}${draw}</p>+ </div>`);+ }+ if (m.atl != null) {+ const rec =+ mult != null+ ? ` · <span class="cv-up">${mult >= 100 ? Math.round(mult).toLocaleString('en-US') : mult.toFixed(1)}×</span> from ATL`+ : '';+ cards.push(`+ <div class="cv-extreme">+ <p class="label">All-Time Low</p>+ <p class="value">${esc(formatPrice(m.atl))}</p>+ <p class="sub">${m.atl_date ? esc(formatDateShort(m.atl_date)) : ''}${rec}</p>+ </div>`);+ }+ el.innerHTML = `<h2 class="cv-h2">All-Time High & Low</h2><div class="cv-extremes-grid">${cards.join('')}</div>`;+}++// ── Community sentiment ──────────────────────────────────────────────────────++function renderSentiment(coin) {+ const s = coin.sentiment || {};+ const el = $('cv-sentiment');+ const { up_pct: up, down_pct: down, watchlist_users: watch } = s;+ if (up == null && down == null && watch == null) {+ el.innerHTML = '';+ return;+ }+ let bar = '';+ if (up != null || down != null) {+ const u = up != null ? up : down != null ? 100 - down : 50;+ const d = down != null ? down : 100 - u;+ bar = `+ <div class="cv-sent-row">+ <span class="cv-up">▲ ${u.toFixed(0)}% Bullish</span>+ <span class="cv-down">${d.toFixed(0)}% Bearish ▼</span>+ </div>+ <div class="cv-sent-bar"><span class="up" style="width:${u}%"></span><span class="down" style="width:${d}%"></span></div>`;+ }+ el.innerHTML = `+ <h2 class="cv-h2">Community Sentiment</h2>+ <div class="cv-sent-card">+ ${bar}+ ${watch != null ? `<p class="cv-sent-watch"><strong>${esc(formatSupply(watch))}</strong> users watching on CoinGecko</p>` : ''}+ </div>`;+}++// ── Community & developer activity ───────────────────────────────────────────++function statCell(label, value) {+ return `<div class="cv-mini-stat"><p class="label">${esc(label)}</p><p class="value cv-mono">${esc(value)}</p></div>`;+}++function renderDevCom(coin) {+ const el = $('cv-devcom');+ const com = coin.community;+ const dev = coin.developer;+ const blocks = [];+ if (com) {+ const cells = [+ com.twitter_followers != null && statCell('Twitter Followers', formatSupply(com.twitter_followers)),+ com.reddit_subscribers != null && statCell('Reddit Subscribers', formatSupply(com.reddit_subscribers)),+ com.telegram_users != null && statCell('Telegram Members', formatSupply(com.telegram_users)),+ ].filter(Boolean).join('');+ if (cells) blocks.push(`<div><h3 class="cv-h3">Community</h3><div class="cv-dc-grid">${cells}</div></div>`);+ }+ if (dev) {+ const cells = [+ dev.stars != null && statCell('GitHub Stars', formatSupply(dev.stars)),+ dev.forks != null && statCell('Forks', formatSupply(dev.forks)),+ dev.subscribers != null && statCell('Watchers', formatSupply(dev.subscribers)),+ dev.total_issues != null && statCell('Total Issues', formatSupply(dev.total_issues)),+ dev.closed_issues != null && statCell('Closed Issues', formatSupply(dev.closed_issues)),+ dev.prs_merged != null && statCell('PRs Merged', formatSupply(dev.prs_merged)),+ dev.pr_contributors != null && statCell('Contributors', formatSupply(dev.pr_contributors)),+ dev.commits_4w != null && statCell('Commits (4w)', formatSupply(dev.commits_4w)),+ ].filter(Boolean).join('');+ if (cells) blocks.push(`<div><h3 class="cv-h3">Developer Activity</h3><div class="cv-dc-grid">${cells}</div></div>`);+ }+ if (!blocks.length) {+ el.innerHTML = '';+ return;+ }+ el.innerHTML = `<h2 class="cv-h2">Community & Development</h2><div class="cv-dc-wrap ${blocks.length === 2 ? 'two' : ''}">${blocks.join('')}</div>`;+}++// ── Markets (exchange listings) ──────────────────────────────────────────────++const marketsState = { page: 0, rows: [], loading: false, done: false, error: false };++function trustCell(trust) {+ if (!trust) return '<span class="cv-trust">—</span>';+ const label = { green: 'High', yellow: 'Fair', red: 'Low' }[trust] || '';+ return `<span class="cv-trust"><span class="dot ${trust}" aria-hidden="true"></span>${esc(label)}</span>`;+}++function tickerRow(t) {+ const ex = t.exchange || {};+ const exCell = ex.id+ ? `<a class="cv-mkt-x" href="/exchange/${encodeURIComponent(ex.id)}">${ex.logo ? `<img src="${esc(ex.logo)}" alt="" loading="lazy" />` : ''}<span class="nm">${esc(ex.name || ex.id)}</span></a>`+ : `<span class="cv-mkt-x"><span class="nm">${esc(ex.name || '—')}</span></span>`;+ const pairCell = t.trade_url+ ? `<a class="cv-mkt-pair" href="${esc(t.trade_url)}" target="_blank" rel="noopener noreferrer">${esc(t.pair || '—')} ↗</a>`+ : `<span class="cv-mkt-pair">${esc(t.pair || '—')}</span>`;+ return `+ <tr class="${t.stale ? 'cv-stale' : ''}">+ <td class="left">${exCell}</td>+ <td class="left">${pairCell}</td>+ <td class="cv-mono">${esc(formatPrice(t.price_usd))}</td>+ <td class="cv-mono">${t.spread_pct != null ? `${t.spread_pct.toFixed(2)}%` : '—'}</td>+ <td class="cv-mono">${esc(formatUsd(t.depth_up_usd))}</td>+ <td class="cv-mono">${esc(formatUsd(t.depth_down_usd))}</td>+ <td class="cv-mono">${esc(formatUsd(t.volume_usd))}</td>+ <td>${trustCell(t.trust)}</td>+ </tr>`;+}++function renderMarkets(coin) {+ const el = $('cv-markets');+ const { rows, loading, error, done } = marketsState;+ if (!rows.length && loading) {+ el.innerHTML = `+ <h2 class="cv-h2">Markets</h2>+ <div class="cv-table-wrap">+ <div class="cv-skel" style="height:2.5rem;margin-bottom:0.5rem"></div>+ ${Array.from({ length: 6 }, () => '<div class="cv-skel" style="height:2.25rem;margin-bottom:0.375rem"></div>').join('')}+ </div>`;+ return;+ }+ if (!rows.length && error) {+ el.innerHTML = `+ <h2 class="cv-h2">Markets</h2>+ <div class="cv-mkt-error">+ <p style="margin:0 0 0.75rem">Exchange listings are temporarily unavailable.</p>+ <button type="button" id="cv-mkt-retry">Retry</button>+ </div>`;+ $('cv-mkt-retry')?.addEventListener('click', () => {+ marketsState.error = false;+ marketsState.page = 0;+ loadMarkets(coin);+ });+ return;+ }+ if (!rows.length) {+ el.innerHTML = '';+ return;+ }+ el.innerHTML = `+ <h2 class="cv-h2">Markets</h2>+ <div class="cv-table-wrap">+ <table class="cv-table">+ <thead>+ <tr>+ <th scope="col" class="left">Exchange</th>+ <th scope="col" class="left">Pair</th>+ <th scope="col">Price</th>+ <th scope="col">Spread</th>+ <th scope="col">+2% Depth</th>+ <th scope="col">−2% Depth</th>+ <th scope="col">24h Volume</th>+ <th scope="col">Trust</th>+ </tr>+ </thead>+ <tbody>${rows.map(tickerRow).join('')}</tbody>+ </table>+ </div>+ ${done ? '' : `<button type="button" class="cv-load-more" id="cv-mkt-more"${loading ? ' disabled' : ''}>${loading ? 'Loading…' : 'Load more exchanges'}</button>`}`;+ $('cv-mkt-more')?.addEventListener('click', () => loadMarkets(coin));+}++async function loadMarkets(coin) {+ if (marketsState.loading || marketsState.done) return;+ marketsState.loading = true;+ renderMarkets(coin);+ try {+ const next = marketsState.page + 1;+ const { tickers, count } = await getJson(+ `/api/coin/tickers?id=${encodeURIComponent(coin.id)}&page=${next}`,+ );+ marketsState.page = next;+ marketsState.rows.push(...(tickers || []));+ // A short page (CoinGecko caps at 100/page) or the 10-page ceiling ends it.+ if (!count || count < 100 || next >= 10) marketsState.done = true;+ marketsState.loading = false;+ marketsState.error = false;+ } catch {+ marketsState.loading = false;+ marketsState.error = true;+ }+ renderMarkets(coin);+}+// ── Not found / error states ────────────────────────────────────────────────function renderNotFound(id) {@@ -495,7 +774,12 @@ async function main() {main_.removeAttribute('aria-busy');updateMeta(coin);renderHead(coin);+ renderPerf(coin);renderStats(coin);+ renderSupply(coin);+ renderExtremes(coin);+ renderSentiment(coin);+ renderDevCom(coin);renderAbout(coin);renderLinks(coin);if (coin.last_updated) {@@ -503,8 +787,9 @@ async function main() {upd.hidden = false;upd.textContent = `Last updated: ${new Date(coin.last_updated).toLocaleString()}`;}- // Chart + news stream in independently of the core profile.+ // Chart, markets, and news stream in independently of the core profile.loadChart(coin);+ loadMarkets(coin);loadNews(coin);}diff --git a/src/coin-pages.css b/src/coin-pages.cssindex e1ccffb18..e88955f35 100644--- a/src/coin-pages.css+++ b/src/coin-pages.css@@ -2013,6 +2013,522 @@ a.cv-liq-item:focus-visible {margin: 0 0 1rem;}+/* ── "Your briefing" layout (/markets/news) ────────────────────────────── */++.nwb-head {+ display: flex;+ flex-wrap: wrap;+ gap: 1rem 2rem;+ align-items: flex-end;+ justify-content: space-between;+ margin: 0 0 1rem;+}+.nwb-head .cv-h1 {+ margin: 0;+}+.nwb-date {+ color: var(--cv-text-3);+ margin: 0.375rem 0 0;+ font-size: 0.9rem;+}+.nwb-head-tools {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ align-items: flex-end;+ flex: 1 1 300px;+ max-width: 560px;+ min-width: 0;+}+.nwb-search {+ width: 100%;+}+.nwb-controls {+ display: flex;+ gap: 0.5rem;+ flex-wrap: wrap;+ justify-content: flex-end;+}+.nwb-ask {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ padding: 0.5rem 0.875rem;+ border-radius: 999px;+ border: 1px solid var(--cv-border);+ background: var(--cv-surface);+ color: var(--cv-text-2);+ font-size: 0.8125rem;+ font-weight: 500;+ text-decoration: none;+ white-space: nowrap;+ transition: color 0.15s, border-color 0.15s;+}+.nwb-ask:hover {+ color: var(--cv-text);+ border-color: var(--cv-border-hover);+}+.nwb-ask:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}+@media (max-width: 640px) {+ .nwb-head-tools {+ align-items: stretch;+ }+ .nwb-controls {+ justify-content: flex-start;+ }+}++/* Primary briefing tabs — underline style, icons + labels. */+.nwb-tabs {+ display: flex;+ gap: 0.25rem;+ overflow-x: auto;+ border-bottom: 1px solid var(--cv-border);+ margin: 0 0 1rem;+ scrollbar-width: thin;+ -webkit-overflow-scrolling: touch;+}+.nwb-tab {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ flex-shrink: 0;+ padding: 0.55rem 0.8rem;+ margin-bottom: -1px;+ border: 0;+ border-bottom: 2px solid transparent;+ background: none;+ color: var(--cv-text-2);+ font-size: 0.85rem;+ font-weight: 500;+ cursor: pointer;+ white-space: nowrap;+ transition: color 0.15s, border-color 0.15s;+}+.nwb-tab:hover {+ color: var(--cv-text);+}+.nwb-tab:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: -2px;+ border-radius: var(--cv-radius-sm);+}+.nwb-tab[aria-pressed='true'] {+ color: var(--cv-accent);+ border-bottom-color: var(--cv-accent);+ font-weight: 600;+}+.nwb-cats {+ margin-top: -0.25rem;+}++/* Breaking-news ticker. */+.nwb-break {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ border: 1px solid var(--cv-border);+ background: var(--cv-surface);+ border-radius: var(--cv-radius-lg);+ box-shadow: var(--cv-shadow-card);+ padding: 0.5rem 0.875rem;+ margin: 0 0 1rem;+ overflow: hidden;+}+.nwb-break-label {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ color: var(--cv-red);+ font-weight: 700;+ font-size: 0.72rem;+ letter-spacing: 0.08em;+ flex-shrink: 0;+}+.nwb-break-viewport {+ overflow: hidden;+ flex: 1;+ min-width: 0;+ -webkit-mask-image: linear-gradient(90deg, transparent, #000 24px, #000 calc(100% - 24px), transparent);+ mask-image: linear-gradient(90deg, transparent, #000 24px, #000 calc(100% - 24px), transparent);+}+.nwb-break-track {+ display: flex;+ width: max-content;+ animation: nwb-marquee 45s linear infinite;+}+.nwb-break-track:hover,+.nwb-break-track:focus-within {+ animation-play-state: paused;+}+.nwb-break-run {+ display: flex;+ align-items: center;+ gap: 1.25rem;+ padding-right: 1.25rem;+}+.nwb-break-item {+ display: inline-flex;+ align-items: baseline;+ gap: 0.5rem;+ color: var(--cv-text);+ text-decoration: none;+ font-size: 0.8125rem;+ white-space: nowrap;+}+.nwb-break-item:hover .nwb-break-title {+ text-decoration: underline;+ text-underline-offset: 3px;+}+.nwb-break-item time {+ color: var(--cv-text-3);+ font-size: 0.72rem;+}+.nwb-break-sep {+ color: var(--cv-text-3);+ align-self: center;+}+@keyframes nwb-marquee {+ to {+ transform: translateX(-50%);+ }+}+@media (prefers-reduced-motion: reduce) {+ .nwb-break-track {+ animation: none;+ }+ .nwb-break-viewport {+ overflow-x: auto;+ }+}++/* Today's AI Briefing card. */+.nwb-brief {+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-xl);+ background: var(--cv-surface);+ box-shadow: var(--cv-shadow-card);+ padding: 1rem 1.25rem;+ margin: 0 0 1.5rem;+}+.nwb-brief-head {+ display: flex;+ align-items: center;+ gap: 0.75rem;+}+.nwb-brief-title {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin: 0;+ font-size: 0.95rem;+ font-weight: 600;+}+.nwb-brief-spark {+ color: #eab308;+}+.nwb-brief-time {+ color: var(--cv-text-3);+ font-size: 0.78rem;+}+.nwb-brief-toggle {+ margin-left: auto;+ display: inline-flex;+ background: none;+ border: 0;+ color: var(--cv-text-3);+ cursor: pointer;+ padding: 0.25rem;+ border-radius: var(--cv-radius);+ transition: color 0.15s;+}+.nwb-brief-toggle:hover {+ color: var(--cv-text);+}+.nwb-brief-toggle:focus-visible {+ outline: 2px solid var(--cv-accent);+}+.nwb-brief-toggle svg {+ transition: transform 0.2s;+}+.nwb-brief-toggle[aria-expanded='false'] svg {+ transform: rotate(-90deg);+}+.nwb-brief-list {+ margin: 0.875rem 0 0;+ padding-left: 1.375rem;+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ font-size: 0.875rem;+ line-height: 1.55;+}+.nwb-brief-list li::marker {+ color: var(--cv-accent);+ font-weight: 600;+}+.nwb-brief-list a {+ color: var(--cv-text);+ text-decoration: none;+}+.nwb-brief-list a:hover {+ text-decoration: underline;+ text-underline-offset: 3px;+}+.nwb-brief-more {+ display: inline-block;+ margin-top: 0.875rem;+ color: var(--cv-accent);+ font-size: 0.8125rem;+ font-weight: 600;+ text-decoration: none;+}+.nwb-brief-more:hover {+ text-decoration: underline;+ text-underline-offset: 3px;+}++/* Section headings (Top stories / Latest). */+.nwb-section-h {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 1.125rem;+ margin: 0 0 1rem;+ font-family: var(--cv-font-serif, inherit);+}+.nwb-section-h svg {+ color: #eab308;+}+.nw-grid + .nwb-section-h,+.nwb-top + .nwb-section-h {+ margin-top: 1.75rem;+}++/* Top stories: hero left, compact rail right. */+.nwb-top {+ display: grid;+ gap: 1rem;+ margin: 0 0 1.75rem;+}+@media (min-width: 900px) {+ .nwb-top {+ grid-template-columns: minmax(0, 3fr) minmax(0, 2fr);+ align-items: start;+ }+}+/* Inside the briefing block the hero stacks vertically: image, then body. */+.nwb-top .nw-hero {+ margin: 0;+ display: flex;+ flex-direction: column;+ height: 100%;+}+.nwb-top .nw-hero-media {+ min-height: 240px;+ flex: 1;+}+.nwb-top .nw-hero-media img {+ max-height: none;+}+.nwb-top .nw-hero-body {+ justify-content: flex-start;+ flex: 0 0 auto;+}+.nwb-rail {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ min-width: 0;+}+.nwb-saved {+ max-width: 760px;+}++/* Compact headline row (rail + saved). */+.nw-row {+ display: flex;+ gap: 0.875rem;+ align-items: stretch;+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ box-shadow: var(--cv-shadow-card);+ padding: 0.75rem 0.875rem;+ cursor: pointer;+ transition: box-shadow 0.2s, border-color 0.2s, transform 0.2s;+}+.nw-row:hover {+ box-shadow: var(--cv-shadow-card-hover);+ border-color: var(--cv-border-hover);+ transform: translateY(-1px);+}+.nw-row:focus-within {+ border-color: var(--cv-accent);+}+.nw-row-body {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+}+.nw-row-title {+ font-size: 0.9rem;+ font-weight: 600;+ line-height: 1.35;+ margin: 0;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.nw-row-title a {+ color: inherit;+ text-decoration: none;+}+.nw-row-title a:hover {+ text-decoration: underline;+ text-underline-offset: 3px;+}+.nw-row-sub {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ font-size: 0.72rem;+ color: var(--cv-text-3);+ margin-top: auto;+}+.nw-row-cat {+ text-transform: uppercase;+ letter-spacing: 0.06em;+ font-weight: 600;+}+.nw-row-thumb {+ flex: 0 0 92px;+ align-self: center;+}+.nw-row-thumb .nw-media,+.nw-row-thumb .nw-hero-media {+ aspect-ratio: 1;+ width: 92px;+ border-radius: var(--cv-radius-md);+ overflow: hidden;+}+.nw-row-thumb .nw-fallback {+ font-size: 1.25rem;+}++/* Save-story star. */+.nw-star {+ background: none;+ border: 0;+ color: var(--cv-text-3);+ cursor: pointer;+ font-size: 0.95rem;+ line-height: 1;+ padding: 0.125rem 0.25rem;+ border-radius: var(--cv-radius-sm);+ transition: color 0.15s, transform 0.15s;+}+.nw-star:hover {+ color: #eab308;+ transform: scale(1.15);+}+.nw-star:focus-visible {+ outline: 2px solid var(--cv-accent);+}+.nw-star[aria-pressed='true'] {+ color: #eab308;+}+.nw-card .nw-meta time {+ margin-left: auto;+}++/* Trending narratives (digest clusters). */+.nwb-trend {+ display: flex;+ flex-direction: column;+ gap: 0.875rem;+}+.nwb-trend-item {+ display: flex;+ gap: 1rem;+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ box-shadow: var(--cv-shadow-card);+ padding: 1rem 1.125rem;+ cursor: pointer;+ transition: box-shadow 0.2s, border-color 0.2s, transform 0.2s;+}+.nwb-trend-item:hover {+ box-shadow: var(--cv-shadow-card-hover);+ border-color: var(--cv-border-hover);+ transform: translateY(-1px);+}+.nwb-trend-item:focus-within {+ border-color: var(--cv-accent);+}+.nwb-trend-rank {+ font-family: var(--cv-font-mono);+ font-size: 1.25rem;+ font-weight: 700;+ color: var(--cv-text-3);+ min-width: 1.75rem;+ line-height: 1.2;+}+.nwb-trend-body {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ min-width: 0;+}+.nwb-trend-title {+ margin: 0;+ font-size: 1.05rem;+ line-height: 1.35;+ font-family: var(--cv-font-serif, inherit);+}+.nwb-trend-title a {+ color: inherit;+ text-decoration: none;+}+.nwb-trend-title a:hover {+ text-decoration: underline;+ text-underline-offset: 3px;+}+.nwb-trend-srcs {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem 0.875rem;+ font-size: 0.72rem;+ color: var(--cv-text-3);+}+.nwb-stance {+ padding: 0.1rem 0.5rem;+ border-radius: 999px;+ font-size: 0.68rem;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.05em;+}+.nwb-stance-bullish {+ color: var(--cv-green);+ background: var(--cv-green-soft);+}+.nwb-stance-bearish {+ color: var(--cv-red);+ background: var(--cv-red-soft);+}+.nwb-stance-neutral {+ color: var(--cv-text-2);+ background: var(--cv-surface-2);+}+/* ── Article reader ────────────────────────────────────────────────────── */.art-hero {@@ -2446,6 +2962,9 @@ a.cv-liq-item:focus-visible {@media (prefers-reduced-motion: reduce) {.nw-card,.nw-hero,+ .nw-row,+ .nwb-trend-item,+ .nw-star,.mkt-hero-card,.nw-card:hover .nw-media img {transition: none;diff --git a/src/derivatives.js b/src/derivatives.jsindex eae30b8be..d25e43b61 100644--- a/src/derivatives.js+++ b/src/derivatives.js@@ -237,6 +237,133 @@ function renderTable() {});}+// ── Derivatives exchanges section ───────────────────────────────────────────+// A second table ranked by open interest, from /api/coin/derivatives?view=+// exchanges. Rows deep-link to the internal /exchange/:id profile (the detail+// endpoint's derivatives fallback serves these venues). The section container+// is injected here rather than living in the static HTML.++const exState = { exchanges: [], loading: true, error: false };++// BTC amount: 4 decimals below 1 BTC, whole otherwise; em dash for missing.+function formatBtc(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ return n.toLocaleString('en-US', { maximumFractionDigits: n < 1 ? 4 : 0 });+}++function exSection() {+ let el = $('dv-exchanges');+ if (el) return el;+ el = document.createElement('section');+ el.id = 'dv-exchanges';+ el.className = 'cv-section';+ el.setAttribute('aria-label', 'Derivatives exchanges');+ const updated = $('dv-updated');+ const market = $('dv-market');+ // Sit between the perps table and the "updated" line.+ if (updated && updated.parentNode) updated.parentNode.insertBefore(el, updated);+ else if (market && market.parentNode) market.parentNode.appendChild(el);+ else document.querySelector('.cv-container')?.appendChild(el);+ return el;+}++const EX_COLUMNS = [+ { label: 'Exchange', left: true },+ { label: 'Open Interest BTC', num: true },+ { label: '24h Vol BTC', num: true },+ { label: 'Perps', num: true, hide: 'hide-sm' },+ { label: 'Futures', num: true, hide: 'hide-sm' },+ { label: 'Year', num: true, hide: 'hide-md' },+ { label: 'Country', left: true, hide: 'hide-md' },+];++function renderExchanges() {+ const el = exSection();+ const heading = '<h2 class="cv-h2">Derivatives Exchanges</h2>';++ if (exState.loading) {+ el.innerHTML = `${heading}<div class="cv-table-wrap" style="padding:0.75rem">${Array.from(+ { length: 6 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('')}</div>`;+ return;+ }+ if (exState.error) {+ el.innerHTML = `${heading}<div class="cv-empty">Derivatives exchange data is temporarily unavailable. Please try again shortly.</div>`;+ return;+ }+ if (!exState.exchanges.length) {+ el.innerHTML = `${heading}<div class="cv-empty">No derivatives exchanges to show right now.</div>`;+ return;+ }++ const head = EX_COLUMNS.map(+ (c) =>+ `<th scope="col" class="${c.left ? 'left' : ''} ${c.hide || ''}">${esc(c.label)}</th>`,+ ).join('');++ const body = exState.exchanges+ .map((e) => {+ const rowAttrs = e.id+ ? ` data-href="/exchange/${encodeURIComponent(e.id)}" tabindex="0" role="link" aria-label="Open ${esc(e.name)} exchange profile"`+ : '';+ return `+ <tr${rowAttrs}>+ <td class="left name-cell"><span class="inner">+ ${e.image ? `<img src="${esc(e.image)}" alt="" loading="lazy" width="24" height="24" data-no-dark-filter />` : ''}+ <span class="nm">${esc(e.name)}</span>+ </span></td>+ <td class="cv-mono">${esc(formatBtc(e.open_interest_btc))}</td>+ <td class="cv-mono">${esc(formatBtc(e.trade_volume_24h_btc))}</td>+ <td class="cv-mono hide-sm">${e.perpetual_pairs ?? '—'}</td>+ <td class="cv-mono hide-sm">${e.futures_pairs ?? '—'}</td>+ <td class="cv-mono hide-md">${e.year_established ?? '—'}</td>+ <td class="left dim hide-md">${esc(e.country || '—')}</td>+ </tr>`;+ })+ .join('');++ el.innerHTML = `+ ${heading}+ <div class="cv-table-wrap">+ <table class="cv-table dv-table dv-ex-table">+ <thead><tr>${head}</tr></thead>+ <tbody>${body}</tbody>+ </table>+ </div>`;++ // Whole row opens the internal /exchange/:id profile; keyboard-accessible.+ el.querySelectorAll('tr[data-href]').forEach((tr) => {+ const go = () => window.location.assign(tr.dataset.href);+ tr.addEventListener('click', (e) => {+ if (e.target.closest('a')) return;+ go();+ });+ tr.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ go();+ }+ });+ });+}++async function loadExchanges() {+ exState.loading = true;+ exState.error = false;+ renderExchanges();+ try {+ const data = await getJson('/api/coin/derivatives?view=exchanges');+ exState.exchanges = Array.isArray(data.exchanges) ? data.exchanges : [];+ exState.loading = false;+ } catch {+ exState.loading = false;+ exState.error = true;+ exState.exchanges = [];+ }+ renderExchanges();+}+// ── Boot ──────────────────────────────────────────────────────────────────────function renderSkeleton() {@@ -269,6 +396,8 @@ async function load() {renderStats();buildFilters();renderTable();+ // The derivatives-exchanges table streams in independently of the perps.+ loadExchanges();}load();diff --git a/src/exchange-page.css b/src/exchange-page.cssnew file mode 100644index 000000000..6570e1a9c--- /dev/null+++ b/src/exchange-page.css@@ -0,0 +1,287 @@+/*+ * /exchange/:id — feature styles layered on top of /src/coin-pages.css.+ * Reuses the shared cv-* container, card, chart, table, pill, and state+ * system; adds only the hero, trust-score badge, meta chips, and markets-table+ * affordances unique to this detail page.+ */++/* ── Hero ──────────────────────────────────────────────────────────────────── */++.ex-hero {+ display: flex;+ gap: 1.25rem;+ align-items: flex-start;+ margin: 0.5rem 0 2rem;+}+.ex-logo {+ width: 72px;+ height: 72px;+ border-radius: 16px;+ object-fit: contain;+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ flex-shrink: 0;+}+.ex-logo-fallback {+ background: var(--cv-surface-2);+}+.ex-hero-body {+ flex: 1;+ min-width: 0;+}+.ex-title-row {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 0.625rem 0.75rem;+}+.ex-title {+ margin: 0;+ font-size: clamp(1.5rem, 4vw, 2rem);+ line-height: 1.1;+}++/* Trust-score badge — larger sibling of the /exchanges list pill. */+.ex-score {+ display: inline-flex;+ align-items: baseline;+ gap: 0.0625rem;+ border-radius: 999px;+ padding: 0.25rem 0.625rem;+ font-family: var(--cv-font-mono);+ font-size: 1rem;+ font-weight: 700;+ line-height: 1;+ font-variant-numeric: tabular-nums;+ border: 1px solid transparent;+ cursor: help;+}+.ex-score .of {+ font-size: 0.6875rem;+ font-weight: 500;+ opacity: 0.7;+}+.ex-score-hi {+ color: var(--cv-green);+ background: var(--cv-green-soft);+ border-color: color-mix(in srgb, var(--cv-green) 30%, transparent);+}+.ex-score-mid {+ color: #b45309;+ background: rgba(234, 179, 8, 0.12);+ border-color: rgba(234, 179, 8, 0.35);+}+:root[data-theme='dark'] .ex-score-mid {+ color: #fbbf24;+}+.ex-score-lo {+ color: var(--cv-red);+ background: var(--cv-red-soft);+ border-color: color-mix(in srgb, var(--cv-red) 30%, transparent);+}++.ex-rank {+ display: inline-flex;+ align-items: center;+ padding: 0.25rem 0.5rem;+ border-radius: 999px;+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ color: var(--cv-text-2);+ font-family: var(--cv-font-mono);+ font-size: 0.8125rem;+ font-weight: 600;+ line-height: 1;+ cursor: help;+}++/* Meta chips: centralized/DEX, country, launch year. */+.ex-meta {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+ margin: 0.875rem 0 0;+}+.ex-chip {+ display: inline-flex;+ align-items: center;+ padding: 0.25rem 0.625rem;+ border-radius: 999px;+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ color: var(--cv-text-2);+ font-size: 0.75rem;+ font-weight: 500;+ line-height: 1.4;+}+.ex-chip-dex {+ color: var(--cv-accent);+ border-color: color-mix(in srgb, var(--cv-accent) 35%, transparent);+ background: color-mix(in srgb, var(--cv-accent) 8%, transparent);+}++.ex-desc {+ margin-top: 1rem;+ font-size: 0.9375rem;+ max-width: 68ch;+}+.ex-links {+ margin-top: 1.125rem;+}++/* ── Stat cards ────────────────────────────────────────────────────────────── */++.ex-stat .sub {+ margin-top: 0.25rem;+}++/* Info affordance next to the normalized-volume label. */+.ex-info {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-size: 0.75rem;+ color: var(--cv-text-3);+ cursor: help;+ transition: color 0.15s;+}+.ex-info:hover,+.ex-info:focus-visible {+ color: var(--cv-accent);+ outline: none;+}+.ex-info:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+ border-radius: var(--cv-radius-sm);+}++/* ── Chart tooltip: two mono lines (USD + BTC) plus the date. ──────────────── */++.cv-chart-tip .p + .p {+ font-size: 0.75rem;+ color: var(--cv-text-3);+}++/* ── Markets / contracts table ─────────────────────────────────────────────── */++.ex-pair {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+}+.ex-pair-link {+ color: var(--cv-text);+ text-decoration: none;+ font-weight: 500;+ transition: color 0.15s;+}+.ex-pair-link:hover,+.ex-pair-link:focus-visible {+ color: var(--cv-accent);+}+.ex-pair-link:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+ border-radius: var(--cv-radius-sm);+}+.ex-trade {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: var(--cv-text-3);+ transition: color 0.15s;+}+.ex-trade:hover,+.ex-trade:focus-visible {+ color: var(--cv-accent);+ outline: none;+}+.ex-trade:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+ border-radius: var(--cv-radius-sm);+}+.ex-trade-inline {+ color: var(--cv-text-3);+}++/* Trust dot: green High / yellow Fair / red Low. */+.ex-trust-cell {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ font-size: 0.8125rem;+ color: var(--cv-text-2);+}+.ex-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ flex-shrink: 0;+}+.ex-dot-green {+ background: var(--cv-green);+}+.ex-dot-yellow {+ background: #eab308; /* no yellow token in the cv palette */+}+.ex-dot-red {+ background: var(--cv-red);+}++/* Stale / anomalous tickers are dimmed but still legible. */+.ex-mkt-table tr.ex-stale td {+ opacity: 0.5;+}++.ex-mkt-note {+ margin: 0.875rem 0 0;+ font-size: 0.8125rem;+ color: var(--cv-text-3);+}++/* ── Error-state retry button ──────────────────────────────────────────────── */++.ex-retry {+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-weight: 600;+ color: var(--cv-text);+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ padding: 0.5rem 1.125rem;+ transition:+ border-color 0.15s,+ background 0.15s;+}+.ex-retry:hover {+ border-color: var(--cv-border-hover);+ background: var(--cv-surface-3);+}+.ex-retry:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++@media (max-width: 480px) {+ .ex-hero {+ gap: 0.875rem;+ }+ .ex-logo {+ width: 56px;+ height: 56px;+ border-radius: 12px;+ }+}++@media (prefers-reduced-motion: reduce) {+ .ex-pair-link,+ .ex-trade,+ .ex-info,+ .ex-retry {+ transition: none;+ }+}diff --git a/src/exchange-page.js b/src/exchange-page.jsnew file mode 100644index 000000000..4efe3a972--- /dev/null+++ b/src/exchange-page.js@@ -0,0 +1,599 @@+// /exchange/:id — rich profile for one crypto exchange, part of the three.ws+// Markets surface. Hero (logo / name / trust score / rank / country / year /+// centralized chip / description / link pills), stat cards, an interactive SVG+// volume-history chart with a range toggle and crosshair tooltip (spot venues+// only), and a markets/contracts table. Derivatives venues — which live on a+// separate CoinGecko namespace — render open interest, perp/futures counts, and+// a contracts table instead of a volume chart. Data comes from the+// /api/coin/exchange proxy (CoinGecko + live BTC price) — never mocked. Mirrors+// the /coin/:id detail-page pattern (src/coin-page.js).++import {+ formatUsd,+ formatPrice,+ formatChartTick,+ escapeHtml as esc,+} from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++// Matches the /exchange/:id route; falls back to the ?id= query for direct+// links and dev proxies that don't rewrite the path.+function idFromLocation() {+ const m = location.pathname.match(/^\/exchange\/([a-z0-9_-]{1,60})$/i);+ if (m) return m[1].toLowerCase();+ const q = new URLSearchParams(location.search).get('id');+ return q && /^[a-z0-9_-]{1,60}$/i.test(q) ? q.toLowerCase() : null;+}++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// BTC volume figure: 4 decimals below 1 BTC, whole otherwise.+function formatBtc(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ return `${n.toLocaleString('en-US', { maximumFractionDigits: n < 1 ? 4 : 0 })} BTC`;+}++// A twitter_handle from CoinGecko is a bare handle ("binance") but occasionally+// arrives with an @ or a full URL — normalize to a canonical profile URL.+function twitterUrl(handle) {+ const h = String(handle)+ .trim()+ .replace(/^@/, '')+ .replace(/^https?:\/\/(www\.)?(twitter|x)\.com\//i, '')+ .replace(/\/+$/, '');+ return h ? `https://twitter.com/${encodeURIComponent(h)}` : null;+}++// ── Skeletons ────────────────────────────────────────────────────────────────++function renderSkeletons() {+ $('ex-hero').innerHTML = `+ <div class="ex-hero">+ <div class="cv-skel" style="width:72px;height:72px;border-radius:16px;flex-shrink:0"></div>+ <div style="flex:1;min-width:0">+ <div class="cv-skel" style="width:14rem;height:2rem"></div>+ <div class="cv-skel" style="width:22rem;max-width:100%;height:1.25rem;margin-top:0.75rem"></div>+ <div class="cv-skel" style="width:30rem;max-width:100%;height:3.5rem;margin-top:0.75rem"></div>+ </div>+ </div>`;+ $('ex-stats').innerHTML =+ '<div class="cv-stats-grid">' ++ Array.from({ length: 4 }, () => '<div class="cv-skel" style="height:5.5rem"></div>').join('') ++ '</div>';+ $('ex-chart').innerHTML =+ '<div class="cv-chart-panel"><div class="cv-skel" style="height:300px;border-radius:8px"></div></div>';+ $('ex-markets').innerHTML = `+ <h2 class="cv-h2">Markets</h2>+ <div class="cv-table-wrap" style="padding:0.75rem">+ ${Array.from({ length: 8 }, () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>').join('')}+ </div>`;+}++// ── Hero ─────────────────────────────────────────────────────────────────────++function trustScoreBadge(score) {+ if (score == null || !Number.isFinite(score)) return '';+ const band = score >= 7 ? 'hi' : score >= 5 ? 'mid' : 'lo';+ return `<span class="ex-score ex-score-${band}" title="CoinGecko trust score — a 0–10 measure of a venue's liquidity, scale, and data integrity">${esc(+ score.toFixed(1),+ )}<span class="of">/10</span></span>`;+}++function metaChips(d) {+ const chips = [];+ if (d.centralized === true) chips.push('<span class="ex-chip">Centralized</span>');+ else if (d.centralized === false) chips.push('<span class="ex-chip ex-chip-dex">DEX</span>');+ if (d.type === 'derivatives') chips.push('<span class="ex-chip">Derivatives</span>');+ if (d.country) chips.push(`<span class="ex-chip">${esc(d.country)}</span>`);+ if (d.year_established != null)+ chips.push(`<span class="ex-chip">Est. ${esc(String(d.year_established))}</span>`);+ return chips.length ? `<div class="ex-meta">${chips.join('')}</div>` : '';+}++function linkPill(href, label) {+ return `<a class="cv-pill" href="${esc(href)}" target="_blank" rel="noopener noreferrer">${esc(label)} ↗</a>`;+}++function heroLinks(d) {+ const s = d.socials || {};+ const pills = [];+ if (d.url) pills.push(linkPill(d.url, 'Website'));+ const tw = s.twitter ? twitterUrl(s.twitter) : null;+ if (tw) pills.push(linkPill(tw, 'Twitter'));+ if (s.reddit_url) pills.push(linkPill(s.reddit_url, 'Reddit'));+ if (s.telegram_url) pills.push(linkPill(s.telegram_url, 'Telegram'));+ if (s.facebook_url) pills.push(linkPill(s.facebook_url, 'Facebook'));+ for (const url of s.other_urls || []) pills.push(linkPill(url, 'Link'));+ return pills.length ? `<div class="cv-pills ex-links">${pills.join('')}</div>` : '';+}++function heroDescription(d) {+ if (!d.description) return '';+ const paras = d.description+ .split(/\n{2,}/)+ .map((p) => p.trim())+ .filter(Boolean)+ .slice(0, 4)+ .map((p) => `<p>${esc(p)}</p>`)+ .join('');+ return paras ? `<div class="cv-prose ex-desc">${paras}</div>` : '';+}++function renderHero(d) {+ $('ex-crumb-name').textContent = d.name;+ $('ex-hero').innerHTML = `+ <div class="ex-hero">+ ${+ d.image+ ? `<img class="ex-logo" src="${esc(d.image)}" alt="${esc(d.name)} logo" width="72" height="72" loading="eager" data-no-dark-filter />`+ : '<div class="ex-logo ex-logo-fallback" aria-hidden="true"></div>'+ }+ <div class="ex-hero-body">+ <div class="ex-title-row">+ <h1 class="cv-h1 ex-title">${esc(d.name)}</h1>+ ${trustScoreBadge(d.trust_score)}+ ${d.trust_score_rank != null ? `<span class="ex-rank" title="Trust-score rank">#${esc(String(d.trust_score_rank))}</span>` : ''}+ </div>+ ${metaChips(d)}+ ${heroDescription(d)}+ ${heroLinks(d)}+ </div>+ </div>`;+}++// ── Stat cards ───────────────────────────────────────────────────────────────++const INFO_ICON =+ '<span class="ex-info" tabindex="0" role="img" aria-label="Adjusted to discount inflated or wash-traded volume" title="Adjusted to discount inflated or wash-traded volume">ⓘ</span>';++function statCard({ label, value, sub, info }) {+ return `+ <div class="cv-mini-stat ex-stat">+ <p class="label">${esc(label)}${info ? ` ${INFO_ICON}` : ''}</p>+ <p class="value cv-mono">${esc(value)}</p>+ ${sub ? `<p class="sub">${esc(sub)}</p>` : ''}+ </div>`;+}++// A BTC amount rendered as USD when the live BTC price is available, with the+// BTC figure as the sub-line; falls back to BTC-only when the price is missing.+function btcValueSub(btc, btcUsd) {+ if (btc == null || !Number.isFinite(btc)) return { value: '—', sub: undefined };+ if (btcUsd != null && btcUsd > 0) return { value: formatUsd(btc * btcUsd), sub: formatBtc(btc) };+ return { value: formatBtc(btc), sub: undefined };+}++function renderStats(d, btcUsd) {+ const cards = [];+ if (d.type === 'derivatives') {+ const oi = btcValueSub(d.open_interest_btc, btcUsd);+ const vol = btcValueSub(d.trade_volume_24h_btc, btcUsd);+ cards.push(statCard({ label: 'Open Interest', value: oi.value, sub: oi.sub }));+ cards.push(statCard({ label: '24h Volume', value: vol.value, sub: vol.sub }));+ cards.push(+ statCard({+ label: 'Perpetual Pairs',+ value: d.number_of_perpetual_pairs != null ? d.number_of_perpetual_pairs.toLocaleString('en-US') : '—',+ }),+ );+ cards.push(+ statCard({+ label: 'Futures Pairs',+ value: d.number_of_futures_pairs != null ? d.number_of_futures_pairs.toLocaleString('en-US') : '—',+ }),+ );+ } else {+ const vol = btcValueSub(d.trade_volume_24h_btc, btcUsd);+ const norm = btcValueSub(d.trade_volume_24h_btc_normalized, btcUsd);+ cards.push(statCard({ label: '24h Volume', value: vol.value, sub: vol.sub }));+ cards.push(+ statCard({+ label: 'Normalized 24h Volume',+ value: norm.value,+ sub: norm.sub,+ info: true,+ }),+ );+ cards.push(+ statCard({+ label: 'Markets',+ value: d.tickers_count != null ? d.tickers_count.toLocaleString('en-US') : '—',+ }),+ );+ cards.push(+ statCard({+ label: 'Trust Rank',+ value: d.trust_score_rank != null ? `#${d.trust_score_rank}` : '—',+ }),+ );+ }+ $('ex-stats').innerHTML = `<div class="cv-stats-grid">${cards.join('')}</div>`;+}++// ── Volume chart (spot venues) ───────────────────────────────────────────────++const TIME_RANGES = [+ { label: '7D', days: 7 },+ { label: '14D', days: 14 },+ { label: '30D', days: 30 },+ { label: '90D', days: 90 },+ { label: '180D', days: 180 },+ { label: '1Y', days: 365 },+];++const CHART_W = 800;+const CHART_H = 300;+const PAD = { top: 20, right: 72, bottom: 30, left: 10 };++// series: [[ts_ms, vol_btc], …]. btcUsd converts the crosshair readout to USD.+const chartState = { days: 30, series: [], btcUsd: null, loading: false, error: false, name: '' };++function chartGeometry(series) {+ const vals = series.map((p) => p[1]);+ const min = Math.min(...vals, 0); // volume floors at 0 — anchor the area there+ const max = Math.max(...vals);+ const range = max - min || 1;+ const w = CHART_W - PAD.left - PAD.right;+ const h = CHART_H - PAD.top - PAD.bottom;+ const pts = vals.map((v, i) => ({+ x: PAD.left + (series.length === 1 ? w / 2 : (i / (series.length - 1)) * w),+ y: PAD.top + h - ((v - min) / range) * h,+ }));+ const line = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(2)},${p.y.toFixed(2)}`).join(' ');+ const area = `${line} L${pts[pts.length - 1].x.toFixed(2)},${(PAD.top + h).toFixed(2)} L${pts[0].x.toFixed(2)},${(PAD.top + h).toFixed(2)} Z`;+ return { min, max, range, line, area };+}++function volAxisLabel(btc, btcUsd) {+ return btcUsd != null && btcUsd > 0 ? formatUsd(btc * btcUsd) : formatBtc(btc);+}++function renderChart() {+ const el = $('ex-chart');+ const { days, series, loading, error, name } = chartState;++ const rangeBtns = TIME_RANGES.map(+ (r) =>+ `<button type="button" class="cv-range-btn" data-days="${r.days}" aria-pressed="${r.days === days}">${r.label}</button>`,+ ).join('');++ let body;+ if (loading) {+ body = '<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading chart…</div>';+ } else if (error) {+ body = '<div class="cv-chart-state">Volume history is temporarily unavailable.</div>';+ } else if (series.length < 2) {+ body = '<div class="cv-chart-state">No volume history available for this range.</div>';+ } else {+ const g = chartGeometry(series);+ const color = 'var(--cv-chart-green)';+ const steps = 4;+ const h = CHART_H - PAD.top - PAD.bottom;+ const yLabels = Array.from({ length: steps + 1 }, (_, i) => {+ const v = g.min + (g.range * i) / steps;+ const y = PAD.top + h - (i / steps) * h;+ return `<g><line x1="${PAD.left}" y1="${y}" x2="${CHART_W - PAD.right}" y2="${y}" stroke="var(--cv-border)" stroke-width="0.5" stroke-dasharray="4 4" opacity="0.5"/><text x="${CHART_W - PAD.right + 8}" y="${y + 4}" font-size="10" fill="var(--cv-text-3)">${esc(volAxisLabel(v, chartState.btcUsd))}</text></g>`;+ }).join('');+ body = `+ <div class="cv-chart-area">+ <svg viewBox="0 0 ${CHART_W} ${CHART_H}" role="img"+ aria-label="24h volume history for ${esc(name)} over ${days} day${days > 1 ? 's' : ''}, denominated in BTC">+ <defs>+ <linearGradient id="ex-grad" x1="0" x2="0" y1="0" y2="1">+ <stop offset="0%" stop-color="${color}" stop-opacity="0.2"/>+ <stop offset="100%" stop-color="${color}" stop-opacity="0.02"/>+ </linearGradient>+ </defs>+ ${yLabels}+ <path d="${g.area}" fill="url(#ex-grad)"/>+ <path d="${g.line}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>+ <g id="ex-crosshair" hidden>+ <line id="ex-cross-line" x1="0" y1="${PAD.top}" x2="0" y2="${CHART_H - PAD.bottom}" stroke="var(--cv-text-3)" stroke-width="0.5" stroke-dasharray="3 3"/>+ <circle id="ex-cross-dot" r="4" fill="${color}" stroke="var(--cv-surface)" stroke-width="2"/>+ </g>+ </svg>+ <div class="cv-chart-tip" id="ex-tip" hidden>+ <p class="p cv-mono" id="ex-tip-val"></p>+ <p class="p cv-mono" id="ex-tip-btc"></p>+ <p class="d" id="ex-tip-date"></p>+ </div>+ </div>`;+ }++ el.innerHTML = `+ <div class="cv-chart-panel">+ <div class="cv-chart-bar">+ <div class="left"><span class="title">24h Volume History</span></div>+ <div class="cv-ranges" role="group" aria-label="Chart time range">${rangeBtns}</div>+ </div>+ ${body}+ </div>`;++ el.querySelectorAll('.cv-range-btn').forEach((btn) => {+ btn.addEventListener('click', () => {+ const dd = Number(btn.dataset.days);+ if (dd === chartState.days) return;+ chartState.days = dd;+ loadChart();+ });+ });++ wireChartPointer();+}++function wireChartPointer() {+ const svg = $('ex-chart').querySelector('svg');+ const tip = $('ex-tip');+ if (!svg || !tip || chartState.series.length < 2) return;+ const g = chartGeometry(chartState.series);+ const cross = svg.querySelector('#ex-crosshair');+ const crossLine = svg.querySelector('#ex-cross-line');+ const crossDot = svg.querySelector('#ex-cross-dot');+ const usableW = CHART_W - PAD.left - PAD.right;+ const usableH = CHART_H - PAD.top - PAD.bottom;++ function show(clientX) {+ const rect = svg.getBoundingClientRect();+ const mouseX = ((clientX - rect.left) / rect.width) * CHART_W;+ const n = chartState.series.length;+ const i = Math.max(0, Math.min(n - 1, Math.round(((mouseX - PAD.left) / usableW) * (n - 1))));+ const [ts, btc] = chartState.series[i];+ const x = PAD.left + (i / (n - 1)) * usableW;+ const y = PAD.top + usableH - ((btc - g.min) / g.range) * usableH;+ cross.removeAttribute('hidden');+ crossLine.setAttribute('x1', x);+ crossLine.setAttribute('x2', x);+ crossDot.setAttribute('cx', x);+ crossDot.setAttribute('cy', y);+ tip.hidden = false;+ tip.style.left = `${(x / CHART_W) * 100}%`;+ const usd =+ chartState.btcUsd != null && chartState.btcUsd > 0 ? formatUsd(btc * chartState.btcUsd) : null;+ $('ex-tip-val').textContent = usd || formatBtc(btc);+ $('ex-tip-btc').textContent = usd ? formatBtc(btc) : '';+ $('ex-tip-btc').hidden = !usd;+ $('ex-tip-date').textContent = formatChartTick(ts, chartState.days);+ }+ function hide() {+ cross.setAttribute('hidden', '');+ tip.hidden = true;+ }+ svg.addEventListener('pointermove', (e) => show(e.clientX));+ svg.addEventListener('pointerleave', hide);+ svg.addEventListener('pointerdown', (e) => show(e.clientX));+}++async function loadChart() {+ chartState.loading = true;+ chartState.error = false;+ renderChart();+ try {+ const { volume_chart, btc_usd } = await getJson(+ `/api/coin/exchange?id=${encodeURIComponent(chartState.id)}&view=chart&days=${chartState.days}`,+ );+ chartState.series = Array.isArray(volume_chart) ? volume_chart : [];+ if (btc_usd != null) chartState.btcUsd = btc_usd;+ chartState.loading = false;+ } catch {+ chartState.loading = false;+ chartState.error = true;+ chartState.series = [];+ }+ renderChart();+}++// ── Markets / contracts table ────────────────────────────────────────────────++const TRADE_ICON =+ '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';++function trustDot(trust) {+ if (!trust) return '<span class="ex-trust-cell"><span class="dim">—</span></span>';+ const label = { green: 'High', yellow: 'Fair', red: 'Low' }[trust] || '';+ return `<span class="ex-trust-cell"><span class="ex-dot ex-dot-${esc(trust)}" aria-hidden="true"></span>${esc(label)}</span>`;+}++function spotRow(t) {+ const pairLabel = esc(t.pair || '—');+ const pairCell = t.coin_id+ ? `<a class="ex-pair-link" href="/coin/${encodeURIComponent(t.coin_id)}">${pairLabel}</a>`+ : `<span>${pairLabel}</span>`;+ const trade = t.trade_url+ ? `<a class="ex-trade" href="${esc(t.trade_url)}" target="_blank" rel="noopener noreferrer" aria-label="Trade ${pairLabel} (opens in a new tab)">${TRADE_ICON}</a>`+ : '';+ return `+ <tr class="${t.stale ? 'ex-stale' : ''}">+ <td class="left"><span class="ex-pair">${pairCell}${trade}</span></td>+ <td class="cv-mono">${esc(formatPrice(t.price_usd))}</td>+ <td class="cv-mono">${t.spread_pct != null ? `${t.spread_pct.toFixed(2)}%` : '—'}</td>+ <td class="cv-mono">${esc(formatUsd(t.volume_usd))}</td>+ <td>${trustDot(t.trust)}</td>+ </tr>`;+}++function derivRow(t) {+ const sym = esc(t.symbol || '—');+ const symCell = t.trade_url+ ? `<a class="ex-pair-link" href="${esc(t.trade_url)}" target="_blank" rel="noopener noreferrer">${sym} <span class="ex-trade-inline" aria-hidden="true">↗</span></a>`+ : `<span>${sym}</span>`;+ const funding =+ t.funding_rate != null+ ? `<span class="${t.funding_rate >= 0 ? 'cv-up' : 'cv-down'}">${t.funding_rate >= 0 ? '+' : ''}${t.funding_rate.toFixed(4)}%</span>`+ : '—';+ return `+ <tr>+ <td class="left"><span class="ex-pair">${symCell}</span></td>+ <td class="cv-mono">${esc(formatPrice(t.price))}</td>+ <td class="cv-mono">${esc(formatPrice(t.index))}</td>+ <td class="cv-mono">${funding}</td>+ <td class="cv-mono">${esc(formatUsd(t.open_interest_usd))}</td>+ <td class="cv-mono">${esc(formatUsd(t.volume_24h_usd))}</td>+ </tr>`;+}++function renderMarkets(d) {+ const el = $('ex-markets');+ const tickers = Array.isArray(d.tickers) ? d.tickers : [];+ const heading = d.type === 'derivatives' ? 'Contracts' : 'Markets';+ if (!tickers.length) {+ el.innerHTML = `+ <h2 class="cv-h2">${heading}</h2>+ <div class="cv-empty">No ${d.type === 'derivatives' ? 'active contracts' : 'markets'} to show for this exchange right now.</div>`;+ return;+ }++ const head =+ d.type === 'derivatives'+ ? `<tr>+ <th scope="col" class="left">Symbol</th>+ <th scope="col">Price</th>+ <th scope="col">Index</th>+ <th scope="col">Funding</th>+ <th scope="col">Open Interest</th>+ <th scope="col">24h Vol</th>+ </tr>`+ : `<tr>+ <th scope="col" class="left">Pair</th>+ <th scope="col">Price</th>+ <th scope="col">Spread</th>+ <th scope="col">24h Volume</th>+ <th scope="col">Trust</th>+ </tr>`;+ const body = tickers.map(d.type === 'derivatives' ? derivRow : spotRow).join('');+ const shown = tickers.length;+ const total = d.tickers_count ?? shown;+ const note =+ total > shown+ ? `<p class="ex-mkt-note">Showing the top ${shown} of ${total.toLocaleString('en-US')} ${d.type === 'derivatives' ? 'contracts' : 'markets'} by volume.</p>`+ : '';++ el.innerHTML = `+ <h2 class="cv-h2">${heading}</h2>+ <div class="cv-table-wrap">+ <table class="cv-table ex-mkt-table">+ <thead>${head}</thead>+ <tbody>${body}</tbody>+ </table>+ </div>+ ${note}`;+}++// ── Error / not-found states ─────────────────────────────────────────────────++function renderNotFound(id) {+ $('ex-crumb-name').textContent = 'Not found';+ $('ex-hero').innerHTML = `+ <h1 class="cv-h1">Exchange not found</h1>+ <div class="cv-empty" style="text-align:left">+ <p style="margin:0 0 0.75rem">Could not find an exchange for “${esc(id)}”. It may not be+ tracked by the market-data source, or the id is misspelled.</p>+ <p style="margin:0">Browse the <a href="/exchanges">exchanges directory</a> or head back to+ <a href="/markets">Markets</a>.</p>+ </div>`;+ $('ex-stats').innerHTML = '';+ $('ex-chart').innerHTML = '';+ $('ex-markets').innerHTML = '';+}++function renderError(id) {+ $('ex-hero').innerHTML = `+ <h1 class="cv-h1">Exchange data unavailable</h1>+ <div class="cv-empty" style="text-align:left">+ <p style="margin:0 0 0.75rem">The market-data source is temporarily unreachable. This usually+ clears within a minute.</p>+ <button type="button" class="ex-retry" id="ex-retry">Retry</button>+ <span style="margin-left:0.75rem">or return to the <a href="/exchanges">exchanges directory</a>.</span>+ </div>`;+ $('ex-stats').innerHTML = '';+ $('ex-chart').innerHTML = '';+ $('ex-markets').innerHTML = '';+ $('ex-retry')?.addEventListener('click', () => main());+}++// ── SEO / document metadata ──────────────────────────────────────────────────++function updateMeta(d, id) {+ const title = `${d.name} — Exchange · three.ws`;+ document.title = title;+ const url = `https://three.ws/exchange/${id}`;+ const set = (sel, attr, val) => document.querySelector(sel)?.setAttribute(attr, val);+ const kind = d.type === 'derivatives' ? 'derivatives exchange' : 'crypto exchange';+ const desc = `${d.name} ${kind} profile${d.trust_score != null ? ` — trust score ${d.trust_score.toFixed(1)}/10` : ''}: 24h volume, markets, and history. Real CoinGecko data.`;+ set('meta[name="description"]', 'content', desc);+ set('meta[property="og:title"]', 'content', title);+ set('meta[property="og:description"]', 'content', desc);+ set('meta[property="og:url"]', 'content', url);+ set('meta[name="twitter:title"]', 'content', title);+ set('meta[name="twitter:description"]', 'content', desc);+ if (d.image) {+ set('meta[property="og:image"]', 'content', d.image);+ set('meta[name="twitter:image"]', 'content', d.image);+ }+ let canon = document.querySelector('link[rel="canonical"]');+ if (!canon) {+ canon = document.createElement('link');+ canon.rel = 'canonical';+ document.head.appendChild(canon);+ }+ canon.href = url;+}++// ── Boot ─────────────────────────────────────────────────────────────────────++async function main() {+ const id = idFromLocation();+ const root = $('ex-main');+ if (!id) {+ location.replace('/exchanges');+ return;+ }+ renderSkeletons();++ let payload;+ try {+ payload = await getJson(`/api/coin/exchange?id=${encodeURIComponent(id)}`);+ } catch (err) {+ root.removeAttribute('aria-busy');+ if (err.status === 404 || err.status === 400) renderNotFound(id);+ else renderError(id);+ return;+ }++ const d = payload.detail || {};+ const btcUsd = payload.btc_usd ?? null;+ root.removeAttribute('aria-busy');++ updateMeta(d, id);+ renderHero(d);+ renderStats(d, btcUsd);+ renderMarkets(d);++ // Volume history is spot-only — derivatives venues have no upstream chart.+ if (d.type === 'derivatives' || payload.volume_chart == null) {+ $('ex-chart').innerHTML = '';+ } else {+ chartState.id = id;+ chartState.name = d.name;+ chartState.btcUsd = btcUsd;+ chartState.days = 30;+ chartState.series = Array.isArray(payload.volume_chart) ? payload.volume_chart : [];+ chartState.loading = false;+ chartState.error = false;+ renderChart();+ }++ const upd = $('ex-updated');+ upd.hidden = false;+ upd.textContent = `Updated ${new Date(payload.updated_at || Date.now()).toLocaleTimeString('en-US')} · source: CoinGecko`;+}++main();diff --git a/src/exchanges.js b/src/exchanges.jsindex 1a9f9f140..ec7b70cc6 100644--- a/src/exchanges.js+++ b/src/exchanges.js@@ -128,7 +128,11 @@ function renderTable() {const rows = sortedExchanges().map((e) => {- const rowAttrs = e.url ? ` data-href="${esc(e.url)}"` : '';+ // The whole row opens the internal /exchange/:id profile; the+ // external website stays a small secondary ↗ affordance.+ const rowAttrs = e.id+ ? ` data-href="/exchange/${encodeURIComponent(e.id)}" tabindex="0" role="link" aria-label="Open ${esc(e.name)} exchange profile"`+ : '';return `<tr${rowAttrs}><td class="rank cv-mono left">${e.trust_score_rank ?? '—'}</td>@@ -179,12 +183,23 @@ function renderTable() {});});- // Whole row opens the exchange in a new tab; the icon link inside stays a real- // anchor for middle-click / keyboard users.+ // Whole row opens the exchange's internal /exchange/:id profile; the website+ // icon link inside stays a real anchor to the external venue. Rows are+ // keyboard-focusable (role=link) so Enter / Space navigate too.el.querySelectorAll('tr[data-href]').forEach((tr) => {+ const go = () => {+ window.location.assign(tr.dataset.href);+ };tr.addEventListener('click', (e) => {if (e.target.closest('a')) return;- window.open(tr.dataset.href, '_blank', 'noopener');+ go();+ });+ tr.addEventListener('keydown', (e) => {+ if (e.target.closest('a')) return;+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ go();+ }});});}diff --git a/src/markets-news.js b/src/markets-news.jsindex 1166a4483..baed1849b 100644--- a/src/markets-news.js+++ b/src/markets-news.js@@ -1,8 +1,12 @@-// /markets/news — live aggregated crypto news over /api/news/feed (native-// three.ws aggregator). Category tabs, debounced search, language and source-// filters, lead-story hero, card grid with sentiment + ticker chips, offset-// pagination. Every story opens the rich reader at /markets/news/article; the-// source link goes straight to the publisher.+// /markets/news — "Your briefing": the front page of the crypto-news wing over+// /api/news/feed + /api/news/digest (both native three.ws aggregation).+//+// Layout: masthead (title + date + search + language/source + Ask AI), primary+// briefing tabs (Featured / Headlines / Trending / DeFi / Bitcoin / Ethereum /+// Analysis / Saved / All), a breaking-news ticker for stories under 45 minutes+// old, a collapsible "Today's AI Briefing" card fed by the digest engine, a+// Top-stories block (hero + compact rail), and the Latest grid with offset+// pagination. Every story opens the rich reader at /markets/news/article.//// Language defaults to English. The registry also carries international feeds,// which are opt-in via the language selector so the default feed reads as one@@ -11,18 +15,41 @@import { timeAgo, escapeHtml as esc } from './shared/coin-format.js';import {newsCard,+ newsRow,newsMedia,sentimentDot,tickerChips,readerHref,+ savedArticles,wireNewsContainer,} from './shared/news-render.js';const $ = (id) => document.getElementById(id);const PAGE_SIZE = 24;+const BREAKING_WINDOW_MS = 45 * 60_000;+const BRIEF_OPEN_KEY = 'twx_news_brief_open';++// ── Primary briefing tabs ────────────────────────────────────────────────────+// A small, opinionated set fronts the full category registry; "All" unfolds+// the complete category list below the bar.++const icon = (d) =>+ `<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`;++const TABS = [+ { key: 'featured', label: 'Featured', icon: icon('<rect x="2" y="2.5" width="12" height="11" rx="1.5"/><path d="M5 6h6M5 9h6M5 12h3.5"/>') },+ { key: 'headlines', label: 'Headlines', icon: icon('<path d="M8.8 1.5 3 9h4l-.8 5.5L12 7H8l.8-5.5z"/>') },+ { key: 'trending', label: 'Trending', icon: icon('<path d="M8 1.8c.4 2.5-2.8 3.7-2.8 6.7a2.8 2.8 0 0 0 5.6 0c0-1-.4-1.8-.9-2.5-.2 1-.7 1.5-1.4 1.7.5-1.9-.1-4.4-.5-5.9z"/>') },+ { key: 'defi', label: 'DeFi', category: 'defi', icon: icon('<circle cx="8" cy="8" r="6.2"/><path d="M8 4.5v7M10 6.2c-.4-.7-1.1-1-2-1-1.1 0-1.9.6-1.9 1.5C6.1 8.7 10 8 10 9.9c0 .9-.9 1.5-2 1.5-1 0-1.7-.4-2.1-1.1"/>') },+ { key: 'bitcoin', label: 'Bitcoin', category: 'bitcoin', icon: icon('<path d="M6 3h3.2a2 2 0 0 1 0 4H6zM6 7h3.7a2 2 0 0 1 0 4H6zM6 3v8M7.2 1.8V3M7.2 11v1.2M9.5 1.8V3M9.5 11v1.2"/>') },+ { key: 'ethereum', label: 'Ethereum', category: 'ethereum', icon: icon('<path d="M8 1.5 3.5 8 8 10.5 12.5 8zM3.5 9.2 8 14.5l4.5-5.3L8 11.7z"/>') },+ { key: 'analysis', label: 'Analysis', category: 'research', icon: icon('<path d="M2.5 13.5h11M3.5 13V9M7 13V5.5M10.5 13V7.5M14 13V3.5"/>') },+ { key: 'saved', label: 'Saved', icon: icon('<path d="M4 2h8v12.5L8 11l-4 3.5z"/>') },+ { key: 'all', label: 'All', icon: icon('<circle cx="8" cy="8" r="6.2"/><path d="M2 8h12M8 1.8c-3.5 3.5-3.5 8.9 0 12.4M8 1.8c3.5 3.5 3.5 8.9 0 12.4"/>') },+];-// Covers every category the registry can emit. The tab bar renders from the-// API's live category list, so a missing label leaks a raw key ("ai_crypto").+// Covers every category the registry can emit. The "All" picker renders from+// the API's live category list, so a missing label leaks a raw key ("ai_crypto").const CATEGORY_LABELS = {all: 'All',general: 'Top',@@ -68,7 +95,8 @@ const LANGUAGE_LABELS = {};const state = {- category: 'all',+ tab: 'headlines',+ category: 'all', // only meaningful on the "All" tablang: 'en',q: '',source: '',@@ -91,9 +119,22 @@ async function getJson(url) {return res.json();}+function activeTab() {+ return TABS.find((t) => t.key === state.tab) || TABS[1];+}++function activeCategory() {+ const tab = activeTab();+ if (tab.category) return tab.category;+ if (tab.key === 'all' && state.category !== 'all') return state.category;+ return null;+}+function feedUrl(offset) {const p = new URLSearchParams();- if (state.category && state.category !== 'all') p.set('category', state.category);+ const category = activeCategory();+ if (category) p.set('category', category);+ if (state.tab === 'featured') p.set('featured', '1');if (state.lang && state.lang !== 'en') p.set('lang', state.lang);if (state.q) p.set('q', state.q);if (state.source) p.set('source', state.source);@@ -105,7 +146,8 @@ function feedUrl(offset) {function syncUrl() {const p = new URLSearchParams();- if (state.category !== 'all') p.set('category', state.category);+ if (state.tab !== 'headlines') p.set('tab', state.tab);+ if (state.tab === 'all' && state.category !== 'all') p.set('category', state.category);if (state.lang !== 'en') p.set('lang', state.lang);if (state.q) p.set('q', state.q);if (state.source) p.set('source', state.source);@@ -113,9 +155,148 @@ function syncUrl() {history.replaceState(null, '', qs ? `/markets/news?${qs}` : '/markets/news');}+// ── Masthead date ────────────────────────────────────────────────────────────++function renderDate() {+ $('nwb-date').textContent = new Intl.DateTimeFormat('en-US', {+ weekday: 'long',+ month: 'long',+ day: 'numeric',+ }).format(new Date());+}++// ── Breaking ticker ──────────────────────────────────────────────────────────+// Stories younger than 45 minutes, newest first, from the unfiltered feed so a+// category tab still surfaces market-wide breaks. Hidden when nothing is fresh.++async function loadBreaking() {+ const el = $('nwb-breaking');+ try {+ const data = await getJson('/api/news/feed?limit=20');+ const cutoff = Date.now() - BREAKING_WINDOW_MS;+ const fresh = (data.articles || [])+ .filter((a) => a.pub_date && new Date(a.pub_date).getTime() >= cutoff)+ .slice(0, 8);+ if (!fresh.length) return; // stays hidden — no fake urgency+ const items = fresh+ .map(+ (a) => `<a class="nwb-break-item" href="${esc(readerHref(a))}">+ <span class="nwb-break-title">${esc(a.title)}</span>+ <time datetime="${esc(a.pub_date)}">${esc(timeAgo(a.pub_date))}</time>+ </a>`,+ )+ .join('<span class="nwb-break-sep" aria-hidden="true">•</span>');+ // Track duplicated once so the CSS loop is seamless; the copy is+ // presentation-only.+ el.innerHTML = `+ <span class="nwb-break-label">${icon('<path d="M8.8 1.5 3 9h4l-.8 5.5L12 7H8l.8-5.5z"/>')} BREAKING</span>+ <div class="nwb-break-viewport"><div class="nwb-break-track">+ <div class="nwb-break-run">${items}</div>+ <div class="nwb-break-run" aria-hidden="true">${items}</div>+ </div></div>`;+ el.hidden = false;+ } catch {+ /* the ticker is an enhancement — a failed fetch just leaves it hidden */+ }+}++// ── Today's AI Briefing ──────────────────────────────────────────────────────+// One digest fetch serves both the briefing card and the Trending tab.++let digestPromise = null;+function fetchDigest() {+ if (!digestPromise) {+ digestPromise = getJson('/api/news/digest?hours=24&limit=10').catch((err) => {+ digestPromise = null; // let a retry re-fetch+ throw err;+ });+ }+ return digestPromise;+}++function firstSentence(text, max = 220) {+ const t = String(text || '').trim();+ if (!t) return '';+ const m = t.match(/^[\s\S]*?[.!?](?=\s|$)/);+ const s = (m ? m[0] : t).trim();+ return s.length > max ? `${s.slice(0, max).replace(/\s+\S*$/, '')}…` : s;+}++function briefOpen() {+ try {+ return localStorage.getItem(BRIEF_OPEN_KEY) !== '0';+ } catch {+ return true;+ }+}++function setBriefOpen(open) {+ try {+ localStorage.setItem(BRIEF_OPEN_KEY, open ? '1' : '0');+ } catch {+ /* preference just won't persist */+ }+}++async function loadBriefing() {+ const el = $('nwb-brief');+ try {+ const digest = await fetchDigest();+ const points = (digest.narratives || []).slice(0, 3);+ if (!points.length) return;+ const open = briefOpen();+ const generated = digest.generated_at+ ? new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: '2-digit' }).format(new Date(digest.generated_at))+ : '';+ el.innerHTML = `+ <div class="nwb-brief-head">+ <h2 class="nwb-brief-title"><span class="nwb-brief-spark" aria-hidden="true">✦</span> Today's AI Briefing</h2>+ ${generated ? `<time class="nwb-brief-time" datetime="${esc(digest.generated_at)}">${esc(generated)}</time>` : ''}+ <button class="nwb-brief-toggle" type="button" aria-expanded="${open}" aria-controls="nwb-brief-body" aria-label="${open ? 'Collapse' : 'Expand'} AI briefing">+ ${icon('<path d="M3.5 6 8 10.5 12.5 6"/>')}+ </button>+ </div>+ <div class="nwb-brief-body" id="nwb-brief-body" ${open ? '' : 'hidden'}>+ <ol class="nwb-brief-list">+ ${points+ .map((n) => {+ const lead = n.articles?.[0];+ const text = firstSentence(n.summary) || n.title;+ return `<li>${lead ? `<a href="${esc(readerHref(lead))}">${esc(text)}</a>` : esc(text)}</li>`;+ })+ .join('')}+ </ol>+ <a class="nwb-brief-more" href="/markets/digest">Read full briefing <span aria-hidden="true">↓</span></a>+ </div>`;+ el.hidden = false;+ el.querySelector('.nwb-brief-toggle').addEventListener('click', (e) => {+ const btn = e.currentTarget;+ const body = $('nwb-brief-body');+ const nowOpen = body.hidden;+ body.hidden = !nowOpen;+ btn.setAttribute('aria-expanded', String(nowOpen));+ btn.setAttribute('aria-label', `${nowOpen ? 'Collapse' : 'Expand'} AI briefing`);+ setBriefOpen(nowOpen);+ });+ } catch {+ /* briefing is an enhancement — the feed stands on its own */+ }+}++// ── Feed views ───────────────────────────────────────────────────────────────++function skeleton() {+ const card = `<div class="nw-card" aria-hidden="true"><div class="nw-media cv-skel"></div>+ <div class="nw-body"><div class="cv-skel" style="height:0.75rem;width:40%"></div>+ <div class="cv-skel" style="height:1rem"></div><div class="cv-skel" style="height:1rem;width:80%"></div></div></div>`;+ return `<div class="nwb-top" aria-hidden="true"><div class="nw-hero cv-skel" style="min-height:320px"></div>+ <div class="nwb-rail">${`<div class="nw-row cv-skel" style="height:88px"></div>`.repeat(4)}</div></div>+ <div class="nw-grid">${card.repeat(6)}</div>`;+}+function heroHtml(a) {return `- <article class="nw-hero" data-href="${esc(readerHref(a))}">+ <article class="nw-hero" data-href="${esc(readerHref(a))}" tabindex="0">${newsMedia(a, { heroic: true })}<div class="nw-hero-body"><div class="nw-meta">${sentimentDot(a)}<span class="nw-src">${esc(a.source)}</span><span>·</span><time datetime="${esc(a.pub_date || '')}">${a.pub_date ? esc(timeAgo(a.pub_date)) : ''}</time></div>@@ -126,35 +307,53 @@ function heroHtml(a) {</article>`;}-function skeleton() {- const card = `<div class="nw-card" aria-hidden="true"><div class="nw-media cv-skel"></div>- <div class="nw-body"><div class="cv-skel" style="height:0.75rem;width:40%"></div>- <div class="cv-skel" style="height:1rem"></div><div class="cv-skel" style="height:1rem;width:80%"></div></div></div>`;- return `<div class="nw-grid">${card.repeat(9)}</div>`;+function emptyBrowse() {+ return `+ <div class="cv-empty">+ <p><strong>No stories match.</strong></p>+ <p>Try a different search, another section, or browse the+ <a href="/markets/archive">662k-article archive</a> for older coverage.</p>+ </div>`;}-function render() {+function renderFeed() {const feedEl = $('nw-feed');const { articles } = state;if (!articles.length) {- feedEl.innerHTML = `- <div class="cv-empty">- <p><strong>No stories match.</strong></p>- <p>Try a different search, another category, or browse the- <a href="/markets/archive">662k-article archive</a> for older coverage.</p>- </div>`;+ feedEl.innerHTML = emptyBrowse();$('nw-count').textContent = '';$('nw-more').hidden = true;return;}- const showHero = !state.q && !state.source && articles[0]?.image;- const heroA = showHero ? articles[0] : null;- const rest = showHero ? articles.slice(1) : articles;- feedEl.innerHTML = `${heroA ? heroHtml(heroA) : ''}<div class="nw-grid">${rest.map((a) => newsCard(a)).join('')}</div>`;++ // A search or single-source view is a flat result list; a browse view gets+ // the briefing treatment: hero + compact rail, then the Latest grid.+ const flat = Boolean(state.q || state.source);+ if (flat) {+ feedEl.innerHTML = `<div class="nw-grid">${articles.map((a) => newsCard(a)).join('')}</div>`;+ } else {+ // Hero: first story carrying a feed image among the leaders, so the+ // masthead visual is never a fallback tile; everything else keeps order.+ const heroIdx = Math.max(0, articles.slice(0, 8).findIndex((a) => a.image));+ const hero = articles[heroIdx] || articles[0];+ const rest = articles.filter((_, i) => i !== heroIdx);+ const rail = rest.slice(0, 4);+ const grid = rest.slice(4);+ feedEl.innerHTML = `+ <h2 class="nwb-section-h">${icon('<path d="M8.8 1.5 3 9h4l-.8 5.5L12 7H8l.8-5.5z"/>')} Top stories</h2>+ <div class="nwb-top">+ ${heroHtml(hero)}+ <div class="nwb-rail">${rail.map((a) => newsRow(a)).join('')}</div>+ </div>+ ${grid.length ? `<h2 class="nwb-section-h">Latest</h2><div class="nw-grid">${grid.map((a) => newsCard(a)).join('')}</div>` : ''}`;+ }+const src = state.meta?.sources?.find((s) => s.key === state.source);+ const tab = activeTab();$('nw-count').textContent =`${state.total.toLocaleString()} stories · ${state.sourcesOk}/${state.sourcesTotal} feeds live` +- (state.category !== 'all' ? ` · ${CATEGORY_LABELS[state.category] || state.category}` : '') ++ (tab.key !== 'headlines' && tab.key !== 'all' ? ` · ${tab.label}` : '') ++ (state.tab === 'all' && state.category !== 'all' ? ` · ${CATEGORY_LABELS[state.category] || state.category}` : '') +(state.lang !== 'en' ? ` · ${state.lang === 'all' ? 'All languages' : LANGUAGE_LABELS[state.lang] || state.lang}` : '') +(src ? ` · ${src.name}` : '') +(state.q ? ` · “${state.q}”` : '');@@ -170,6 +369,7 @@ async function load({ append = false } = {}) {state.offset = 0;feedEl.innerHTML = skeleton();$('nw-count').textContent = '';+ moreBtn.hidden = true;} else {moreBtn.disabled = true;moreBtn.textContent = 'Loading…';@@ -185,7 +385,7 @@ async function load({ append = false } = {}) {state.sourcesTotal = data.sources_total;state.articles = append ? state.articles.concat(data.articles) : data.articles;state.offset = state.articles.length;- render();+ renderFeed();} catch (err) {feedEl.innerHTML = `<div class="cv-empty">@@ -201,9 +401,100 @@ async function load({ append = false } = {}) {}}+// ── Trending view (digest narratives) ────────────────────────────────────────++async function loadTrending() {+ const feedEl = $('nw-feed');+ $('nw-more').hidden = true;+ $('nw-count').textContent = '';+ feedEl.innerHTML = `<div class="nwb-trend" aria-hidden="true">${`<div class="nwb-trend-item cv-skel" style="height:120px"></div>`.repeat(5)}</div>`;+ try {+ const digest = await fetchDigest();+ const narratives = digest.narratives || [];+ if (!narratives.length) {+ feedEl.innerHTML = emptyBrowse();+ return;+ }+ if (state.tab !== 'trending') return; // user already switched away+ feedEl.innerHTML = `+ <div class="nwb-trend">+ ${narratives+ .map((n, i) => {+ const lead = n.articles?.[0];+ const outlets = [...new Set((n.articles || []).map((a) => a.source))];+ return `+ <article class="nwb-trend-item" ${lead ? `data-href="${esc(readerHref(lead))}" tabindex="0"` : ''}>+ <span class="nwb-trend-rank" aria-hidden="true">${i + 1}</span>+ <div class="nwb-trend-body">+ <div class="nw-meta">+ <span class="nwb-stance nwb-stance-${esc(n.stance || 'neutral')}">${esc(n.stance || 'neutral')}</span>+ <span>${n.coverage || outlets.length} outlet${(n.coverage || outlets.length) === 1 ? '' : 's'}</span>+ </div>+ <h3 class="nwb-trend-title">${lead ? `<a href="${esc(readerHref(lead))}">${esc(n.title)}</a>` : esc(n.title)}</h3>+ <p class="nw-desc" style="-webkit-line-clamp:3">${esc(n.summary || '')}</p>+ <div class="nwb-trend-srcs">${outlets.slice(0, 5).map((s) => `<span>${esc(s)}</span>`).join('')}</div>+ ${tickerChips({ tickers: n.tickers })}+ </div>+ </article>`;+ })+ .join('')}+ </div>+ <p class="nw-count" style="margin-top:1rem">Clustered from ${Number(digest.articles_considered || 0).toLocaleString()} articles over the last ${digest.window_hours || 24}h · mood: ${esc(digest.mood || 'neutral')}</p>`;+ } catch {+ if (state.tab !== 'trending') return;+ feedEl.innerHTML = `+ <div class="cv-empty">+ <p><strong>Couldn’t build the trending view.</strong></p>+ <p>The digest engine didn’t respond. It usually recovers on its own.</p>+ <p><button class="arc-btn" type="button" id="nw-retry-trend">Retry</button></p>+ </div>`;+ document.getElementById('nw-retry-trend')?.addEventListener('click', () => loadTrending());+ }+}++// ── Saved view (localStorage) ────────────────────────────────────────────────++function renderSaved() {+ const feedEl = $('nw-feed');+ $('nw-more').hidden = true;+ const saved = savedArticles();+ $('nw-count').textContent = saved.length+ ? `${saved.length} saved ${saved.length === 1 ? 'story' : 'stories'} · stored in this browser`+ : '';+ if (!saved.length) {+ feedEl.innerHTML = `+ <div class="cv-empty">+ <p><strong>No saved stories yet.</strong></p>+ <p>Tap the ☆ on any story to keep it here — saved stories live in this+ browser and survive the live feed moving on.</p>+ </div>`;+ return;+ }+ feedEl.innerHTML = `<div class="nwb-rail nwb-saved">${saved.map((a) => newsRow(a)).join('')}</div>`;+}++// ── Routing between views ────────────────────────────────────────────────────++function show() {+ renderTabs();+ $('nwb-cats').hidden = state.tab !== 'all';+ if (state.tab === 'all') renderCats();+ syncUrl();+ if (state.tab === 'trending') loadTrending();+ else if (state.tab === 'saved') renderSaved();+ else load();+}+function renderTabs() {+ $('nw-tabs').innerHTML = TABS.map(+ (t) =>+ `<button class="nwb-tab" type="button" data-tab="${t.key}" aria-pressed="${String(t.key === state.tab)}">${t.icon}<span>${t.label}</span></button>`,+ ).join('');+}++function renderCats() {const cats = state.meta?.categories ? ['all', ...state.meta.categories] : Object.keys(CATEGORY_LABELS);- $('nw-tabs').innerHTML = cats+ $('nwb-cats').innerHTML = cats.map((c) =>`<button class="nw-tab" type="button" data-cat="${esc(c)}" aria-pressed="${String(c === state.category)}">${esc(CATEGORY_LABELS[c] || c)}</button>`,@@ -212,7 +503,7 @@ function renderTabs() {}function hydrateFilters() {- renderTabs();+ if (state.tab === 'all') renderCats();const langSel = $('nw-lang');const langs = state.meta?.languages || ['en'];@@ -243,18 +534,25 @@ function hydrateFilters() {}function applyTicker(ticker) {+ if (state.tab === 'trending' || state.tab === 'saved') state.tab = 'headlines';state.q = ticker;$('nw-search').value = ticker;- syncUrl();- load();+ show();}function wireEvents() {$('nw-tabs').addEventListener('click', (e) => {+ const btn = e.target.closest('[data-tab]');+ if (!btn || btn.dataset.tab === state.tab) return;+ state.tab = btn.dataset.tab;+ show();+ });++ $('nwb-cats').addEventListener('click', (e) => {const btn = e.target.closest('[data-cat]');if (!btn) return;state.category = btn.dataset.cat;- for (const t of $('nw-tabs').querySelectorAll('.nw-tab')) {+ for (const t of $('nwb-cats').querySelectorAll('.nw-tab')) {t.setAttribute('aria-pressed', String(t.dataset.cat === state.category));}syncUrl();@@ -266,8 +564,10 @@ function wireEvents() {clearTimeout(debounce);debounce = setTimeout(() => {state.q = e.target.value.trim();- syncUrl();- load();+ // Search always lands on a live-feed view — trending narratives and the+ // local saved list aren't searchable server-side.+ if (state.q && (state.tab === 'trending' || state.tab === 'saved')) state.tab = 'headlines';+ show();}, 300);});@@ -278,31 +578,54 @@ function wireEvents() {state.source = '';hydrateFilters();syncUrl();- load();+ if (state.tab !== 'trending' && state.tab !== 'saved') load();});$('nw-source').addEventListener('change', (e) => {state.source = e.target.value;- syncUrl();- load();+ if (state.source && (state.tab === 'trending' || state.tab === 'saved')) state.tab = 'headlines';+ show();});$('nw-more').addEventListener('click', () => load({ append: true }));- wireNewsContainer($('nw-feed'), { onTicker: applyTicker });+ wireNewsContainer($('nw-feed'), {+ onTicker: applyTicker,+ onSave: () => {+ if (state.tab === 'saved') renderSaved();+ },+ });+ wireNewsContainer($('nwb-breaking'));}function init() {const p = new URLSearchParams(location.search);- state.category = p.get('category') || 'all';+ const tab = (p.get('tab') || '').toLowerCase();+ const category = (p.get('category') || '').toLowerCase();state.lang = p.get('lang') || 'en';state.q = p.get('q') || '';state.source = p.get('source') || '';- if (state.q) $('nw-search').value = state.q;- if (!CATEGORY_LABELS[state.category]) state.category = 'all';++ if (TABS.some((t) => t.key === tab)) state.tab = tab;+ // Legacy deep links: /markets/news?category=defi picks the matching primary+ // tab; any other category lands on "All" with that category selected.+ if (!tab && category && category !== 'all') {+ const primary = TABS.find((t) => t.category === category);+ if (primary) state.tab = primary.key;+ else if (CATEGORY_LABELS[category]) {+ state.tab = 'all';+ state.category = category;+ }+ } else if (state.tab === 'all' && CATEGORY_LABELS[category]) {+ state.category = category;+ }if (state.lang !== 'all' && !LANGUAGE_LABELS[state.lang]) state.lang = 'en';- renderTabs();+ if (state.q) $('nw-search').value = state.q;++ renderDate();wireEvents();- load();+ show();+ loadBreaking();+ loadBriefing();}init();diff --git a/src/markets-page.js b/src/markets-page.jsindex 8ff693232..e6400ee3f 100644--- a/src/markets-page.js+++ b/src/markets-page.js@@ -120,6 +120,8 @@ const G = {link: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',dollar:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="12" y1="2" x2="12" y2="22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>',+ yield:+ '<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="M7 14s1.5-4 5-4 5 3 5-2"/><circle cx="18" cy="7" r="1.5"/></svg>',radar:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.07 4.93A10 10 0 0 0 6.99 3.34"/><path d="M4 6h.01"/><path d="M2.29 9.62a10 10 0 1 0 19.02-1.27"/><path d="M16.24 7.76a6 6 0 1 0-8.01 8.91"/><path d="M12 18h.01"/><path d="M17.99 11.66a6 6 0 0 1-2.22 5.01"/><circle cx="12" cy="12" r="2"/><path d="m13.41 10.59 5.66-5.66"/></svg>',};@@ -141,6 +143,7 @@ const SUITE = [{ href: '/defi', glyph: 'defi', title: 'DeFi TVL', desc: 'Total value locked across DeFi protocols, live from DeFiLlama.' },{ href: '/chains', glyph: 'link', title: 'Chains', desc: 'Blockchain TVL leaderboard with dominance share per chain.' },{ href: '/stablecoins', glyph: 'dollar', title: 'Stablecoins', desc: 'Market caps and peg health across every major issuer.' },+ { href: '/yields', glyph: 'yield', title: 'DeFi Yields', desc: 'Explore ~15k live yield pools by APY and TVL, each with its own history.' },{ href: '/coin-intel', glyph: 'radar', title: 'Coin Intelligence', desc: 'Every launch classified — organic vs bundle, with a learning score.' },];diff --git a/src/news-archive.js b/src/news-archive.jsindex 7035df759..a4de93adf 100644--- a/src/news-archive.js+++ b/src/news-archive.js@@ -6,6 +6,7 @@import { escapeHtml as esc } from './shared/coin-format.js';import { ensureX402 } from './shared/x402-loader.js';+import { readerHref } from './shared/news-render.js';const $ = (id) => document.getElementById(id);const PAGE_SIZE = 50;@@ -132,10 +133,7 @@ function rowHtml(a) {: '—';const label = a.sentiment?.label || 'neutral';const dotCls = label.includes('positive') ? 'pos' : label.includes('negative') ? 'neg' : '';- const readerParams = new URLSearchParams({ url: a.link || '', title: a.title, source: a.source });- const titleInner = a.link- ? `<a href="/markets/news/article?${esc(readerParams.toString())}">${esc(a.title)}</a>`- : esc(a.title);+ const titleInner = a.link ? `<a href="${esc(readerHref(a))}">${esc(a.title)}</a>` : esc(a.title);return `<div class="arc-row"><span class="arc-date">${esc(dateStr)}</span>diff --git a/src/news-article.js b/src/news-article.jsindex d0810dfe4..00b110d59 100644--- a/src/news-article.js+++ b/src/news-article.js@@ -1,16 +1,32 @@-// /markets/news/article — the rich reader. Takes ?url= (+ title/source/image-// for instant first paint), calls /api/news/article for server-side-// extraction + analysis, and renders: hero image, byline with sentiment,-// summary + key-points card, full article prose (when the publisher allows-// extraction or ships it in their feed), detected ticker chips, and a-// related-coverage rail. Publisher-blocked pages degrade to an honest-// preview with a prominent read-at-source CTA — never a dead end.+// The rich reader behind BOTH article surfaces:+// • /markets/news/<YYYY-MM>/<id>-<slug> — the canonical story pages. The+// server (api/news/story-page.js) renders the shell with real meta tags+// and a crawler-visible body plus a #art-seed JSON block; this module+// keeps that content on screen and upgrades it in place once the full+// extraction + analysis arrives.+// • /markets/news/article?url=… — the legacy query-param reader (noindex),+// still used for articles without a stable id/date.+// Renders: hero image, byline with sentiment, summary + key-points card, full+// article prose (when the publisher allows extraction or ships it in their+// feed), ticker chips deep-linking to /coin/:id, market context at+// publication, and a related-coverage rail. Publisher-blocked pages degrade+// to an honest preview with a prominent read-at-source CTA — never a dead end.import { timeAgo, escapeHtml as esc } from './shared/coin-format.js';import { newsCard, wireNewsContainer } from './shared/news-render.js';+import { tickerHref, TICKER_COIN_IDS } from './shared/news-links.js';const root = document.getElementById('art-root');+let wired = false;+function wire() {+ // wireNewsContainer attaches delegated listeners to the container itself —+ // they survive innerHTML swaps, so wiring twice would double-fire clicks.+ if (wired) return;+ wireNewsContainer(root);+ wired = true;+}+async function getJson(url) {const res = await fetch(url, { headers: { accept: 'application/json' } });const body = await res.json().catch(() => ({}));@@ -62,18 +78,35 @@ function tickersHtml(a) {return `<div class="nw-chips" style="margin:0 0 1.25rem">${a.tickers.map((t) =>- `<a class="nw-chip" href="/markets/news?q=${encodeURIComponent(t)}" aria-label="More ${esc(t)} coverage">${esc(t)}</a>`,+ `<a class="nw-chip" href="${esc(tickerHref(t))}" aria-label="${TICKER_COIN_IDS[t] ? `${esc(t)} price and profile` : `More ${esc(t)} coverage`}">${esc(t)}</a>`,).join('')}</div>`;}-function summaryCardHtml(a) {+function fmtUsd(n) {+ if (typeof n !== 'number' || !Number.isFinite(n)) return null;+ return `$${n.toLocaleString('en-US', { maximumFractionDigits: n >= 1000 ? 0 : 2 })}`;+}++// The market snapshot the hourly archiver captured when the story was+// published — real recorded data the publisher's own page doesn't have.+function marketContextHtml(mc) {+ if (!mc) return '';+ const parts = [];+ if (fmtUsd(mc.btc_price)) parts.push(`BTC ${fmtUsd(mc.btc_price)}`);+ if (fmtUsd(mc.eth_price)) parts.push(`ETH ${fmtUsd(mc.eth_price)}`);+ if (mc.fear_greed_index != null) parts.push(`Fear & Greed ${esc(String(mc.fear_greed_index))}`);+ return parts.length ? `<p class="art-provider">Market at publication: ${parts.join(' · ')}</p>` : '';+}++function summaryCardHtml(a, seed) {const points = (a.key_points || []).filter(Boolean);return `<div class="art-summary-card"><h2>Summary</h2><p>${esc(a.summary || a.description || '')}</p>${points.length ? `<h2 style="margin-top:1rem">Key points</h2><ul class="art-keypoints">${points.map((p) => `<li>${esc(p)}</li>`).join('')}</ul>` : ''}+ ${marketContextHtml(seed?.market_context)}<p class="art-provider">${a.analysis_provider === 'heuristic' ? 'Extractive summary from the article text' : `AI summary via ${esc(a.analysis_provider)}`} · three.ws news</p></div>`;}@@ -89,7 +122,7 @@ function render(a, seed) {<div class="art-layout"><div>${tickersHtml(a)}- ${summaryCardHtml(a)}+ ${summaryCardHtml(a, seed)}${isPreview? `<div class="art-preview-note">@@ -112,7 +145,7 @@ function render(a, seed) {</aside></div>`;document.title = `${a.title} · Crypto News · three.ws`;- wireNewsContainer(root);+ wire();}function renderError(err, seed) {@@ -130,9 +163,49 @@ function renderError(err, seed) {document.getElementById('art-retry')?.addEventListener('click', init);}+// On a server-rendered story page the crawler body is already meaningful —+// keep it on screen and only signal that the full text is on its way.+function ssrLoadingIndicator(show) {+ document.getElementById('art-ssr-loading')?.remove();+ if (!show) return;+ const el = document.createElement('div');+ el.id = 'art-ssr-loading';+ el.className = 'art-byline';+ el.innerHTML = `<span class="cv-spinner" aria-hidden="true"></span><span>Extracting the full story…</span>`;+ const anchor = root.querySelector('.art-byline');+ if (anchor) anchor.after(el);+ else root.prepend(el);+}++function ssrErrorNotice(err) {+ ssrLoadingIndicator(false);+ const el = document.createElement('div');+ el.className = 'art-preview-note';+ el.innerHTML = `+ <span aria-hidden="true">⚠️</span>+ <span>Full-text extraction is unavailable right now+ (${err.status === 429 ? 'rate limited — reload in a few seconds' : esc(err.message || 'the reader service didn’t respond')}).+ The story summary above and the read-at-source link still work.</span>`;+ const anchor = root.querySelector('.art-summary-card');+ if (anchor) anchor.after(el);+ else root.append(el);+}++function readSsrSeed() {+ const el = document.getElementById('art-seed');+ if (!el) return null;+ try {+ const seed = JSON.parse(el.textContent);+ return seed?.url ? seed : null;+ } catch {+ return null;+ }+}+async function init() {+ const ssrSeed = readSsrSeed();const p = new URLSearchParams(location.search);- const seed = {+ const seed = ssrSeed || {url: p.get('url') || '',title: p.get('title') || '',source: p.get('source') || '',@@ -147,8 +220,13 @@ async function init() {</div>`;return;}- if (seed.title) document.title = `${seed.title} · Crypto News · three.ws`;- root.innerHTML = skeletonHtml(seed);+ wire();+ if (ssrSeed) {+ ssrLoadingIndicator(true);+ } else {+ if (seed.title) document.title = `${seed.title} · Crypto News · three.ws`;+ root.innerHTML = skeletonHtml(seed);+ }try {const q = new URLSearchParams({ url: seed.url });if (seed.title) q.set('title', seed.title);@@ -156,7 +234,8 @@ async function init() {const a = await getJson(`/api/news/article?${q}`);render(a, seed);} catch (err) {- renderError(err, seed);+ if (ssrSeed) ssrErrorNotice(err);+ else renderError(err, seed);}}diff --git a/src/shared/news-links.js b/src/shared/news-links.jsnew file mode 100644index 000000000..aaccb03f1--- /dev/null+++ b/src/shared/news-links.js@@ -0,0 +1,75 @@+// Canonical story-page links — the single source of truth for how a news+// article maps to its own indexable page on three.ws, shared by the browser+// modules (news feed, archive, coin page, reader) AND the server (the SSR+// story-page handler and the news sitemap import this file too, like+// api/sentiment.js → src/social/sentiment.js).+//+// URL scheme: /markets/news/<YYYY-MM>/<id16>[-<slug>]+// <YYYY-MM> the article's publication month — maps 1:1 to an archive month+// file (articles/YYYY-MM.jsonl), so ANY of the 660k+ historical+// articles resolves with a single fetch.+// <id16> the 16-hex content-addressed article id (sha256 of the+// publisher link) that the live feed and the archive already+// share. This is the lookup key.+// <slug> human/SEO-readable, derived from the title. Cosmetic only —+// the route ignores it, so a retitled story never 404s.++/** Lowercase-ascii slug from an article title. Returns '' for titles with no+ * latin content (e.g. Chinese headlines) — the path stays valid without it. */+export function slugifyTitle(title) {+ return String(title || '')+ .toLowerCase()+ .normalize('NFKD')+ .replace(/[̀-ͯ]/g, '') // strip diacritics+ .replace(/['’]/g, '')+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .split('-')+ .slice(0, 10)+ .join('-')+ .slice(0, 80)+ .replace(/-+$/, '');+}++/** YYYY-MM month bucket for an article, or null when it carries no parseable+ * publication date (undated corpus rows stay on the query-param reader). */+export function storyMonth(a) {+ const t = Date.parse(a?.pub_date || a?.published_at || '');+ if (Number.isNaN(t)) return null;+ return new Date(t).toISOString().slice(0, 7);+}++/**+ * Canonical story-page path for an article record, or null when the record+ * can't carry one (no id or no date). Accepts both the live-feed shape+ * (pub_date) and the coin-rail shape (published_at).+ */+export function storyPath(a) {+ const month = storyMonth(a);+ if (!a?.id || !/^[a-f0-9]{16}$/.test(a.id) || !month) return null;+ const slug = slugifyTitle(a.title);+ return `/markets/news/${month}/${a.id}${slug ? `-${slug}` : ''}`;+}++// Tickers the aggregator detects (api/_lib/news.js TICKER_WORDS) mapped to+// their CoinGecko ids, so article pages can deep-link straight into the+// /coin/:id profiles. Symbols outside this map fall back to a news search.+export const TICKER_COIN_IDS = {+ BTC: 'bitcoin', ETH: 'ethereum', SOL: 'solana', XRP: 'ripple', BNB: 'binancecoin',+ DOGE: 'dogecoin', ADA: 'cardano', USDT: 'tether', USDC: 'usd-coin',+ AVAX: 'avalanche-2', DOT: 'polkadot', LINK: 'chainlink', LTC: 'litecoin',+ MATIC: 'matic-network', TRX: 'tron', SHIB: 'shiba-inu', SUI: 'sui',+ APT: 'aptos', NEAR: 'near', ARB: 'arbitrum', OP: 'optimism', PEPE: 'pepe',+ BONK: 'bonk', AAVE: 'aave', UNI: 'uniswap', MKR: 'maker', XLM: 'stellar',+ XMR: 'monero', ATOM: 'cosmos', FIL: 'filecoin', HBAR: 'hedera-hashgraph',+ INJ: 'injective-protocol', TIA: 'celestia', JTO: 'jito-governance-token',+ JUP: 'jupiter-exchange-solana', WLD: 'worldcoin-wld', TON: 'the-open-network',+ HYPE: 'hyperliquid',+};++/** In-platform destination for a ticker chip: the coin profile when the+ * symbol is a known major, otherwise a scoped news search. */+export function tickerHref(sym) {+ const id = TICKER_COIN_IDS[String(sym || '').toUpperCase()];+ return id ? `/coin/${id}` : `/markets/news?q=${encodeURIComponent(sym)}`;+}diff --git a/src/shared/news-render.js b/src/shared/news-render.jsindex 0d416a371..7edff7e71 100644--- a/src/shared/news-render.js+++ b/src/shared/news-render.js@@ -1,11 +1,32 @@// Shared renderers for crypto-news cards — used by /markets/news,// /markets/news/article (related rail), and the /markets hub news column.-// Pure functions + one event wirer; no module side effects.+// Pure render functions + one event wirer + the saved-stories store.+//+// Preview images load through a three-step chain so a card never shows a+// broken image:+// 1. The feed image loads directly (referrerpolicy=no-referrer clears most+// hotlink-referrer blocks for free).+// 2. On error, one retry through the same-origin /api/img proxy — the server+// fetch is immune to referrer/CORS blocking and mixed-content rules.+// 3. On a second error, the source-initials tile.+// Articles whose feed ships no image at all point at /api/news/image, which+// resolves the publisher page's og:image server-side; its 404 lands on the+// same initials tile.import { timeAgo, escapeHtml as esc } from './coin-format.js';+import { storyPath } from './news-links.js';-/** Reader-page href carrying enough metadata for instant first paint. */+/**+ * Href for reading an article on three.ws. Articles with a stable identity+ * (16-hex id + publication date — everything from the live feed and the+ * archive) get their canonical, indexable story page+ * (/markets/news/<YYYY-MM>/<id>-<slug>, server-rendered for SEO); anything+ * else falls back to the query-param reader, which carries enough metadata+ * for instant first paint.+ */export function readerHref(a) {+ const canonical = storyPath(a);+ if (canonical) return canonical;const p = new URLSearchParams({ url: a.link, title: a.title, source: a.source });if (a.image) p.set('image', a.image);return `/markets/news/article?${p}`;@@ -28,21 +49,88 @@ export function tickerChips(a, { max = 4 } = {}) {.join('')}</div>`;}+// ── Saved stories (localStorage) ─────────────────────────────────────────────+// Full article snapshots, not just ids — feed articles age out of the live+// window, and a saved story must still render weeks later.++const SAVED_KEY = 'twx_news_saved';+const SAVED_MAX = 200;++function readSaved() {+ try {+ const parsed = JSON.parse(localStorage.getItem(SAVED_KEY) || '[]');+ return Array.isArray(parsed) ? parsed : [];+ } catch {+ return [];+ }+}++/** Saved articles, most recently saved first. */+export function savedArticles() {+ return readSaved();+}++export function isSaved(id) {+ return readSaved().some((a) => a.id === id);+}++/** Toggle an article in the saved store. Returns true if it is now saved. */+export function toggleSaved(article) {+ if (!article?.id) return false;+ const list = readSaved();+ const idx = list.findIndex((a) => a.id === article.id);+ let saved;+ if (idx >= 0) {+ list.splice(idx, 1);+ saved = false;+ } else {+ const { id, title, link, description, image, source, source_key, category, pub_date, tickers, sentiment } = article;+ list.unshift({ id, title, link, description, image, source, source_key, category, pub_date, tickers, sentiment, saved_at: new Date().toISOString() });+ if (list.length > SAVED_MAX) list.length = SAVED_MAX;+ saved = true;+ }+ try {+ localStorage.setItem(SAVED_KEY, JSON.stringify(list));+ } catch {+ /* storage full or blocked — the in-page toggle still reflects the click */+ }+ return saved;+}++function starButton(a) {+ const saved = isSaved(a.id);+ return `<button class="nw-star" type="button" data-star="${esc(a.id)}" aria-pressed="${saved}"+ aria-label="${saved ? 'Remove from saved stories' : 'Save story'}" title="${saved ? 'Saved — click to remove' : 'Save story'}">${saved ? '★' : '☆'}</button>`;+}++// Articles rendered this page-view, keyed by id, so the delegated star handler+// can persist a full snapshot at click time without threading state through+// every caller.+const renderedArticles = new Map();++// ── Media ────────────────────────────────────────────────────────────────────++const proxied = (u) => `/api/img?url=${encodeURIComponent(u)}`;+export function newsMedia(a, { heroic = false } = {}) {const cls = heroic ? 'nw-hero-media' : 'nw-media';const initials = esc((a.source || '?').slice(0, 2).toUpperCase());- if (a.image) {- return `<div class="${cls}" style="position:relative"><img src="${esc(a.image)}" alt="" loading="lazy" decoding="async" data-fallback="${initials}" /></div>`;- }- return `<div class="${cls}" style="position:relative"><div class="nw-fallback">${initials}</div></div>`;+ // Feed image → direct load with one proxy retry. No feed image → the+ // og:image resolver; its 404 fires the same error path → initials tile.+ const src = a.image || `/api/news/image?url=${encodeURIComponent(a.link)}`;+ const retry = a.image ? ` data-retry="${esc(proxied(a.image))}"` : '';+ return `<div class="${cls}" style="position:relative"><img src="${esc(src)}" alt="" loading="lazy" decoding="async" referrerpolicy="no-referrer" data-fallback="${initials}"${retry} /></div>`;}-export function newsCard(a, { chips = true, desc = true } = {}) {+// ── Cards / rows ─────────────────────────────────────────────────────────────++export function newsCard(a, { chips = true, desc = true, star = true } = {}) {+ renderedArticles.set(a.id, a);return `- <article class="nw-card" data-href="${esc(readerHref(a))}">+ <article class="nw-card" data-href="${esc(readerHref(a))}" tabindex="0">${newsMedia(a)}<div class="nw-body">- <div class="nw-meta">${sentimentDot(a)}<span class="nw-src">${esc(a.source)}</span><span>·</span><time datetime="${esc(a.pub_date || '')}">${a.pub_date ? esc(timeAgo(a.pub_date)) : ''}</time></div>+ <div class="nw-meta">${sentimentDot(a)}<span class="nw-src">${esc(a.source)}</span>${star ? starButton(a) : ''}<time datetime="${esc(a.pub_date || '')}">${a.pub_date ? esc(timeAgo(a.pub_date)) : ''}</time></div><h3 class="nw-title"><a href="${esc(readerHref(a))}">${esc(a.title)}</a></h3>${desc && a.description ? `<p class="nw-desc">${esc(a.description)}</p>` : ''}${chips ? tickerChips(a) : ''}@@ -51,17 +139,45 @@ export function newsCard(a, { chips = true, desc = true } = {}) {}/**- * Broken/hotlink-blocked thumbnails become a source-initials tile. Image- * error events don't bubble, so listen in the capture phase. Also makes- * data-href cards behave as links (click + Enter) without swallowing real- * anchors/buttons inside them.+ * Compact headline row — the "Top stories" rail and the Saved tab. Thumbnail+ * on the right so the text keeps one clean reading column.*/-export function wireNewsContainer(container, { onTicker } = {}) {+export function newsRow(a, { thumb = true, star = true } = {}) {+ renderedArticles.set(a.id, a);+ const cat = a.category && a.category !== 'general' ? a.category.replace(/_/g, ' ') : 'general';+ return `+ <article class="nw-row" data-href="${esc(readerHref(a))}" tabindex="0">+ <div class="nw-row-body">+ <div class="nw-meta">${sentimentDot(a)}<span class="nw-src">${esc(a.source)}</span>${star ? starButton(a) : ''}</div>+ <h3 class="nw-row-title"><a href="${esc(readerHref(a))}">${esc(a.title)}</a></h3>+ <div class="nw-row-sub"><time datetime="${esc(a.pub_date || '')}">${a.pub_date ? esc(timeAgo(a.pub_date)) : ''}</time><span class="nw-row-cat">${esc(cat)}</span></div>+ </div>+ ${thumb ? `<div class="nw-row-thumb">${newsMedia(a)}</div>` : ''}+ </article>`;+}++// ── Wiring ───────────────────────────────────────────────────────────────────++/**+ * One delegated wirer per container:+ * • image fallback chain (image error events don't bubble — capture phase)+ * • data-href cards behave as links (click + Enter) without swallowing real+ * anchors/buttons inside them+ * • ticker chips → onTicker+ * • star buttons → saved store; onSave lets the Saved tab react live+ */+export function wireNewsContainer(container, { onTicker, onSave } = {}) {container.addEventListener('error',(e) => {const img = e.target;if (img?.tagName !== 'IMG' || !img.dataset.fallback) return;+ if (img.dataset.retry) {+ const retry = img.dataset.retry;+ delete img.dataset.retry;+ img.src = retry;+ return;+ }const tile = document.createElement('div');tile.className = 'nw-fallback';tile.textContent = img.dataset.fallback;@@ -70,6 +186,24 @@ export function wireNewsContainer(container, { onTicker } = {}) {true,);container.addEventListener('click', (e) => {+ const starBtn = e.target.closest('[data-star]');+ if (starBtn) {+ e.preventDefault();+ e.stopPropagation();+ const article = renderedArticles.get(starBtn.dataset.star);+ if (!article) return;+ const saved = toggleSaved(article);+ // One story can render in several places (hero + rail + grid) — keep+ // every copy of its star in sync.+ for (const btn of document.querySelectorAll(`[data-star="${CSS.escape(starBtn.dataset.star)}"]`)) {+ btn.setAttribute('aria-pressed', String(saved));+ btn.setAttribute('aria-label', saved ? 'Remove from saved stories' : 'Save story');+ btn.title = saved ? 'Saved — click to remove' : 'Save story';+ btn.textContent = saved ? '★' : '☆';+ }+ if (onSave) onSave(article, saved);+ return;+ }const chip = e.target.closest('[data-ticker]');if (chip) {e.preventDefault();diff --git a/src/yields.css b/src/yields.cssnew file mode 100644index 000000000..6dbbab2fc--- /dev/null+++ b/src/yields.css@@ -0,0 +1,468 @@+/*+ * /yields — DeFi yield-pool explorer. Reuses cv-container, cv-stats-grid,+ * cv-stat-card, cv-table, cv-search, hm-seg, cv-empty, cv-skel and the+ * scr-controls / scr-field / scr-reset filter chrome from screener.css's+ * siblings. This file styles only what is unique to the yields page: the+ * stablecoin toggle, the wide pool table's pool/APY/chip cells, and the+ * per-row expansion drawer with its dual-axis APY/TVL chart.+ *+ * Chart axis colors are theme-aware custom properties so the SVG strokes and+ * the legend swatches always agree.+ */++:root[data-theme='light'] {+ --yl-apy-axis: #7c3aed;+ --yl-tvl-axis: #2563eb;+ --yl-amber: #b45309;+ --yl-amber-soft: rgba(245, 158, 11, 0.14);+}+:root[data-theme='dark'] {+ --yl-apy-axis: #a78bfa;+ --yl-tvl-axis: #60a5fa;+ --yl-amber: #fbbf24;+ --yl-amber-soft: rgba(245, 158, 11, 0.16);+}++/* ── Stat cards ─────────────────────────────────────────────────────────── */++.yl-stats {+ margin-bottom: 1.5rem;+}+@media (min-width: 768px) {+ /* Three headline stats read best across three columns, not four. */+ .yl-stats {+ grid-template-columns: repeat(3, 1fr);+ }+}+.yl-stat-skel {+ display: inline-block;+ width: 5.5rem;+ height: 1.5rem;+ vertical-align: middle;+}++/* ── Filter controls ───────────────────────────────────────────────────── */++.yl-controls {+ align-items: flex-end;+}+.yl-search {+ max-width: 20rem;+ flex: 1 1 16rem;+}++.yl-toggle {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.8125rem;+ font-weight: 500;+ color: var(--cv-text-2);+ cursor: pointer;+ user-select: none;+ padding-bottom: 0.5rem;+}+.yl-toggle input {+ appearance: none;+ width: 2.25rem;+ height: 1.25rem;+ border-radius: 999px;+ background: var(--cv-surface-3);+ border: 1px solid var(--cv-border);+ position: relative;+ cursor: pointer;+ transition:+ background 0.15s,+ border-color 0.15s;+ flex-shrink: 0;+}+.yl-toggle input::after {+ content: '';+ position: absolute;+ top: 1px;+ left: 1px;+ width: 1rem;+ height: 1rem;+ border-radius: 50%;+ background: var(--cv-text-3);+ transition:+ transform 0.18s ease,+ background 0.15s;+}+.yl-toggle input:checked {+ background: color-mix(in srgb, var(--cv-accent) 30%, transparent);+ border-color: var(--cv-accent);+}+.yl-toggle input:checked::after {+ transform: translateX(1rem);+ background: var(--cv-accent);+}+.yl-toggle input:hover {+ border-color: var(--cv-border-hover);+}+.yl-toggle input:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++.yl-seg {+ padding-bottom: 0;+}++/* ── Table ──────────────────────────────────────────────────────────────── */++.yl-table {+ min-width: 720px;+}+/* Header cells aren't click-to-sort here (sort is the TVL|APY toggle), so drop+ the inherited pointer affordance. */+.yl-table th {+ cursor: default;+}+.yl-table th:hover {+ color: var(--cv-text-2);+}++.yl-row {+ cursor: pointer;+}+.yl-row td {+ transition: background 0.12s;+}+.yl-row:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: -2px;+}+.yl-row.is-open td {+ background: var(--cv-surface-2);+}++.yl-pool {+ display: flex;+ align-items: baseline;+ gap: 0.5rem;+}+.yl-pool .chev {+ color: var(--cv-text-3);+ font-size: 0.7rem;+ transition: transform 0.18s ease;+ transform: translateY(-1px);+}+.yl-row.is-open .yl-pool .chev {+ transform: translateY(-1px) rotate(90deg);+ color: var(--cv-accent);+}+.yl-pool .pool-inner {+ display: flex;+ flex-direction: column;+ gap: 0.1rem;+ min-width: 0;+}+.yl-pool .sym {+ font-weight: 600;+ color: var(--cv-text);+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+}+.yl-pool .meta {+ font-size: 0.7rem;+ color: var(--cv-text-3);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 14rem;+}+.yl-tag {+ font-size: 0.625rem;+ font-weight: 600;+ letter-spacing: 0.03em;+ text-transform: uppercase;+ color: var(--cv-accent);+ background: color-mix(in srgb, var(--cv-accent) 12%, transparent);+ border-radius: var(--cv-radius-sm);+ padding: 0.05rem 0.3rem;+}++.yl-project {+ color: var(--cv-text-2);+ text-transform: capitalize;+}+.yl-chain {+ color: var(--cv-text-2);+}++.yl-apy .big {+ font-weight: 700;+ color: var(--cv-text);+ font-variant-numeric: tabular-nums;+}+.yl-apy .sub {+ display: block;+ font-size: 0.6875rem;+ font-weight: 400;+ color: var(--cv-text-3);+ margin-top: 0.1rem;+ white-space: nowrap;+}++.cv-table td.num {+ text-align: right;+ font-variant-numeric: tabular-nums;+}+.cv-table td.dim {+ color: var(--cv-text-3);+}++/* Risk / outlook chips */+.yl-chips {+ white-space: nowrap;+}+.yl-chip {+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ border-radius: var(--cv-radius-sm);+ padding: 0.1rem 0.4rem;+ font-size: 0.6875rem;+ font-weight: 600;+ line-height: 1.4;+ white-space: nowrap;+}+.yl-chip + .yl-chip {+ margin-left: 0.3rem;+}+.yl-chip.il-yes {+ color: var(--yl-amber);+ background: var(--yl-amber-soft);+}+.yl-chip.il-no {+ color: var(--cv-green);+ background: var(--cv-green-soft);+}+.yl-chip.outlook {+ font-weight: 500;+ color: var(--cv-text-2);+ background: var(--cv-surface-3);+}+.yl-chip.outlook.up {+ color: var(--cv-green);+ background: var(--cv-green-soft);+}+.yl-chip.outlook.down {+ color: var(--cv-red);+ background: var(--cv-red-soft);+}++/* ── Row drawer ─────────────────────────────────────────────────────────── */++.yl-drawer-row.is-open td {+ background: var(--cv-surface-2);+}+.yl-drawer-cell {+ padding: 0 !important;+ border-bottom: 1px solid var(--cv-border);+}+.yl-drawer {+ padding: 1rem 1.25rem 1.25rem;+ animation: ylDrawerIn 0.22s ease;+}+@keyframes ylDrawerIn {+ from {+ opacity: 0;+ transform: translateY(-4px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++.yl-chart-skel,+.yl-chart-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 0.75rem;+ min-height: 180px;+ color: var(--cv-text-3);+ font-size: 0.875rem;+ text-align: center;+}+.yl-chart-skel {+ flex-direction: row;+}++.yl-chart-head {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ margin-bottom: 0.5rem;+}+.yl-legend {+ display: flex;+ gap: 1rem;+}+.yl-leg {+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+ font-size: 0.75rem;+ font-weight: 500;+ color: var(--cv-text-2);+}+.yl-leg i {+ width: 0.75rem;+ height: 0.2rem;+ border-radius: 2px;+ display: inline-block;+}+.yl-leg.apy i {+ background: var(--yl-apy-axis);+}+.yl-leg.tvl i {+ background: var(--yl-tvl-axis);+}+.yl-chart-range {+ font-size: 0.75rem;+ color: var(--cv-text-3);+ font-variant-numeric: tabular-nums;+}++.yl-chart-area {+ position: relative;+}+.yl-chart-area svg {+ display: block;+ width: 100%;+ height: auto;+ touch-action: none;+}++.yl-tip {+ position: absolute;+ top: 0;+ transform: translateX(-50%);+ pointer-events: none;+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ box-shadow: var(--cv-shadow-card);+ padding: 0.5rem 0.625rem;+ font-size: 0.75rem;+ white-space: nowrap;+ z-index: 2;+}+.yl-tip .d {+ color: var(--cv-text-3);+ margin: 0 0 0.25rem;+ font-size: 0.6875rem;+}+.yl-tip .a {+ display: flex;+ align-items: center;+ gap: 0.35rem;+ margin: 0.1rem 0;+ color: var(--cv-text);+ font-variant-numeric: tabular-nums;+}+.yl-tip .a i {+ width: 0.6rem;+ height: 0.6rem;+ border-radius: 2px;+ flex-shrink: 0;+}+.yl-tip .a i.apy {+ background: var(--yl-apy-axis);+}+.yl-tip .a i.tvl {+ background: var(--yl-tvl-axis);+}++/* ── Load more / empty / retry / attribution ────────────────────────────── */++.yl-more-wrap {+ display: flex;+ justify-content: center;+ margin: 1.25rem 0 0;+}+.yl-more {+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-size: 0.875rem;+ font-weight: 500;+ color: var(--cv-text);+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ padding: 0.625rem 1.5rem;+ transition:+ background 0.15s,+ border-color 0.15s;+}+.yl-more:hover:not(:disabled) {+ background: var(--cv-surface-2);+ border-color: var(--cv-border-hover);+}+.yl-more:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}+.yl-more:disabled {+ opacity: 0.6;+ cursor: default;+}++.yl-retry {+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-size: 0.8125rem;+ font-weight: 500;+ color: #fff;+ background: var(--cv-accent);+ border: 0;+ border-radius: var(--cv-radius-md);+ padding: 0.5rem 1.25rem;+ transition: background 0.15s;+}+.yl-retry:hover {+ background: var(--cv-accent-hover);+}+.yl-retry:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++.cv-empty-sub {+ font-size: 0.8125rem;+ color: var(--cv-text-3);+ margin: 0.5rem 0 1rem;+}++.yl-attribution {+ font-size: 0.75rem;+ color: var(--cv-text-3);+ margin-top: 0.75rem;+ max-width: 46rem;+}+.yl-attribution a {+ color: var(--cv-accent);+}+.yl-attribution a:hover {+ text-decoration: underline;+}++@media (max-width: 639px) {+ .yl-search {+ flex-basis: 100%;+ max-width: none;+ }+ .yl-toggle {+ flex: 1 1 45%;+ }+}diff --git a/src/yields.js b/src/yields.jsnew file mode 100644index 000000000..b59bf4a2b--- /dev/null+++ b/src/yields.js@@ -0,0 +1,672 @@+// /yields — DeFi yield-pool explorer over /api/defi/yields (DeFiLlama, keyless).+// The API does all filtering, sorting and paging server-side against a slimmed,+// cached copy of DeFiLlama's ~15k-pool dataset, so this module keeps no local+// pool cache: every filter change is a fresh request, and "Load more" appends+// the next offset window. Each row expands into an inline drawer that fetches+// the pool's APY + TVL history (chart mode) and draws a dual-axis SVG chart+// with a hover crosshair adapted from src/coin-page.js.++import { formatUsd, escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── Formatting ──────────────────────────────────────────────────────────────++/** Unsigned APY percentage: "2.21%". Em dash for missing input. */+function fmtApy(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ return `${n.toFixed(2)}%`;+}++/** Signed APY delta with 2 decimals: "+0.31%" / "−0.07%". */+function fmtDelta(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ return `${n >= 0 ? '+' : '−'}${Math.abs(n).toFixed(2)}%`;+}++// ── State ───────────────────────────────────────────────────────────────────++const PAGE_SIZE = 100;++const state = {+ // filters (mirrored to the URL query string)+ chain: '',+ project: '',+ stablecoin: false,+ minTvl: 0,+ search: '',+ sort: 'tvl', // tvl | apy+ // data+ pools: [],+ total: 0,+ offset: 0,+ facets: null,+ facetsReady: false,+ stats: null,+ // ui+ loading: true,+ loadingMore: false,+ error: false,+ updatedAt: null,+ expanded: null, // pool uuid whose drawer is open+ charts: new Map(), // uuid → { status:'loading'|'ready'|'empty'|'error', points }+};++// ── URL sync ────────────────────────────────────────────────────────────────++function readUrl() {+ const p = new URLSearchParams(location.search);+ state.chain = (p.get('chain') || '').trim();+ state.project = (p.get('project') || '').trim();+ state.stablecoin = p.get('stablecoin') === 'true';+ state.minTvl = Math.max(0, Number(p.get('minTvl')) || 0);+ state.search = (p.get('search') || '').trim();+ state.sort = p.get('sort') === 'apy' ? 'apy' : 'tvl';+}++function writeUrl() {+ const p = new URLSearchParams();+ if (state.chain) p.set('chain', state.chain);+ if (state.project) p.set('project', state.project);+ if (state.stablecoin) p.set('stablecoin', 'true');+ if (state.minTvl) p.set('minTvl', String(state.minTvl));+ if (state.search) p.set('search', state.search);+ if (state.sort !== 'tvl') p.set('sort', state.sort);+ const qs = p.toString();+ const url = qs ? `${location.pathname}?${qs}` : location.pathname;+ history.replaceState(null, '', url);+}++function buildQuery(offset) {+ const p = new URLSearchParams();+ if (state.chain) p.set('chain', state.chain);+ if (state.project) p.set('project', state.project);+ if (state.stablecoin) p.set('stablecoin', 'true');+ if (state.minTvl) p.set('minTvl', String(state.minTvl));+ if (state.search) p.set('search', state.search);+ p.set('sort', state.sort);+ p.set('limit', String(PAGE_SIZE));+ p.set('offset', String(offset));+ return `/api/defi/yields?${p.toString()}`;+}++// ── Filter controls ─────────────────────────────────────────────────────────++function syncControlsFromState() {+ $('yl-search-input').value = state.search;+ $('yl-mintvl').value = String(state.minTvl);+ $('yl-stable').checked = state.stablecoin;+ $('yl-chain').value = state.chain;+ $('yl-project').value = state.project;+ $('yl-sort')+ .querySelectorAll('button')+ .forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.sort === state.sort)));+}++// Populate the chain/project dropdowns once, from the filter-agnostic facets the+// API returns. A pre-selected value from the URL that isn't in the top-N facet+// list is preserved as an extra option so the filter still reflects the URL.+function populateFacets() {+ if (state.facetsReady || !state.facets) return;+ fillSelect($('yl-chain'), state.facets.chains, state.chain);+ fillSelect($('yl-project'), state.facets.projects, state.project);+ state.facetsReady = true;+}++function fillSelect(sel, items, current) {+ const seen = new Set();+ const opts = ['<option value="">' + (sel.id === 'yl-chain' ? 'All chains' : 'All projects') + '</option>'];+ for (const it of items || []) {+ seen.add(it.name);+ opts.push(+ `<option value="${esc(it.name)}">${esc(it.name)} (${it.pool_count.toLocaleString('en-US')})</option>`,+ );+ }+ if (current && !seen.has(current)) {+ opts.push(`<option value="${esc(current)}">${esc(current)}</option>`);+ }+ sel.innerHTML = opts.join('');+ sel.value = current || '';+}++function resetFilters() {+ state.chain = '';+ state.project = '';+ state.stablecoin = false;+ state.minTvl = 0;+ state.search = '';+ state.sort = 'tvl';+ syncControlsFromState();+ writeUrl();+ load();+}++// ── Stats ───────────────────────────────────────────────────────────────────++function renderStats() {+ const s = state.stats;+ if (!s) return;+ $('yl-stat-pools').textContent = s.pool_count != null ? s.pool_count.toLocaleString('en-US') : '—';+ $('yl-stat-tvl').textContent = formatUsd(s.total_tvl);+ $('yl-stat-apy').textContent = fmtApy(s.median_apy);+}++function updateCount() {+ const el = $('yl-count');+ if (!el) return;+ if (!state.stats && !state.error) {+ el.textContent = '';+ return;+ }+ if (state.error) {+ el.textContent = '';+ return;+ }+ const shown = state.pools.length;+ el.textContent = `${shown.toLocaleString('en-US')} of ${state.total.toLocaleString('en-US')} pools`;+}++// ── Table rendering ─────────────────────────────────────────────────────────++const COLUMNS = [+ { label: 'Pool', left: true },+ { label: 'Project', left: true, hide: 'hide-md' },+ { label: 'Chain', left: true, hide: 'hide-sm' },+ { label: 'TVL' },+ { label: 'APY' },+ { label: '30d Avg', hide: 'hide-lg' },+ { label: 'Δ7d', hide: 'hide-md' },+ { label: 'Risk / Outlook', left: true, hide: 'hide-lg' },+];++function skeletonRows(n) {+ return (+ '<div class="cv-table-wrap" style="padding:0.75rem">' ++ Array.from(+ { length: n },+ () => '<div class="cv-skel" style="height:2.75rem;margin:0.375rem 0"></div>',+ ).join('') ++ '</div>'+ );+}++function ilChip(risk) {+ if (risk === 'yes') return '<span class="yl-chip il-yes">IL risk</span>';+ if (risk === 'no') return '<span class="yl-chip il-no">No IL</span>';+ return '';+}++function outlookChip(outlook, confidence) {+ if (!outlook) return '';+ const conf = confidence != null && Number.isFinite(confidence) ? ` ${Math.round(confidence)}%` : '';+ const up = /up/i.test(outlook);+ const down = /down/i.test(outlook);+ const cls = up ? 'up' : down ? 'down' : 'flat';+ return `<span class="yl-chip outlook ${cls}" title="Predicted outlook">${esc(outlook)}${conf}</span>`;+}++function apyCell(p) {+ const hasSplit = p.apy_base != null && p.apy_reward != null && p.apy_reward > 0;+ const sub = hasSplit+ ? `<span class="sub">${fmtApy(p.apy_base)} base + ${fmtApy(p.apy_reward)} reward</span>`+ : '';+ return `<td class="num yl-apy"><span class="big">${esc(fmtApy(p.apy))}</span>${sub}</td>`;+}++function deltaCell(v) {+ if (v == null || !Number.isFinite(v)) return '<td class="num hide-md dim">—</td>';+ const cls = v >= 0 ? 'cv-up' : 'cv-down';+ return `<td class="num hide-md ${cls}">${esc(fmtDelta(v))}</td>`;+}++function rowHtml(p) {+ const expanded = state.expanded === p.pool;+ const meta = p.pool_meta ? `<span class="meta">${esc(p.pool_meta)}</span>` : '';+ const stableTag = p.stablecoin ? '<span class="yl-tag">stable</span>' : '';+ return `+ <tr class="yl-row${expanded ? ' is-open' : ''}" data-pool="${esc(p.pool)}" tabindex="0" role="button"+ aria-expanded="${expanded ? 'true' : 'false'}" aria-label="Toggle history for ${esc(p.symbol)} on ${esc(p.project)}">+ <td class="left yl-pool">+ <span class="chev" aria-hidden="true">▸</span>+ <span class="pool-inner">+ <span class="sym">${esc(p.symbol)}${stableTag}</span>+ ${meta}+ </span>+ </td>+ <td class="left hide-md yl-project">${esc(p.project)}</td>+ <td class="left hide-sm yl-chain">${esc(p.chain)}</td>+ <td class="num">${esc(formatUsd(p.tvl_usd))}</td>+ ${apyCell(p)}+ <td class="num hide-lg dim">${esc(fmtApy(p.apy_mean_30d))}</td>+ ${deltaCell(p.apy_change_7d)}+ <td class="left hide-lg yl-chips">${ilChip(p.il_risk)}${outlookChip(p.outlook, p.outlook_confidence)}</td>+ </tr>+ <tr class="yl-drawer-row${expanded ? ' is-open' : ''}" data-drawer="${esc(p.pool)}"${expanded ? '' : ' hidden'}>+ <td colspan="${COLUMNS.length}" class="yl-drawer-cell">+ <div class="yl-drawer" id="drawer-${esc(p.pool)}"></div>+ </td>+ </tr>`;+}++function renderTable() {+ const el = $('yl-table');++ if (state.error) {+ el.innerHTML = `+ <div class="cv-empty">+ <p>DeFi yield data is unavailable right now.</p>+ <button type="button" class="yl-retry" id="yl-retry">Retry</button>+ </div>`;+ $('yl-retry')?.addEventListener('click', () => load());+ $('yl-more-wrap').hidden = true;+ updateCount();+ return;+ }++ if (state.loading) {+ el.innerHTML = skeletonRows(12);+ $('yl-more-wrap').hidden = true;+ return;+ }++ if (!state.pools.length) {+ el.innerHTML = `+ <div class="cv-empty">+ <p>No pools match these filters.</p>+ <p class="cv-empty-sub">Loosen your chain, project, TVL or stablecoin filters to see more.</p>+ <button type="button" class="yl-retry" id="yl-empty-reset">Reset filters</button>+ </div>`;+ $('yl-empty-reset')?.addEventListener('click', resetFilters);+ $('yl-more-wrap').hidden = true;+ updateCount();+ return;+ }++ const head = COLUMNS.map(+ (c) => `<th scope="col" class="${c.left ? 'left' : ''} ${c.hide || ''}">${esc(c.label)}</th>`,+ ).join('');++ const body = state.pools.map(rowHtml).join('');++ el.innerHTML = `+ <div class="cv-table-wrap yl-table-wrap">+ <table class="cv-table yl-table">+ <thead><tr>${head}</tr></thead>+ <tbody>${body}</tbody>+ </table>+ </div>`;++ el.querySelectorAll('tr.yl-row').forEach((tr) => {+ const toggle = () => toggleRow(tr.dataset.pool);+ tr.addEventListener('click', toggle);+ tr.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ toggle();+ }+ });+ });++ // Re-open drawer content if one was expanded before a re-render.+ if (state.expanded) renderDrawer(state.expanded);++ $('yl-more-wrap').hidden = state.pools.length >= state.total;+ updateCount();+}++// ── Row expansion + chart ───────────────────────────────────────────────────++function toggleRow(pool) {+ if (state.expanded === pool) {+ state.expanded = null;+ renderTable();+ return;+ }+ state.expanded = pool;+ renderTable();+ loadChart(pool);+ // Bring the freshly-opened drawer into view on small screens.+ const row = $('yl-table').querySelector(`tr.yl-row[data-pool="${cssEsc(pool)}"]`);+ row?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });+}++function cssEsc(s) {+ return typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(s) : String(s).replace(/"/g, '\\"');+}++async function loadChart(pool) {+ const cached = state.charts.get(pool);+ if (cached && (cached.status === 'ready' || cached.status === 'empty')) {+ renderDrawer(pool);+ return;+ }+ state.charts.set(pool, { status: 'loading', points: [] });+ renderDrawer(pool);+ try {+ const data = await getJson(`/api/defi/yields?pool=${encodeURIComponent(pool)}`);+ const points = Array.isArray(data?.points) ? data.points : [];+ state.charts.set(pool, { status: points.length ? 'ready' : 'empty', points });+ } catch (err) {+ // A 404 from the API means "no history for this pool", not an outage.+ if (err?.status === 404) state.charts.set(pool, { status: 'empty', points: [] });+ else state.charts.set(pool, { status: 'error', points: [] });+ }+ if (state.expanded === pool) renderDrawer(pool);+}++function renderDrawer(pool) {+ const host = $(`drawer-${pool}`);+ if (!host) return;+ const c = state.charts.get(pool) || { status: 'loading', points: [] };++ if (c.status === 'loading') {+ host.innerHTML =+ '<div class="yl-chart-skel"><span class="cv-spinner" aria-hidden="true"></span>Loading APY & TVL history…</div>';+ return;+ }+ if (c.status === 'error') {+ host.innerHTML = `+ <div class="yl-chart-state">+ <p>Couldn't load this pool's history.</p>+ <button type="button" class="yl-retry" data-retry="${esc(pool)}">Retry</button>+ </div>`;+ host.querySelector('[data-retry]')?.addEventListener('click', () => {+ state.charts.delete(pool);+ loadChart(pool);+ });+ return;+ }+ if (c.status === 'empty' || c.points.length < 2) {+ host.innerHTML = '<div class="yl-chart-state">No history yet for this pool.</div>';+ return;+ }++ host.innerHTML = renderChartSvg(pool, c.points);+ wireChartPointer(pool, c.points);+}++// ── Dual-axis SVG chart (APY left, TVL right) ───────────────────────────────++const CW = 760;+const CH = 220;+const CP = { top: 18, right: 66, bottom: 26, left: 56 };++function seriesExtent(points, key) {+ let min = Infinity;+ let max = -Infinity;+ for (const p of points) {+ const v = p[key];+ if (v == null || !Number.isFinite(v)) continue;+ if (v < min) min = v;+ if (v > max) max = v;+ }+ if (!Number.isFinite(min)) return null;+ return { min, max, range: max - min || Math.abs(max) || 1 };+}++function linePath(points, key, ext) {+ const w = CW - CP.left - CP.right;+ const h = CH - CP.top - CP.bottom;+ const n = points.length;+ let d = '';+ let started = false;+ for (let i = 0; i < n; i++) {+ const v = points[i][key];+ if (v == null || !Number.isFinite(v)) {+ started = false; // break the line across a gap+ continue;+ }+ const x = CP.left + (i / (n - 1)) * w;+ const y = CP.top + h - ((v - ext.min) / ext.range) * h;+ d += `${started ? 'L' : 'M'}${x.toFixed(2)},${y.toFixed(2)} `;+ started = true;+ }+ return d.trim();+}++function renderChartSvg(pool, points) {+ const apyExt = seriesExtent(points, 'apy');+ const tvlExt = seriesExtent(points, 'tvl_usd');+ const h = CH - CP.top - CP.bottom;++ const apyPath = apyExt ? linePath(points, 'apy', apyExt) : '';+ const tvlPath = tvlExt ? linePath(points, 'tvl_usd', tvlExt) : '';++ // Left axis labels (APY), right axis labels (TVL); 4 gridlines shared.+ const steps = 4;+ let grid = '';+ for (let i = 0; i <= steps; i++) {+ const y = CP.top + h - (i / steps) * h;+ const apyLabel = apyExt ? fmtApy(apyExt.min + (apyExt.range * i) / steps) : '';+ const tvlLabel = tvlExt ? formatUsd(tvlExt.min + (tvlExt.range * i) / steps) : '';+ grid += `<line x1="${CP.left}" y1="${y}" x2="${CW - CP.right}" y2="${y}" stroke="var(--cv-border)" stroke-width="0.5" stroke-dasharray="4 4" opacity="0.5"/>`;+ grid += `<text x="${CP.left - 6}" y="${y + 3}" text-anchor="end" font-size="9" fill="var(--yl-apy-axis)">${esc(apyLabel)}</text>`;+ grid += `<text x="${CW - CP.right + 6}" y="${y + 3}" font-size="9" fill="var(--yl-tvl-axis)">${esc(tvlLabel)}</text>`;+ }++ const from = points[0]?.t;+ const to = points[points.length - 1]?.t;++ return `+ <div class="yl-chart-head">+ <div class="yl-legend">+ <span class="yl-leg apy"><i></i>APY (left)</span>+ <span class="yl-leg tvl"><i></i>TVL (right)</span>+ </div>+ <span class="yl-chart-range">${esc(fmtDate(from))} – ${esc(fmtDate(to))}</span>+ </div>+ <div class="yl-chart-area">+ <svg viewBox="0 0 ${CW} ${CH}" role="img" preserveAspectRatio="none"+ aria-label="APY and TVL history for this pool over ${points.length} points">+ ${grid}+ ${tvlPath ? `<path d="${tvlPath}" fill="none" stroke="var(--yl-tvl-axis)" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" opacity="0.9"/>` : ''}+ ${apyPath ? `<path d="${apyPath}" fill="none" stroke="var(--yl-apy-axis)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>` : ''}+ <g class="yl-cross" data-cross="${esc(pool)}" hidden>+ <line class="cl" x1="0" y1="${CP.top}" x2="0" y2="${CH - CP.bottom}" stroke="var(--cv-text-3)" stroke-width="0.5" stroke-dasharray="3 3"/>+ <circle class="dot-apy" r="4" fill="var(--yl-apy-axis)" stroke="var(--cv-surface)" stroke-width="2" hidden/>+ <circle class="dot-tvl" r="4" fill="var(--yl-tvl-axis)" stroke="var(--cv-surface)" stroke-width="2" hidden/>+ </g>+ </svg>+ <div class="yl-tip" data-tip="${esc(pool)}" hidden>+ <p class="d"></p>+ <p class="a"><i class="apy"></i><span></span></p>+ <p class="a"><i class="tvl"></i><span></span></p>+ </div>+ </div>`;+}++function fmtDate(t) {+ if (t == null) return '';+ const d = new Date(t);+ if (Number.isNaN(d.getTime())) return '';+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });+}++function wireChartPointer(pool, points) {+ const host = $(`drawer-${pool}`);+ const svg = host?.querySelector('svg');+ const cross = host?.querySelector('.yl-cross');+ const tip = host?.querySelector('.yl-tip');+ if (!svg || !cross || !tip) return;++ const apyExt = seriesExtent(points, 'apy');+ const tvlExt = seriesExtent(points, 'tvl_usd');+ const w = CW - CP.left - CP.right;+ const h = CH - CP.top - CP.bottom;+ const n = points.length;+ const crossLine = cross.querySelector('.cl');+ const dotApy = cross.querySelector('.dot-apy');+ const dotTvl = cross.querySelector('.dot-tvl');++ function show(clientX) {+ const rect = svg.getBoundingClientRect();+ const mx = ((clientX - rect.left) / rect.width) * CW;+ const i = Math.max(0, Math.min(n - 1, Math.round(((mx - CP.left) / w) * (n - 1))));+ const pt = points[i];+ const x = CP.left + (i / (n - 1)) * w;+ cross.removeAttribute('hidden');+ crossLine.setAttribute('x1', x);+ crossLine.setAttribute('x2', x);++ if (apyExt && pt.apy != null && Number.isFinite(pt.apy)) {+ const y = CP.top + h - ((pt.apy - apyExt.min) / apyExt.range) * h;+ dotApy.setAttribute('cx', x);+ dotApy.setAttribute('cy', y);+ dotApy.removeAttribute('hidden');+ } else {+ dotApy.setAttribute('hidden', '');+ }+ if (tvlExt && pt.tvl_usd != null && Number.isFinite(pt.tvl_usd)) {+ const y = CP.top + h - ((pt.tvl_usd - tvlExt.min) / tvlExt.range) * h;+ dotTvl.setAttribute('cx', x);+ dotTvl.setAttribute('cy', y);+ dotTvl.removeAttribute('hidden');+ } else {+ dotTvl.setAttribute('hidden', '');+ }++ tip.hidden = false;+ tip.style.left = `${(x / CW) * 100}%`;+ tip.querySelector('.d').textContent = fmtDate(pt.t);+ tip.querySelectorAll('.a span')[0].textContent = `APY ${fmtApy(pt.apy)}`;+ tip.querySelectorAll('.a span')[1].textContent = `TVL ${formatUsd(pt.tvl_usd)}`;+ }+ function hide() {+ cross.setAttribute('hidden', '');+ tip.hidden = true;+ }+ svg.addEventListener('pointermove', (e) => show(e.clientX));+ svg.addEventListener('pointerdown', (e) => show(e.clientX));+ svg.addEventListener('pointerleave', hide);+}++// ── Data loading ────────────────────────────────────────────────────────────++async function load() {+ state.loading = true;+ state.error = false;+ state.offset = 0;+ state.expanded = null;+ renderTable();+ try {+ const data = await getJson(buildQuery(0));+ state.pools = Array.isArray(data.pools) ? data.pools : [];+ state.total = Number(data.total) || state.pools.length;+ state.offset = state.pools.length;+ state.facets = data.facets || state.facets;+ state.stats = data.stats || state.stats;+ state.updatedAt = data.updated_at || null;+ state.loading = false;+ populateFacets();+ renderStats();+ $('yl-updated').textContent = state.updatedAt+ ? `Updated ${new Date(state.updatedAt).toLocaleTimeString('en-US')} · DeFiLlama`+ : '';+ } catch {+ state.loading = false;+ state.error = true;+ $('yl-updated').textContent = '';+ }+ renderTable();+}++async function loadMore() {+ if (state.loadingMore || state.pools.length >= state.total) return;+ state.loadingMore = true;+ const btn = $('yl-more');+ btn.disabled = true;+ btn.textContent = 'Loading…';+ try {+ const data = await getJson(buildQuery(state.offset));+ const more = Array.isArray(data.pools) ? data.pools : [];+ state.pools = state.pools.concat(more);+ state.total = Number(data.total) || state.total;+ state.offset = state.pools.length;+ renderTable();+ } catch {+ btn.textContent = 'Retry loading more';+ btn.disabled = false;+ state.loadingMore = false;+ return;+ }+ state.loadingMore = false;+ btn.disabled = false;+ btn.textContent = 'Load more pools';+}++// ── Wiring ──────────────────────────────────────────────────────────────────++function wireControls() {+ const input = $('yl-search-input');+ let timer = null;+ input.addEventListener('input', () => {+ clearTimeout(timer);+ timer = setTimeout(() => {+ const v = input.value.trim();+ if (v === state.search) return;+ state.search = v;+ writeUrl();+ load();+ }, 300);+ });++ $('yl-chain').addEventListener('change', (e) => {+ state.chain = e.target.value;+ writeUrl();+ load();+ });+ $('yl-project').addEventListener('change', (e) => {+ state.project = e.target.value;+ writeUrl();+ load();+ });+ $('yl-mintvl').addEventListener('change', (e) => {+ state.minTvl = Number(e.target.value) || 0;+ writeUrl();+ load();+ });+ $('yl-stable').addEventListener('change', (e) => {+ state.stablecoin = e.target.checked;+ writeUrl();+ load();+ });++ $('yl-sort')+ .querySelectorAll('button')+ .forEach((btn) => {+ btn.addEventListener('click', () => {+ if (state.sort === btn.dataset.sort) return;+ state.sort = btn.dataset.sort;+ $('yl-sort')+ .querySelectorAll('button')+ .forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));+ writeUrl();+ load();+ });+ });++ $('yl-reset').addEventListener('click', resetFilters);+ $('yl-more').addEventListener('click', loadMore);++ // Reflect back/forward navigation into the filters.+ window.addEventListener('popstate', () => {+ readUrl();+ syncControlsFromState();+ load();+ });+}++readUrl();+syncControlsFromState();+wireControls();+load();diff --git a/tests/news-lib.test.js b/tests/news-lib.test.jsindex 6078b9ab4..8f5719d4b 100644--- a/tests/news-lib.test.js+++ b/tests/news-lib.test.js@@ -7,8 +7,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';const {parseFeed, lexiconSentiment, extractTickers, articleId, stripHtml, getNews, findArticle,- stripFeedBoilerplate, truncateWords,+ stripFeedBoilerplate, truncateWords, cleanImageUrl, metaContent, extractOgImage,} = await import('../api/_lib/news.js');+const { isFeaturedSource, NEWS_SOURCES } = await import('../api/_lib/news-sources.js');const RSS_FIXTURE = `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">@@ -128,6 +129,73 @@ describe('enrichment', () => {});});+describe('image hygiene', () => {+ it('cleanImageUrl keeps real https URLs and upgrades http / protocol-relative', () => {+ expect(cleanImageUrl('https://cdn.example.com/a.jpg')).toBe('https://cdn.example.com/a.jpg');+ expect(cleanImageUrl('http://cdn.example.com/a.jpg')).toBe('https://cdn.example.com/a.jpg');+ expect(cleanImageUrl('//cdn.example.com/a.jpg')).toBe('https://cdn.example.com/a.jpg');+ });++ it('cleanImageUrl rejects data: URIs, relative paths, and tracking pixels', () => {+ expect(cleanImageUrl('data:image/svg+xml,%3Csvg%3E')).toBeNull(); // ZeroHedge ships this+ expect(cleanImageUrl('/images/local.png')).toBeNull();+ expect(cleanImageUrl('ftp://example.com/a.jpg')).toBeNull();+ expect(cleanImageUrl('https://stats.example.com/1x1.gif')).toBeNull();+ expect(cleanImageUrl('https://example.com/spacer.gif')).toBeNull();+ expect(cleanImageUrl('https://feeds.feedburner.com/~r/site/~4/abc')).toBeNull();+ expect(cleanImageUrl('')).toBeNull();+ expect(cleanImageUrl(null)).toBeNull();+ });++ it('parseFeed falls through junk media:content to a real enclosure image', () => {+ const xml = `<?xml version="1.0"?><rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">+ <channel><item>+ <title>Story with a junk media slot</title>+ <link>https://example.com/story</link>+ <media:content url="data:image/svg+xml,%3Csvg%3E"/>+ <enclosure url="https://cdn.example.com/real.jpg" type="image/jpeg"/>+ </item></channel></rss>`;+ const [a] = parseFeed(xml, 'coindesk');+ expect(a.image).toBe('https://cdn.example.com/real.jpg');+ });++ it('extractOgImage reads og:image / twitter:image in either attribute order', () => {+ expect(+ extractOgImage('<head><meta property="og:image" content="https://pub.example.com/og.jpg"/></head>'),+ ).toBe('https://pub.example.com/og.jpg');+ expect(+ extractOgImage('<head><meta content="https://pub.example.com/tw.jpg" name="twitter:image"/></head>'),+ ).toBe('https://pub.example.com/tw.jpg');+ // secure_url wins over the plain og:image+ expect(+ extractOgImage(+ '<head><meta property="og:image" content="http://pub.example.com/a.jpg"/><meta property="og:image:secure_url" content="https://pub.example.com/b.jpg"/></head>',+ ),+ ).toBe('https://pub.example.com/b.jpg');+ // a data:-URI og:image is junk, not a preview+ expect(extractOgImage('<meta property="og:image" content="data:image/png;base64,xx"/>')).toBeNull();+ expect(extractOgImage('<head><title>no meta</title></head>')).toBeNull();+ });++ it('metaContent returns null when the tag is absent', () => {+ expect(metaContent('<head></head>', ['og:image'])).toBeNull();+ });+});++describe('featured sources', () => {+ it('admits tier1/tier2 and high-credibility outlets, refuses the long tail', () => {+ expect(isFeaturedSource('coindesk')).toBe(true); // tier2, 0.95+ expect(isFeaturedSource('theblock')).toBe(true); // tier2, 0.93+ expect(isFeaturedSource('bbc_business')).toBe(true); // tier1+ expect(isFeaturedSource('watcherguru')).toBe(false); // tier3, 0.68+ expect(isFeaturedSource('not-a-source')).toBe(false);+ // the bar yields a real set — enough for a Featured tab, far below the registry+ const featured = Object.keys(NEWS_SOURCES).filter(isFeaturedSource);+ expect(featured.length).toBeGreaterThanOrEqual(8);+ expect(featured.length).toBeLessThan(Object.keys(NEWS_SOURCES).length / 4);+ });+});+describe('getNews aggregation', () => {const originalFetch = global.fetch;beforeEach(() => {diff --git a/vercel.json b/vercel.jsonindex 8ce4c243e..1745edb8f 100644--- a/vercel.json+++ b/vercel.json@@ -956,6 +956,10 @@"src": "/markets/news/article/?","dest": "/news-article.html"},+ {+ "src": "/markets/news/(20[0-9]{2}-[0-9]{2})/([a-f0-9]{16})(?:-[a-zA-Z0-9-]{0,120})?/?",+ "dest": "/api/news/story-page?month=$1&id=$2"+ },{"src": "/markets/archive/?","dest": "/news-archive.html"@@ -1008,6 +1012,18 @@"src": "/stablecoins/?","dest": "/stablecoins.html"},+ {+ "src": "/yields/?",+ "dest": "/yields.html"+ },+ {+ "src": "/exchange/([a-z0-9_-]{1,60})/?",+ "dest": "/exchange.html"+ },+ {+ "src": "/category/([a-z0-9-]{1,80})/?",+ "dest": "/category.html"+ },{"src": "/bnb/?","dest": "/bnb.html"@@ -4230,7 +4246,7 @@"dest": "/api/sitemap"},{- "src": "/sitemap/(core|agents|avatars|widgets|profiles)\\.xml",+ "src": "/sitemap/(core|agents|avatars|widgets|profiles|news)\\.xml","dest": "/api/sitemap/[type]?type=$1"},{diff --git a/vite.config.js b/vite.config.jsindex 0ef2e131f..ff38b7891 100644--- a/vite.config.js+++ b/vite.config.js@@ -482,6 +482,9 @@ const appConfig = {defi: resolve(__dirname, 'pages/defi.html'),chains: resolve(__dirname, 'pages/chains.html'),stablecoins: resolve(__dirname, 'pages/stablecoins.html'),+ exchange: resolve(__dirname, 'pages/exchange.html'),+ category: resolve(__dirname, 'pages/category.html'),+ yields: resolve(__dirname, 'pages/yields.html'),bnb: resolve(__dirname, 'pages/bnb.html'),'bnb-latency': resolve(__dirname, 'pages/bnb-latency.html'),vault: resolve(__dirname, 'pages/vault.html'),@@ -1072,6 +1075,8 @@ support: resolve(__dirname, 'pages/support.html'),'/chains/': resolve(root, 'pages/chains.html'),'/stablecoins': resolve(root, 'pages/stablecoins.html'),'/stablecoins/': resolve(root, 'pages/stablecoins.html'),+ '/yields': resolve(root, 'pages/yields.html'),+ '/yields/': resolve(root, 'pages/yields.html'),'/bnb': resolve(root, 'pages/bnb.html'),'/bnb/': resolve(root, 'pages/bnb.html'),'/bnb-latency': resolve(root, 'pages/bnb-latency.html'),@@ -1499,6 +1504,12 @@ support: resolve(__dirname, 'pages/support.html'),/^\/coin\/[a-zA-Z0-9][a-zA-Z0-9_-]{0,99}\/?$/.test(path))filePath = resolve(root, 'pages/coin.html');+ // /exchange/:id → exchange detail page (CoinGecko exchange slug)+ else if (!filePath && /^\/exchange\/[a-z0-9_-]{1,60}\/?$/i.test(path))+ filePath = resolve(root, 'pages/exchange.html');+ // /category/:id → crypto category detail page+ else if (!filePath && /^\/category\/[a-z0-9-]{1,80}\/?$/.test(path))+ filePath = resolve(root, 'pages/category.html');// /@<handle> → public live profile pageelse if (!filePath && /^\/@[a-z0-9_-]{3,30}\/?$/i.test(path))filePath = resolve(root, 'pages/handle.html');