Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(markets): protocol/chain/stablecoin detail pages + fees, DEX volumes, hacks, trending

fudjiae260ab580fe1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e08b8d40b..4a40e93ea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,8 +8,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Dashboard · Billing & Passes** (`/dashboard/billing`) — Manage subscriptions and paid services — Premium pass status, on-chain payment history, API keys, and creator subscriptions.
- **Dashboard · Data API** (`/dashboard/data-api`) — Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage API keys, watch usage, and copy quickstarts.
+- **DeFi Hacks Database** (`/hacks`) — A searchable database of every major DeFi exploit — amount stolen, classification, technique, chains affected, whether it was a bridge hack, and the source, with all-time and trailing-12-month totals. Live from DeFiLlama.
- **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.
+- **DEX Volume Leaderboard** (`/dex-volumes`) — Every decentralized exchange ranked by trading volume, with 24h and 7d totals, 7-day change, and market share, plus an aggregate volume history chart. Live from DeFiLlama.
- **Premium Pass — Monthly Data API Access** (`/docs/premium`) — One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.
+- **Protocol Fees & Revenue** (`/fees`) — Fees paid by users and revenue kept by protocols across all of DeFi, ranked with 24h/7d/30d totals and an aggregate history chart. Toggle between fees and revenue; each protocol links to its detail page. Live from DeFiLlama.
+- **Trending Crypto** (`/markets/trending`) — The most-searched coins, categories, and NFTs on CoinGecko over the last 24 hours — trending rank, price, 24h change, market cap, and volume, each coin and category linking to its detail page. Auto-refreshing.
+- **Detail pages for protocols, chains, and stablecoins — plus fees, DEX volumes, hacks, and trending** — Every DeFiLlama list now opens into a full detail page. A protocol page charts its whole TVL history with funding-round and event markers, breaks TVL down per chain, and shows its fees, revenue, and methodology. A chain page charts TVL, stablecoin supply, and DEX volume side by side with the top protocols on that chain. A stablecoin page charts circulating supply over time, shows the per-chain distribution, and flags how far off-peg it is in basis points. On top of the detail pages there are four new market surfaces: protocol fees and revenue ranked and charted, the DEX-volume leaderboard with market share, a searchable database of every major DeFi hack ($16.7B stolen all-time), and a trending page of the most-searched coins, categories, and NFTs on CoinGecko. Everything is real, key-free data, and the yields, DeFi, chains, and stablecoin tables now link straight into the new detail pages. (`/fees`) `[feature]`
- **Documentation accuracy pass: every tutorial verified against the shipped platform** — We cross-referenced all 300+ docs and specs against the actual codebase and fixed everything that had drifted. The embed snippet in ten tutorials now uses the real two-line form that works on any site, four tutorials that demonstrated retired or never-shipped APIs were rewritten against the live component, the troubleshooting guide now reflects the current Cloud Run production stack with the correct session and storage details, and the manifest, quick-start, and API references now list exactly the providers, attributes, and endpoints that exist today. Every code sample in the affected docs runs as written. (`/docs/tutorials/embed-in-30-seconds`) `[docs, fix]`
- **Premium: one monthly pass instead of paying per call** — Go Premium for $9.99/30 days and stop paying the Data API per search: one Solana payment — in $THREE at 20% off, SOL, or USDC — mints an API key with unmetered archive search and lets your wallet sign in on the archive page instead of paying. Two new dashboard surfaces ship with it: a developer console at /dashboard/data-api (buy or renew the pass, manage and rotate API keys, live usage, copy-paste quickstarts) and Billing & Passes at /dashboard/billing (pass status, on-chain payment history, your subscriptions and paid services in one place). Renewals stack — renewing early adds 30 days to the end, never losing time. (`/docs/premium`) `[feature]`
- **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]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 01ff516da..50bb95f10 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -80,6 +80,7 @@ bottom.
| 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 surfaces III (protocol/chain/stablecoin detail + fees, DEX volumes, hacks, trending) | Detail pages `→ /protocol/:slug /chain/:name /stablecoin/:id` over [api/defi/protocol.js](api/defi/protocol.js), [api/defi/chain.js](api/defi/chain.js), [api/defi/stablecoin.js](api/defi/stablecoin.js); surfaces `→ /fees /dex-volumes /hacks` over [api/defi/](api/defi) (fees, dex-volumes, hacks over DeFiLlama) + `→ /markets/trending` over [api/coin/trending.js](api/coin/trending.js) (CoinGecko /search/trending); list rows in [src/defi.js](src/defi.js), [src/chains.js](src/chains.js), [src/stablecoins.js](src/stablecoins.js) now deep-link into the detail pages | In-repo | Turns the DeFiLlama list pages into full detail experiences: a protocol page (TVL history + hallmark markers, per-chain breakdown, fees/revenue, funding rounds, methodology), a chain page (TVL + stablecoin + DEX-volume charts, top protocols), a stablecoin page (supply history, per-chain distribution, peg-deviation badge). Plus three new market surfaces — protocol fees & revenue, the DEX-volume leaderboard, and a searchable DeFi hacks database ($16.7B all-time) — and a CoinGecko trending page (most-searched coins/categories/NFTs). All real key-free data, cross-linked. 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, image) + 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: /markets/news is “Your briefing” — live news aggregated natively from 192 publisher feeds (Featured/Trending/Saved tabs, breaking ticker, AI briefing card, top-stories hero + rail, search, sentiment, ticker chips, og:image preview resolution for imageless feeds), 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) |
| Premium Data API pass | [api/premium/](api/premium) + [api/_lib/premium.js](api/_lib/premium.js), dashboards [src/dashboard-next/pages/data-api.js](src/dashboard-next/pages/data-api.js) `→ /dashboard/data-api` + [src/dashboard-next/pages/billing.js](src/dashboard-next/pages/billing.js) `→ /dashboard/billing` | In-repo | Monthly pass ($9.99/30d) paid on Solana in $THREE (20% off), SOL, or USDC — replaces per-call x402 on the news archive with an `x402_live_` API key (existing access-control lane) + SIWX browser grants. Quote→sign→verify flow with on-chain balance-delta verification; tables `premium_passes`/`premium_quotes`. Docs: [docs/premium.md](docs/premium.md) |
diff --git a/api/coin/trending.js b/api/coin/trending.js
new file mode 100644
index 000000000..a1118c8b0
--- /dev/null
+++ b/api/coin/trending.js
@@ -0,0 +1,120 @@
+// GET /api/coin/trending
+// ---------------------------------------------------------------------------
+// Most-searched assets on CoinGecko over the last 24h — powers /markets/trending.
+// Proxies CoinGecko /search/trending, the one trending surface the coin-pages
+// proxy never called. That endpoint returns three lists (coins, categories,
+// NFTs); each carries a `data` block that mixes raw numbers with pre-formatted
+// display strings ("$1,234,567"), so every money field is parsed defensively —
+// number passes through, a "$…"/","-grouped string is stripped to digits and
+// parsed, anything else collapses to null so the client never renders NaN.
+// Cached 2 min in-memory + CDN, like the sibling coin endpoints.
+
+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';
+
+const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
+
+// CoinGecko trending money fields arrive either as a raw number (categories'
+// data.market_cap) or a locale-formatted display string ("$1,234,567.89" for
+// coins/NFTs). Accept both: keep finite numbers, strip a string down to its
+// numeric core (drop the currency glyph and thousands separators) and parse,
+// and fail to null on anything else so no NaN reaches the page.
+function parseMoney(v) {
+ if (typeof v === 'number') return Number.isFinite(v) ? v : null;
+ if (typeof v === 'string') {
+ const cleaned = v.replace(/[^0-9.]/g, '');
+ if (!cleaned) return null;
+ const n = Number.parseFloat(cleaned);
+ return Number.isFinite(n) ? n : null;
+ }
+ return null;
+}
+
+// Only pass through a sparkline that is an absolute http(s) URL — CoinGecko
+// serves these as ready-to-embed SVGs; a client <img> renders them directly.
+function sparklineUrl(v) {
+ const s = str(v);
+ return s && /^https?:\/\//i.test(s) ? s : null;
+}
+
+function shapeCoin(entry, index) {
+ const it = entry?.item || {};
+ const d = it.data || {};
+ return {
+ id: str(it.id),
+ name: str(it.name) || str(it.id),
+ symbol: str(it.symbol)?.toUpperCase() ?? null,
+ image: str(it.small) || str(it.thumb) || str(it.large) || null,
+ rank: num(it.market_cap_rank),
+ score: index, // trending position (0 = most searched)
+ price_usd: num(d.price),
+ change_24h_pct: num(d.price_change_percentage_24h?.usd),
+ market_cap_usd: parseMoney(d.market_cap),
+ volume_24h_usd: parseMoney(d.total_volume),
+ sparkline_url: sparklineUrl(d.sparkline),
+ };
+}
+
+function shapeCategory(c) {
+ const d = c?.data || {};
+ return {
+ // CoinGecko category ids in /search/trending are numeric; the slug is the
+ // human-readable path segment the /category/:slug page routes on.
+ id: c?.id ?? null,
+ slug: str(c?.slug),
+ name: str(c?.name) || str(c?.slug) || 'Unnamed sector',
+ coins_count: num(c?.coins_count),
+ mcap_change_1h_pct: num(c?.market_cap_1h_change),
+ market_cap_usd: parseMoney(d.market_cap),
+ };
+}
+
+function shapeNft(n) {
+ const d = n?.data || {};
+ return {
+ id: str(n?.id),
+ name: str(n?.name) || str(n?.id),
+ symbol: str(n?.symbol)?.toUpperCase() ?? null,
+ thumb: str(n?.thumb) || null,
+ floor_price_native: num(n?.floor_price_in_native_currency),
+ native_currency_symbol: str(n?.native_currency_symbol)?.toUpperCase() ?? null,
+ floor_price_usd: parseMoney(d.floor_price),
+ floor_change_24h_pct: num(n?.floor_price_24h_percentage_change),
+ volume_24h_usd: parseMoney(d.h24_volume),
+ };
+}
+
+function shape(raw) {
+ const coins = Array.isArray(raw?.coins)
+ ? raw.coins.map(shapeCoin).filter((c) => c.id)
+ : [];
+ const categories = Array.isArray(raw?.categories)
+ ? raw.categories.map(shapeCategory).filter((c) => c.name)
+ : [];
+ const nfts = Array.isArray(raw?.nfts) ? raw.nfts.map(shapeNft).filter((n) => n.id) : [];
+ return { coins, categories, nfts };
+}
+
+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);
+
+ try {
+ const raw = await geckoFetch('/search/trending', { ttlMs: 120_000, timeoutMs: 10_000 });
+ return json(res, 200, shape(raw), {
+ 'cache-control': 'public, max-age=60, s-maxage=120, stale-while-revalidate=600',
+ });
+ } catch {
+ return error(
+ res,
+ 502,
+ 'upstream_error',
+ 'trending data is unavailable right now — retry shortly',
+ );
+ }
+});
diff --git a/api/defi/chain.js b/api/defi/chain.js
new file mode 100644
index 000000000..50ca2f995
--- /dev/null
+++ b/api/defi/chain.js
@@ -0,0 +1,292 @@
+// GET /api/defi/chain?name=<chain>
+// ---------------------------------------------------------------------------
+// Rich profile for one blockchain — powers the /chain/:name detail page.
+// Fans out across DeFiLlama's keyless feeds (no API key) and stitches them into
+// a single payload the page renders:
+// · /v2/chains → this chain's TVL, native token, chainId,
+// its rank + dominance share of the
+// cross-chain DeFi total
+// · /v2/historicalChainTvl/{name} → full TVL history, downsampled ≤400 pts
+// · /protocols → the protocols deployed on this chain,
+// top 50 by their TVL *on this chain*
+// · stablecoins /stablecoincharts → stablecoin circulating supply history
+// · overview/dexs/{name} → 24h/7d DEX volume + a volume chart
+// · overview/fees/{name} → 24h/7d fees
+// Only the /v2/chains lookup is load-bearing (it resolves the canonical name and
+// the headline stats); every other feed is best-effort via Promise.allSettled,
+// so a chain that has no DEX/stablecoin/fees coverage still renders. DeFiLlama
+// chain names are case-sensitive ("Ethereum", not "ethereum") — the request name
+// is matched case-insensitively against /v2/chains and everything downstream uses
+// the canonical casing. Cached ~5 min in-memory per chain + CDN. 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 NAME_RE = /^[a-z0-9 ._-]{1,40}$/i;
+
+const CHAINS_URL = 'https://api.llama.fi/v2/chains';
+const CHAINS_TTL_MS = 300_000;
+const CHAIN_TTL_MS = 300_000;
+
+const finite = (n) => (Number.isFinite(n) ? n : null);
+
+// ── Upstream helpers ─────────────────────────────────────────────────────────
+
+async function fetchJson(url, { timeout = 10_000 } = {}) {
+ const resp = await fetch(url, {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(timeout),
+ });
+ if (!resp.ok) {
+ const err = new Error(`llama ${resp.status}`);
+ err.status = resp.status;
+ throw err;
+ }
+ return resp.json();
+}
+
+// Evenly downsample an array to at most `max` items, always keeping the first
+// and last (the endpoints anchor a chart's axis + "where it ends now").
+function downsample(arr, max) {
+ if (!Array.isArray(arr) || arr.length <= max) return arr || [];
+ const step = (arr.length - 1) / (max - 1);
+ const out = [];
+ for (let i = 0; i < max; i++) out.push(arr[Math.round(i * step)]);
+ return out;
+}
+
+// ── /v2/chains: canonical-name resolution + market totals ────────────────────
+
+let _chainsCache = null; // { value: { list, totalTvl }, expiresAt }
+
+async function loadChains() {
+ const now = Date.now();
+ if (_chainsCache && _chainsCache.expiresAt > now) return _chainsCache.value;
+
+ const raw = await fetchJson(CHAINS_URL);
+ if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');
+
+ let totalTvl = 0;
+ const list = [];
+ for (const c of raw) {
+ if (typeof c?.name !== 'string') continue;
+ const tvl = Number(c.tvl);
+ const posTvl = Number.isFinite(tvl) && tvl > 0 ? tvl : 0;
+ totalTvl += posTvl;
+ list.push({
+ name: c.name,
+ tvl: posTvl,
+ tokenSymbol: typeof c.tokenSymbol === 'string' && c.tokenSymbol ? c.tokenSymbol : null,
+ chainId: c.chainId != null && Number.isFinite(Number(c.chainId)) ? Number(c.chainId) : null,
+ });
+ }
+ // Rank is assigned over chains with a positive TVL, highest first.
+ const ranked = list.filter((c) => c.tvl > 0).sort((a, b) => b.tvl - a.tvl);
+ const rankByName = new Map(ranked.map((c, i) => [c.name, i + 1]));
+
+ const value = { list, totalTvl, rankByName };
+ _chainsCache = { value, expiresAt: now + CHAINS_TTL_MS };
+ return value;
+}
+
+// Resolve the request name to DeFiLlama's exact casing. Exact hit first, then a
+// case-insensitive match so /chain/ethereum and /chain/Ethereum both land.
+function resolveCanonical(chains, requested) {
+ const exact = chains.list.find((c) => c.name === requested);
+ if (exact) return exact;
+ const lower = requested.toLowerCase();
+ return chains.list.find((c) => c.name.toLowerCase() === lower) || null;
+}
+
+// ── Optional feeds (best-effort) ─────────────────────────────────────────────
+
+function shapeTvlSeries(raw) {
+ if (!Array.isArray(raw)) return [];
+ const pts = [];
+ for (const p of raw) {
+ const t = Number(p?.date) * 1000;
+ const tvl = Number(p?.tvl);
+ if (Number.isFinite(t) && Number.isFinite(tvl)) pts.push({ t, tvl });
+ }
+ return downsample(pts, 400);
+}
+
+// /protocols → the DeFi protocols on this chain, ranked by their TVL on it.
+// CEX "reserves" are excluded for the same reason api/defi/protocols.js drops
+// them: a chain's DeFi profile must not be dwarfed by Binance/OKX custody rows.
+function shapeProtocols(raw, chainName) {
+ if (!Array.isArray(raw)) return { protocols: [], count: 0 };
+ const onChain = [];
+ for (const p of raw) {
+ const chains = Array.isArray(p?.chains) ? p.chains : [];
+ if (!chains.includes(chainName)) continue;
+ if (typeof p.category === 'string' && p.category.toUpperCase() === 'CEX') continue;
+ const tvl = Number(p?.chainTvls?.[chainName]);
+ if (!Number.isFinite(tvl) || tvl <= 0) continue;
+ onChain.push({
+ name: typeof p.name === 'string' ? p.name : 'Unknown',
+ slug: typeof p.slug === 'string' ? p.slug : null,
+ logo: typeof p.logo === 'string' ? p.logo : null,
+ category: typeof p.category === 'string' ? p.category : null,
+ tvl_on_chain: tvl,
+ change_7d: finite(Number(p.change_7d)),
+ });
+ }
+ onChain.sort((a, b) => b.tvl_on_chain - a.tvl_on_chain);
+ return { protocols: onChain.slice(0, 50), count: onChain.length };
+}
+
+// stablecoins/stablecoincharts → USD circulating supply per point. Each point
+// carries every peg (USD/EUR/…) in its own currency AND converted to USD under
+// totalCirculatingUSD; we take the USD-pegged USD figure, the dominant stable
+// supply metric. Returns { total, series } with total = the latest point.
+function shapeStablecoins(raw) {
+ if (!Array.isArray(raw) || !raw.length) return { total: null, series: [] };
+ const pts = [];
+ for (const p of raw) {
+ const t = Number(p?.date) * 1000;
+ const usd = Number(p?.totalCirculatingUSD?.peggedUSD);
+ if (Number.isFinite(t) && Number.isFinite(usd)) pts.push({ t, total: usd });
+ }
+ if (!pts.length) return { total: null, series: [] };
+ return { total: pts[pts.length - 1].total, series: downsample(pts, 200) };
+}
+
+function shapeDex(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const total24h = finite(Number(raw.total24h));
+ const total7d = finite(Number(raw.total7d));
+ // A chain listed on the DEX overview but with no activity returns total24h:
+ // null — nothing to show, so collapse to null and let the page hide the card.
+ if (total24h == null && total7d == null) return null;
+ const chart = Array.isArray(raw.totalDataChart) ? raw.totalDataChart : [];
+ const series = [];
+ for (const p of chart) {
+ const t = Number(p?.[0]) * 1000;
+ const v = Number(p?.[1]);
+ if (Number.isFinite(t) && Number.isFinite(v)) series.push({ t, v });
+ }
+ return {
+ total24h,
+ total7d,
+ change_7dover7d: finite(Number(raw.change_7dover7d)),
+ series: downsample(series, 200),
+ };
+}
+
+function shapeFees(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const total24h = finite(Number(raw.total24h));
+ const total7d = finite(Number(raw.total7d));
+ if (total24h == null && total7d == null) return null;
+ return { total24h, total7d };
+}
+
+// ── Per-chain payload (cached by canonical name) ─────────────────────────────
+
+const _chainCache = new Map(); // canonicalName → { value, expiresAt }
+
+async function buildChain(canonical, chains) {
+ const now = Date.now();
+ const cached = _chainCache.get(canonical.name);
+ if (cached && cached.expiresAt > now) return cached.value;
+
+ const enc = encodeURIComponent(canonical.name);
+ const [tvlRes, protoRes, stableRes, dexRes, feesRes] = await Promise.allSettled([
+ fetchJson(`https://api.llama.fi/v2/historicalChainTvl/${enc}`),
+ fetchJson('https://api.llama.fi/protocols'),
+ fetchJson(`https://stablecoins.llama.fi/stablecoincharts/${enc}`),
+ fetchJson(`https://api.llama.fi/overview/dexs/${enc}?excludeTotalDataChartBreakdown=true`),
+ fetchJson(
+ `https://api.llama.fi/overview/fees/${enc}?excludeTotalDataChart=true&excludeTotalDataChartBreakdown=true`,
+ ),
+ ]);
+
+ const tvlSeries = tvlRes.status === 'fulfilled' ? shapeTvlSeries(tvlRes.value) : [];
+ const { protocols, count: protocolCount } =
+ protoRes.status === 'fulfilled'
+ ? shapeProtocols(protoRes.value, canonical.name)
+ : { protocols: [], count: 0 };
+ const stablecoins =
+ stableRes.status === 'fulfilled' ? shapeStablecoins(stableRes.value) : { total: null, series: [] };
+ const dex = dexRes.status === 'fulfilled' ? shapeDex(dexRes.value) : null;
+ const fees = feesRes.status === 'fulfilled' ? shapeFees(feesRes.value) : null;
+
+ const rank = chains.rankByName.get(canonical.name) ?? null;
+ const share_pct = chains.totalTvl > 0 ? (canonical.tvl / chains.totalTvl) * 100 : null;
+
+ const value = {
+ chain: {
+ name: canonical.name,
+ token_symbol: canonical.tokenSymbol,
+ chain_id: canonical.chainId,
+ tvl: canonical.tvl,
+ rank,
+ share_pct,
+ defi_total_tvl: chains.totalTvl,
+ },
+ tvl_series: tvlSeries,
+ protocols,
+ protocol_count: protocolCount,
+ stablecoins,
+ dex,
+ fees,
+ updated_at: now,
+ };
+
+ // Bound the cache so a scan across every chain name can't grow it unbounded.
+ if (_chainCache.size > 500) _chainCache.clear();
+ _chainCache.set(canonical.name, { value, expiresAt: now + CHAIN_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;
+
+ const rl = await limits.marketDataIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const name = (params.get('name') || '').trim();
+ if (!NAME_RE.test(name)) {
+ return error(
+ res,
+ 400,
+ 'bad_name',
+ 'name must be a blockchain name (1–40 chars: letters, digits, spaces, or . _ -)',
+ );
+ }
+
+ let chains;
+ try {
+ chains = await loadChains();
+ } catch {
+ return error(
+ res,
+ 502,
+ 'upstream_error',
+ 'Chain data is unavailable right now — retry shortly',
+ );
+ }
+
+ const canonical = resolveCanonical(chains, name);
+ if (!canonical) {
+ return error(res, 404, 'not_found', `no blockchain found for "${name}"`);
+ }
+
+ try {
+ const payload = await buildChain(canonical, chains);
+ return json(res, 200, payload, {
+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
+ });
+ } catch {
+ return error(
+ res,
+ 502,
+ 'upstream_error',
+ 'Chain data is unavailable right now — retry shortly',
+ );
+ }
+});
diff --git a/api/defi/dex-volumes.js b/api/defi/dex-volumes.js
new file mode 100644
index 000000000..ab8804d98
--- /dev/null
+++ b/api/defi/dex-volumes.js
@@ -0,0 +1,110 @@
+// GET /api/defi/dex-volumes
+// ---------------------------------------------------------------------------
+// DEX trading-volume rankings for the /dex-volumes page. Fetches DeFiLlama's
+// keyless /overview/dexs dimension feed (no API key). Returns whole-market 24h
+// and 7d volume, the aggregate daily volume chart (downsampled to ≤200 points),
+// the 7d-over-prior-7d change, and the top 100 DEXs by 24h volume. Each DEX's
+// `share_pct` is its slice of the whole-market summed 24h volume, and its `slug`
+// resolves at api.llama.fi/protocol/{slug} (verified) so the page can deep-link
+// to a protocol detail page. Cached 10 min in-memory + CDN. 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 UPSTREAM = 'https://api.llama.fi/overview/dexs?excludeTotalDataChartBreakdown=true';
+const TTL_MS = 600_000;
+const MAX_CHART_POINTS = 200;
+const MAX_PROTOCOLS = 100;
+
+let _cache = null; // { value, expiresAt }
+
+const finite = (n) => (Number.isFinite(n) ? n : null);
+
+// Downsample [[unixSeconds, value], …] to at most `max` points as [{t: ms, value}],
+// always keeping the final point so the line ends where the data does.
+function normalizeChart(raw) {
+ const pts = (Array.isArray(raw) ? raw : [])
+ .filter((p) => Array.isArray(p) && Number.isFinite(Number(p[0])) && Number.isFinite(Number(p[1])))
+ .map((p) => ({ t: Number(p[0]) * 1000, value: Number(p[1]) }));
+ if (pts.length <= MAX_CHART_POINTS) return pts;
+ const step = (pts.length - 1) / (MAX_CHART_POINTS - 1);
+ const out = [];
+ for (let i = 0; i < MAX_CHART_POINTS; i++) out.push(pts[Math.round(i * step)]);
+ return out;
+}
+
+async function build() {
+ const now = Date.now();
+ if (_cache && _cache.expiresAt > now) return _cache.value;
+
+ const resp = await fetch(UPSTREAM, {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!resp.ok) throw new Error(`llama ${resp.status}`);
+ const raw = await resp.json();
+ if (!raw || !Array.isArray(raw.protocols)) throw new Error('unexpected upstream shape');
+
+ const eligible = raw.protocols.filter((p) => Number.isFinite(Number(p?.total24h)));
+ // Denominator for `share_pct` spans every DEX with a positive 24h volume, not
+ // just the top 100 we return — so a DEX's share reflects the whole market.
+ let marketTotal24h = 0;
+ for (const p of eligible) {
+ const v = Number(p.total24h);
+ if (v > 0) marketTotal24h += v;
+ }
+
+ eligible.sort((a, b) => Number(b.total24h) - Number(a.total24h));
+
+ const protocols = eligible.slice(0, MAX_PROTOCOLS).map((p) => {
+ const chains = Array.isArray(p.chains) ? p.chains.filter((c) => typeof c === 'string') : [];
+ const total24h = finite(Number(p.total24h));
+ return {
+ name: typeof p.displayName === 'string' && p.displayName ? p.displayName
+ : typeof p.name === 'string' ? p.name : 'Unknown',
+ // `slug` is DeFiLlama's canonical protocol key — it resolves at
+ // /protocol/{slug} (verified against uniswap-v3 and peers).
+ slug: typeof p.slug === 'string' && p.slug ? p.slug : null,
+ logo: typeof p.logo === 'string' ? p.logo : null,
+ chains,
+ total24h,
+ total7d: finite(Number(p.total7d)),
+ change_7d: finite(Number(p.change_7d)),
+ share_pct: marketTotal24h > 0 && total24h != null ? (total24h / marketTotal24h) * 100 : 0,
+ };
+ });
+
+ const value = {
+ total24h: finite(Number(raw.total24h)),
+ total7d: finite(Number(raw.total7d)),
+ change_7dover7d: finite(Number(raw.change_7dover7d)),
+ chart: normalizeChart(raw.totalDataChart),
+ protocols,
+ updated_at: now,
+ };
+ _cache = { value, expiresAt: now + 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;
+
+ const rl = await limits.marketDataIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ try {
+ const payload = await build();
+ return json(res, 200, payload, {
+ 'cache-control': 'public, max-age=120, s-maxage=600, stale-while-revalidate=600',
+ });
+ } catch {
+ return error(
+ res,
+ 502,
+ 'upstream_error',
+ 'DEX volume data is unavailable right now — retry shortly',
+ );
+ }
+});
diff --git a/api/defi/fees.js b/api/defi/fees.js
new file mode 100644
index 000000000..c2f00a1b5
--- /dev/null
+++ b/api/defi/fees.js
@@ -0,0 +1,116 @@
+// GET /api/defi/fees?type=fees|revenue
+// ---------------------------------------------------------------------------
+// Protocol fees & revenue for the /fees page. Fetches DeFiLlama's keyless
+// /overview/fees dimension feed (no API key). `type=fees` (default) pulls the
+// dailyFees series — the total users pay to use a protocol — and `type=revenue`
+// pulls dailyRevenue — the slice the protocol itself keeps. Returns whole-market
+// 24h/7d/30d totals, the aggregate daily chart (downsampled to ≤200 points), and
+// the top 100 protocols by 24h. Each protocol's `slug` resolves at
+// api.llama.fi/protocol/{slug} (verified) so the page can deep-link to a
+// protocol detail page. Cached 10 min in-memory + CDN. 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 TTL_MS = 600_000;
+const MAX_CHART_POINTS = 200;
+const MAX_PROTOCOLS = 100;
+
+// One cache slot per data type — the two series are independent upstream calls.
+const _cache = new Map(); // type -> { value, expiresAt }
+
+const finite = (n) => (Number.isFinite(n) ? n : null);
+
+function upstreamFor(type) {
+ const dataType = type === 'revenue' ? 'dailyRevenue' : 'dailyFees';
+ return `https://api.llama.fi/overview/fees?excludeTotalDataChartBreakdown=true&dataType=${dataType}`;
+}
+
+// Downsample [[unixSeconds, value], …] to at most `max` points as [{t: ms, value}],
+// always keeping the final point so the line ends where the data does.
+function normalizeChart(raw) {
+ const pts = (Array.isArray(raw) ? raw : [])
+ .filter((p) => Array.isArray(p) && Number.isFinite(Number(p[0])) && Number.isFinite(Number(p[1])))
+ .map((p) => ({ t: Number(p[0]) * 1000, value: Number(p[1]) }));
+ if (pts.length <= MAX_CHART_POINTS) return pts;
+ const step = (pts.length - 1) / (MAX_CHART_POINTS - 1);
+ const out = [];
+ for (let i = 0; i < MAX_CHART_POINTS; i++) out.push(pts[Math.round(i * step)]);
+ return out;
+}
+
+async function build(type) {
+ const now = Date.now();
+ const hit = _cache.get(type);
+ if (hit && hit.expiresAt > now) return hit.value;
+
+ const resp = await fetch(upstreamFor(type), {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!resp.ok) throw new Error(`llama ${resp.status}`);
+ const raw = await resp.json();
+ if (!raw || !Array.isArray(raw.protocols)) throw new Error('unexpected upstream shape');
+
+ const eligible = raw.protocols.filter((p) => Number.isFinite(Number(p?.total24h)));
+ eligible.sort((a, b) => Number(b.total24h) - Number(a.total24h));
+
+ const protocols = eligible.slice(0, MAX_PROTOCOLS).map((p) => {
+ const chains = Array.isArray(p.chains) ? p.chains.filter((c) => typeof c === 'string') : [];
+ return {
+ name: typeof p.displayName === 'string' && p.displayName ? p.displayName
+ : typeof p.name === 'string' ? p.name : 'Unknown',
+ // `slug` is DeFiLlama's canonical protocol key — it resolves at
+ // /protocol/{slug} (verified against tether / circle-usdc / uniswap-v3).
+ slug: typeof p.slug === 'string' && p.slug ? p.slug : null,
+ logo: typeof p.logo === 'string' ? p.logo : null,
+ category: typeof p.category === 'string' ? p.category : null,
+ chains,
+ total24h: finite(Number(p.total24h)),
+ total7d: finite(Number(p.total7d)),
+ total30d: finite(Number(p.total30d)),
+ change_1d: finite(Number(p.change_1d)),
+ change_7d: finite(Number(p.change_7d)),
+ change_1m: finite(Number(p.change_1m)),
+ };
+ });
+
+ const value = {
+ type: type === 'revenue' ? 'revenue' : 'fees',
+ total24h: finite(Number(raw.total24h)),
+ total7d: finite(Number(raw.total7d)),
+ total30d: finite(Number(raw.total30d)),
+ change_1d: finite(Number(raw.change_1d)),
+ chart: normalizeChart(raw.totalDataChart),
+ protocols,
+ updated_at: now,
+ };
+ _cache.set(type, { value, expiresAt: now + 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;
+
+ const rl = await limits.marketDataIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const type = url.searchParams.get('type') === 'revenue' ? 'revenue' : 'fees';
+
+ try {
+ const payload = await build(type);
+ return json(res, 200, payload, {
+ 'cache-control': 'public, max-age=120, s-maxage=600, stale-while-revalidate=600',
+ });
+ } catch {
+ return error(
+ res,
+ 502,
+ 'upstream_error',
+ 'Protocol fee data is unavailable right now — retry shortly',
+ );
+ }
+});
diff --git a/api/defi/hacks.js b/api/defi/hacks.js
new file mode 100644
index 000000000..42ae6cd98
--- /dev/null
+++ b/api/defi/hacks.js
@@ -0,0 +1,169 @@
+// GET /api/defi/hacks
+// ---------------------------------------------------------------------------
+// DeFi exploit / hack history for the /hacks page. Fetches DeFiLlama's keyless
+// /hacks feed (no API key), normalizes each incident to the fields the page
+// renders, computes whole-dataset headline stats, then applies an optional
+// case-insensitive search over name+technique+classification and paginates.
+// The raw upstream is cached ~10 min in-memory + CDN. DeFiLlama's hacks
+// database is the data source — see the page's attribution line.
+//
+// Amount unit: DeFiLlama reports `amount` in raw USD (verified at build time
+// against incidents of known magnitude — the largest bridge exploits land at
+// hundreds of millions to billions, matching their public post-mortems), so no
+// scaling is applied. `returnedFunds` uses the same unit. `chain` is an array
+// of chain names (or null); it is normalized to an array.
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const UPSTREAM = 'https://api.llama.fi/hacks';
+const TTL_MS = 600_000;
+const YEAR_MS = 365 * 24 * 60 * 60 * 1000;
+const MAX_LIMIT = 200;
+const DEFAULT_LIMIT = 100;
+
+let _cache = null; // { value, expiresAt }
+
+const finiteOrNull = (n) => (Number.isFinite(n) ? n : null);
+
+function normalizeChains(chain) {
+ if (Array.isArray(chain)) return chain.filter((c) => typeof c === 'string' && c.length);
+ if (typeof chain === 'string' && chain.length) return [chain];
+ return [];
+}
+
+// Fetch + normalize the whole upstream feed once, cache it. Returns the full
+// sorted, normalized incident list plus the dataset-wide headline stats — the
+// per-request search/pagination happens on top of this cached whole.
+async function loadDataset() {
+ const now = Date.now();
+ if (_cache && _cache.expiresAt > now) return _cache.value;
+
+ const resp = await fetch(UPSTREAM, {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!resp.ok) throw new Error(`llama ${resp.status}`);
+ const raw = await resp.json();
+ if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');
+
+ const hacks = [];
+ for (const h of raw) {
+ const dateSec = Number(h?.date);
+ if (!Number.isFinite(dateSec)) continue;
+ const amount = Number(h?.amount);
+ const returned = Number(h?.returnedFunds);
+ hacks.push({
+ date: dateSec * 1000, // epoch ms
+ name: typeof h.name === 'string' && h.name.length ? h.name : 'Unknown',
+ classification: typeof h.classification === 'string' ? h.classification : null,
+ technique: typeof h.technique === 'string' ? h.technique : null,
+ amount_usd: Number.isFinite(amount) && amount >= 0 ? amount : null,
+ chains: normalizeChains(h.chain),
+ bridge: h.bridgeHack === true,
+ target_type: typeof h.targetType === 'string' ? h.targetType : null,
+ // `source` is a post-mortem/reference URL when present; DeFiLlama
+ // frequently ships it empty, so keep it null rather than render a
+ // dead link.
+ source: typeof h.source === 'string' && /^https?:\/\//i.test(h.source) ? h.source : null,
+ returned_usd: Number.isFinite(returned) && returned > 0 ? returned : null,
+ });
+ }
+
+ // Newest first.
+ hacks.sort((a, b) => b.date - a.date);
+
+ // Headline stats span the entire dataset, independent of any search/paging.
+ const cutoff = now - YEAR_MS;
+ let totalAllTime = 0;
+ let total12mo = 0;
+ let incidents12mo = 0;
+ let bridgeAllTime = 0;
+ for (const h of hacks) {
+ const amt = h.amount_usd || 0;
+ totalAllTime += amt;
+ if (h.bridge) bridgeAllTime += amt;
+ if (h.date >= cutoff) {
+ total12mo += amt;
+ incidents12mo += 1;
+ }
+ }
+
+ const value = {
+ hacks,
+ stats: {
+ total_stolen_all_time: totalAllTime,
+ total_stolen_12mo: total12mo,
+ incidents_12mo: incidents12mo,
+ bridge_hack_share_pct: totalAllTime > 0 ? (bridgeAllTime / totalAllTime) * 100 : 0,
+ },
+ updated_at: now,
+ };
+ _cache = { value, expiresAt: now + TTL_MS };
+ return value;
+}
+
+function clampInt(raw, fallback, min, max) {
+ const n = Number.parseInt(raw, 10);
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(max, Math.max(min, n));
+}
+
+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);
+
+ let url;
+ try {
+ url = new URL(req.url, 'http://local');
+ } catch {
+ url = new URL('/api/defi/hacks', 'http://local');
+ }
+ const search = (url.searchParams.get('search') || '').trim().toLowerCase();
+ const limit = clampInt(url.searchParams.get('limit'), DEFAULT_LIMIT, 1, MAX_LIMIT);
+ const offset = clampInt(url.searchParams.get('offset'), 0, 0, Number.MAX_SAFE_INTEGER);
+
+ try {
+ const dataset = await loadDataset();
+
+ let filtered = dataset.hacks;
+ if (search) {
+ filtered = filtered.filter((h) => {
+ const hay = `${h.name} ${h.technique || ''} ${h.classification || ''}`.toLowerCase();
+ return hay.includes(search);
+ });
+ }
+
+ const page = filtered.slice(offset, offset + limit);
+
+ return json(
+ res,
+ 200,
+ {
+ stats: {
+ total_stolen_all_time: dataset.stats.total_stolen_all_time,
+ total_stolen_12mo: dataset.stats.total_stolen_12mo,
+ incidents_12mo: dataset.stats.incidents_12mo,
+ bridge_hack_share_pct: finiteOrNull(dataset.stats.bridge_hack_share_pct) ?? 0,
+ },
+ hacks: page,
+ count: filtered.length,
+ updated_at: dataset.updated_at,
+ },
+ {
+ 'cache-control':
+ 'public, max-age=120, s-maxage=600, stale-while-revalidate=1200',
+ },
+ );
+ } catch {
+ return error(
+ res,
+ 502,
+ 'upstream_error',
+ 'DeFi hacks data is unavailable right now — retry shortly',
+ );
+ }
+});
diff --git a/api/defi/protocol.js b/api/defi/protocol.js
new file mode 100644
index 000000000..a6eeb8f29
--- /dev/null
+++ b/api/defi/protocol.js
@@ -0,0 +1,271 @@
+// GET /api/defi/protocol?slug=<slug>
+// ---------------------------------------------------------------------------
+// Rich profile for one DeFi protocol — powers the /protocol/:slug detail page.
+// Proxies DeFiLlama's keyless endpoints (no API key) and slims the multi-MB
+// upstream payload to exactly what the page renders:
+// · /protocol/{slug} (required) — TVL history, per-chain TVL, raises,
+// hallmarks, mcap, metadata
+// · /summary/fees/{slug} (optional) — 24h/7d/30d/all-time fees + revenue
+// (dailyFees + dailyRevenue passes)
+// · /summary/dexs/{slug} (optional) — DEX trading volume
+// The fees/dexs summaries also carry richer metadata (category, audits,
+// methodology, forkedFrom, parentProtocol) than the bare /protocol payload for
+// aggregator ("parent") protocols, so missing metadata is enriched from them.
+// The full daily TVL history (often 2k+ points) is downsampled server-side to
+// ≤400 points so the SVG chart stays light. Cached 5 min in-memory per slug +
+// CDN. 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 SLUG_RE = /^[a-z0-9.-]{1,80}$/i;
+const TTL_MS = 300_000;
+const MAX_TVL_POINTS = 400;
+const UA = 'three.ws/1.0';
+
+const _cache = new Map(); // slug -> { value, expiresAt }
+
+// Coerce numbers and DeFiLlama's occasional numeric strings (audits count, some
+// summary totals) to a finite number, else null.
+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.trim()) ? v.trim() : null);
+
+// Synthetic per-chain suffixes DeFiLlama appends to `currentChainTvls` — these
+// are not real TVL a chain holds (they double-count borrowed collateral, staked
+// governance tokens, LP-side liquidity, or locked vesting), so a "TVL by chain"
+// view must exclude them or every chain appears 2–3× with inflated numbers.
+const SYNTH_SUFFIX = /-(borrowed|staking|pool2|vesting)$/i;
+// …and the whole-protocol aggregates of those same categories.
+const AGGREGATE_KEYS = new Set(['borrowed', 'staking', 'pool2', 'vesting']);
+
+async function fetchJson(url) {
+ const resp = await fetch(url, {
+ headers: { accept: 'application/json', 'user-agent': UA },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!resp.ok) {
+ const err = new Error(`llama ${resp.status}`);
+ err.status = resp.status;
+ throw err;
+ }
+ return resp.json();
+}
+
+// Optional upstream — a 4xx (many protocols have no fees/dexs feed) or any other
+// failure collapses to null so the section is simply hidden, never an error.
+async function fetchOptional(url) {
+ try {
+ return await fetchJson(url);
+ } catch {
+ return null;
+ }
+}
+
+// Reduce the full daily TVL history to ≤MAX points by a fixed stride, always
+// keeping the first and last sample so the chart's start and current value are
+// exact. Input points are [{ date: unix_s, totalLiquidityUSD }].
+function downsampleTvl(series) {
+ const clean = [];
+ for (const p of Array.isArray(series) ? series : []) {
+ const t = num(p?.date);
+ const tvl = num(p?.totalLiquidityUSD);
+ if (t == null || tvl == null) continue;
+ clean.push({ t: Math.floor(t), tvl });
+ }
+ if (clean.length <= MAX_TVL_POINTS) return clean;
+ const stride = Math.ceil(clean.length / MAX_TVL_POINTS);
+ const out = [];
+ for (let i = 0; i < clean.length; i += stride) out.push(clean[i]);
+ const last = clean[clean.length - 1];
+ if (out[out.length - 1]?.t !== last.t) out.push(last);
+ return out;
+}
+
+// Current per-chain TVL sorted desc, excluding the synthetic/aggregate keys.
+// Staking + borrowed totals (if the protocol reports them) are surfaced
+// separately so the page can note them without polluting the chain breakdown.
+function shapeChainTvls(currentChainTvls) {
+ const chains = [];
+ let staking = null;
+ let borrowed = null;
+ for (const [key, raw] of Object.entries(currentChainTvls || {})) {
+ const val = num(raw);
+ if (val == null) continue;
+ if (key === 'staking') { staking = val; continue; }
+ if (key === 'borrowed') { borrowed = val; continue; }
+ if (AGGREGATE_KEYS.has(key)) continue;
+ if (SYNTH_SUFFIX.test(key)) continue;
+ if (val <= 0) continue;
+ chains.push({ chain: key, tvl: val });
+ }
+ chains.sort((a, b) => b.tvl - a.tvl);
+ return { chains, staking, borrowed };
+}
+
+// Embedded funding rounds. DeFiLlama reports `amount` in millions of USD, so it
+// is scaled to raw dollars here; the page never has to know the unit.
+function shapeRaises(raises) {
+ if (!Array.isArray(raises) || !raises.length) return null;
+ const strList = (a) => (Array.isArray(a) ? a.map(str).filter(Boolean) : []);
+ const out = raises
+ .map((r) => {
+ const amt = num(r?.amount);
+ return {
+ date: num(r?.date) != null ? Math.floor(num(r.date)) : null,
+ round: str(r?.round),
+ amount_usd: amt != null ? amt * 1e6 : null,
+ leadInvestors: strList(r?.leadInvestors),
+ otherInvestors: strList(r?.otherInvestors),
+ valuation: num(r?.valuation),
+ source: httpUrl(r?.source),
+ };
+ })
+ .sort((a, b) => (b.date || 0) - (a.date || 0));
+ return out.length ? out : null;
+}
+
+// Timeline annotations: [unix_s, label]. Deduped (upstream occasionally repeats
+// an entry) and sorted ascending so chart markers land in chronological order.
+function shapeHallmarks(hallmarks) {
+ if (!Array.isArray(hallmarks) || !hallmarks.length) return null;
+ const seen = new Set();
+ const out = [];
+ for (const item of hallmarks) {
+ if (!Array.isArray(item) || item.length < 2) continue;
+ const t = num(item[0]);
+ const label = str(item[1]);
+ if (t == null || !label) continue;
+ const key = `${Math.floor(t)}|${label}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push([Math.floor(t), label]);
+ }
+ out.sort((a, b) => a[0] - b[0]);
+ return out.length ? out : null;
+}
+
+function shapeAudits(protoAudits, protoLinks, metaAudits, metaLinks) {
+ const count = num(protoAudits ?? metaAudits);
+ const src = (Array.isArray(protoLinks) && protoLinks.length ? protoLinks : metaLinks) || [];
+ const audit_links = (Array.isArray(src) ? src : []).map(httpUrl).filter(Boolean).slice(0, 6);
+ if ((count == null || count === 0) && !audit_links.length) return null;
+ return { count: count ?? 0, audit_links };
+}
+
+function shapeFees(fees, revenue) {
+ if (!fees && !revenue) return null;
+ const f = fees || {};
+ const r = revenue || {};
+ const out = {
+ total24h: num(f.total24h),
+ total7d: num(f.total7d),
+ total30d: num(f.total30d),
+ totalAllTime: num(f.totalAllTime),
+ revenue24h: num(r.total24h),
+ revenue7d: num(r.total7d),
+ revenue30d: num(r.total30d),
+ };
+ return Object.values(out).some((v) => v != null) ? out : null;
+}
+
+function shapeDexVolume(dexs) {
+ if (!dexs) return null;
+ const out = {
+ total24h: num(dexs.total24h),
+ total7d: num(dexs.total7d),
+ change_7dover7d: num(dexs.change_7dover7d),
+ };
+ return out.total24h != null || out.total7d != null ? out : null;
+}
+
+function build(slug, proto, fees, revenue, dexs) {
+ // The fees/dexs summaries carry the richest metadata; prefer the /protocol
+ // value, fall back to whichever summary is present.
+ const meta = fees || dexs || {};
+ const tvlSeries = downsampleTvl(proto.tvl);
+ const { chains, staking, borrowed } = shapeChainTvls(proto.currentChainTvls);
+ const forkedFromSrc =
+ (Array.isArray(proto.forkedFrom) && proto.forkedFrom.length ? proto.forkedFrom : meta.forkedFrom) || [];
+
+ return {
+ slug,
+ name: str(proto.name) || slug,
+ symbol: str(proto.symbol) && proto.symbol !== '-' ? proto.symbol : null,
+ logo: httpUrl(proto.logo) || httpUrl(meta.logo),
+ url: httpUrl(proto.url) || httpUrl(meta.url),
+ twitter: str(proto.twitter) || str(meta.twitter),
+ category: str(proto.category) || str(meta.category),
+ chains: Array.isArray(proto.chains) ? proto.chains.filter((c) => typeof c === 'string') : [],
+ audits: shapeAudits(proto.audits, proto.audit_links, meta.audits, meta.audit_links),
+ forkedFrom: (Array.isArray(forkedFromSrc) ? forkedFromSrc : []).map(str).filter(Boolean),
+ parentProtocol: str(proto.parentProtocol) || str(meta.parentProtocol),
+ listedAt: num(proto.listedAt),
+ mcap: num(proto.mcap),
+ description: (str(proto.description) || str(meta.description) || '').slice(0, 2000) || null,
+ methodology: str(proto.methodology) || str(meta.methodology),
+ tvl_current: tvlSeries.length ? tvlSeries[tvlSeries.length - 1].tvl : null,
+ tvl_series: tvlSeries,
+ chain_tvls: chains,
+ staking_tvl: staking,
+ borrowed_tvl: borrowed,
+ hallmarks: shapeHallmarks(proto.hallmarks),
+ raises: shapeRaises(proto.raises),
+ fees: shapeFees(fees, revenue),
+ dex_volume: shapeDexVolume(dexs),
+ updated_at: Date.now(),
+ };
+}
+
+async function load(slug) {
+ const now = Date.now();
+ const hit = _cache.get(slug);
+ if (hit && hit.expiresAt > now) return hit.value;
+
+ // Main call is required; the rest are best-effort enrichment fetched in
+ // parallel. The main fetch throwing a 400/404 propagates as not-found.
+ const [proto, fees, revenue, dexs] = await Promise.all([
+ fetchJson(`https://api.llama.fi/protocol/${encodeURIComponent(slug)}`),
+ fetchOptional(`https://api.llama.fi/summary/fees/${encodeURIComponent(slug)}?dataType=dailyFees`),
+ fetchOptional(`https://api.llama.fi/summary/fees/${encodeURIComponent(slug)}?dataType=dailyRevenue`),
+ fetchOptional(`https://api.llama.fi/summary/dexs/${encodeURIComponent(slug)}`),
+ ]);
+
+ const value = build(slug, proto, fees, revenue, dexs);
+ // Bound the cache so a scan over many distinct slugs can't grow it unbounded.
+ if (_cache.size > 500) _cache.clear();
+ _cache.set(slug, { value, expiresAt: now + 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;
+
+ const rl = await limits.marketDataIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const slug = (params.get('slug') || '').trim().toLowerCase();
+ if (!SLUG_RE.test(slug)) {
+ return error(res, 400, 'bad_slug', 'slug must be a DeFiLlama protocol slug (1–80 chars: letters, digits, . or -)');
+ }
+
+ try {
+ const payload = await load(slug);
+ return json(res, 200, payload, {
+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
+ });
+ } catch (err) {
+ // DeFiLlama answers an unknown slug with 400 "Protocol not found" (and 404
+ // for some paths) — both mean "no such protocol" to the client.
+ if (err?.status === 404 || err?.status === 400) {
+ return error(res, 404, 'not_found', `no DeFi protocol found for "${slug}"`);
+ }
+ return error(res, 502, 'upstream_error', 'DeFi protocol data is unavailable right now — retry shortly');
+ }
+});
diff --git a/api/defi/protocols.js b/api/defi/protocols.js
index f6fd4aa51..bc8bac888 100644
--- a/api/defi/protocols.js
+++ b/api/defi/protocols.js
@@ -50,6 +50,8 @@ async function build() {
const protocols = eligible.slice(0, 100).map((p) => {
const chains = Array.isArray(p.chains) ? p.chains.filter((c) => typeof c === 'string') : [];
return {
+ // DeFiLlama protocol slug — the /protocol/:slug detail page keys off it.
+ slug: typeof p.slug === 'string' ? p.slug : null,
name: typeof p.name === 'string' ? p.name : 'Unknown',
logo: typeof p.logo === 'string' ? p.logo : null,
symbol: typeof p.symbol === 'string' && p.symbol !== '-' ? p.symbol : null,
diff --git a/api/defi/stablecoin.js b/api/defi/stablecoin.js
new file mode 100644
index 000000000..24c63f50f
--- /dev/null
+++ b/api/defi/stablecoin.js
@@ -0,0 +1,231 @@
+// GET /api/defi/stablecoin?id=<n>
+// ---------------------------------------------------------------------------
+// Rich profile for ONE stablecoin — powers the /stablecoin/:id detail page.
+// Proxies the free, keyless DeFiLlama per-coin endpoint
+// (https://stablecoins.llama.fi/stablecoin/{id}) and reshapes its firehose into
+// a lean payload: identity + peg metadata, current per-chain circulation with
+// dominance share, the full circulating-supply history (downsampled), and the
+// circulating history of the top chains. Circulating is denominated in the
+// asset's own peg unit (the on-chain market cap). A USD-family asset's price is
+// turned into a peg-deviation figure so the page can grade peg health. Cached
+// 5m in-memory keyed by id + CDN s-maxage — the source refreshes on the order of
+// minutes, not seconds. Mirrors api/defi/stablecoins.js (list) and the
+// api/coin/exchange.js detail-handler pattern.
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const ID_RE = /^\d{1,6}$/;
+const UPSTREAM = (id) => `https://stablecoins.llama.fi/stablecoin/${id}`;
+const TTL_MS = 300_000; // 5 minutes — matches the CDN s-maxage below.
+const MAX_SUPPLY_POINTS = 400;
+const MAX_CHAIN_POINTS = 200;
+const TOP_CHAIN_SERIES = 5;
+
+// Per-id in-memory cache. { [id]: { value, expiresAt } }.
+const _cache = new Map();
+
+const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
+const httpUrl = (v) => (typeof v === 'string' && /^https?:\/\//.test(v.trim()) ? v.trim() : null);
+const num = (v) => {
+ if (v == null || v === '') return null;
+ const n = typeof v === 'number' ? v : Number(v);
+ return Number.isFinite(n) ? n : null;
+};
+
+// DeFiLlama nests every balance under the asset's own peg unit, e.g.
+// { peggedUSD: 184_000_000 }. Some fields collapse to a bare 0 when empty
+// (minted / unreleased on early rows), so accept a number too.
+function pegVal(v, pegType) {
+ if (v == null) return null;
+ if (typeof v === 'number') return Number.isFinite(v) ? v : null;
+ if (typeof v === 'object') return num(v[pegType]);
+ return null;
+}
+
+// "peggedUSD" → "USD", "peggedEUR" → "EUR"; anything unexpected passes through.
+function pegDisplay(pegType) {
+ if (!pegType) return null;
+ return pegType.startsWith('pegged') ? pegType.slice(6) : pegType;
+}
+
+// DeFiLlama's source data carries a persistent typo — "crytpo-backed" — for a
+// slice of assets. Normalize it so the page's fiat/crypto/algorithmic grouping
+// never sees two spellings of the same mechanism.
+function normalizeMechanism(m) {
+ const s = str(m);
+ if (!s) return null;
+ return s === 'crytpo-backed' ? 'crypto-backed' : s;
+}
+
+// Downsample an array to at most `max` entries, always keeping the first and
+// last (a supply chart cares most about where the line starts and ends).
+function downsample(arr, max) {
+ if (!Array.isArray(arr) || arr.length <= max) return arr || [];
+ const step = (arr.length - 1) / (max - 1);
+ const out = [];
+ for (let i = 0; i < max; i++) out.push(arr[Math.round(i * step)]);
+ return out;
+}
+
+// Current per-chain circulation → sorted rows with dominance share. Circulating
+// is the asset's peg-unit balance on that chain (its on-chain market cap).
+function shapeChains(currentChainBalances, pegType) {
+ const rows = [];
+ let total = 0;
+ if (currentChainBalances && typeof currentChainBalances === 'object') {
+ for (const [chain, bal] of Object.entries(currentChainBalances)) {
+ const circulating = pegVal(bal, pegType);
+ if (circulating == null || circulating <= 0) continue;
+ total += circulating;
+ rows.push({ chain, circulating_usd: circulating });
+ }
+ }
+ rows.sort((a, b) => b.circulating_usd - a.circulating_usd);
+ for (const r of rows) r.share_pct = total > 0 ? (r.circulating_usd / total) * 100 : null;
+ return rows;
+}
+
+// Full circulating-supply history → { t (ms), circulating, minted, unreleased }.
+// Upstream `date` is unix seconds; minted/unreleased are best-effort (absent on
+// early rows). Filtered to points that carry a finite circulating figure.
+function shapeSupplySeries(tokens, pegType) {
+ if (!Array.isArray(tokens)) return [];
+ const pts = [];
+ for (const row of tokens) {
+ if (!row || typeof row !== 'object') continue;
+ const t = num(row.date);
+ const circulating = pegVal(row.circulating, pegType);
+ if (t == null || circulating == null) continue;
+ pts.push({
+ t: t * 1000,
+ circulating,
+ minted: pegVal(row.minted, pegType),
+ unreleased: pegVal(row.unreleased, pegType),
+ });
+ }
+ pts.sort((a, b) => a.t - b.t);
+ return downsample(pts, MAX_SUPPLY_POINTS);
+}
+
+// Circulating history for the top N chains, ranked by their latest balance.
+// chainBalances[chain] = { tokens: [ … ] } with the same row shape as the
+// asset-wide `tokens` series.
+function shapeChainSeries(chainBalances, pegType, topChains) {
+ if (!chainBalances || typeof chainBalances !== 'object') return [];
+ const order = topChains.map((c) => c.chain);
+ const out = [];
+ for (const chain of order.slice(0, TOP_CHAIN_SERIES)) {
+ const entry = chainBalances[chain];
+ const tokens = entry && Array.isArray(entry.tokens) ? entry.tokens : null;
+ if (!tokens) continue;
+ const pts = [];
+ for (const row of tokens) {
+ if (!row || typeof row !== 'object') continue;
+ const t = num(row.date);
+ const circulating = pegVal(row.circulating, pegType);
+ if (t == null || circulating == null) continue;
+ pts.push({ t: t * 1000, circulating });
+ }
+ pts.sort((a, b) => a.t - b.t);
+ if (pts.length) out.push({ chain, series: downsample(pts, MAX_CHAIN_POINTS) });
+ }
+ return out;
+}
+
+function shape(raw, id) {
+ const pegType = str(raw.pegType);
+ const price = num(raw.price);
+ // Peg deviation is only meaningful for USD-family assets, whose peg unit is
+ // $1.00. A EUR/GBP/etc. price is quoted in USD (~1.08, ~1.27) — comparing it
+ // to 1.0 would be nonsense — so it stays null for non-USD pegs.
+ const pegDeviationPct =
+ pegType === 'peggedUSD' && price != null ? (price - 1) * 100 : null;
+
+ const auditLinks = Array.isArray(raw.auditLinks)
+ ? raw.auditLinks.map(httpUrl).filter(Boolean)
+ : [];
+
+ const chains = shapeChains(raw.currentChainBalances, pegType);
+
+ return {
+ id,
+ name: str(raw.name) || 'Unknown',
+ symbol: str(raw.symbol) || '',
+ peg_type: pegDisplay(pegType),
+ mechanism: normalizeMechanism(raw.pegMechanism),
+ description: str(raw.description),
+ mint_redeem: str(raw.mintRedeemDescription),
+ url: httpUrl(raw.url),
+ twitter: httpUrl(raw.twitter),
+ audit_links: auditLinks,
+ gecko_id: str(raw.gecko_id),
+ price,
+ peg_deviation_pct: pegDeviationPct,
+ chains,
+ supply_series: shapeSupplySeries(raw.tokens, pegType),
+ chain_series: shapeChainSeries(raw.chainBalances, pegType, chains),
+ updated_at: Date.now(),
+ };
+}
+
+// Fetches + shapes one stablecoin, cached per id. Throws { status: 404 } when
+// the id is unknown upstream so the handler can map it to a clean 404.
+async function build(id) {
+ const now = Date.now();
+ const hit = _cache.get(id);
+ if (hit && hit.expiresAt > now) return hit.value;
+
+ const resp = await fetch(UPSTREAM(id), {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (resp.status === 404) throw Object.assign(new Error('not found'), { status: 404 });
+ if (!resp.ok) throw new Error(`llama ${resp.status}`);
+
+ const body = await resp.json();
+ if (!body || typeof body !== 'object' || body.id == null) {
+ throw new Error('unexpected upstream shape');
+ }
+
+ const value = shape(body, id);
+ _cache.set(id, { value, expiresAt: now + TTL_MS });
+ // Bound the map — one entry per distinct id is tiny, but a scanner walking
+ // ids could grow it unbounded across a long-lived warm instance.
+ if (_cache.size > 512) {
+ for (const key of _cache.keys()) {
+ if (_cache.get(key).expiresAt <= now) _cache.delete(key);
+ }
+ }
+ return value;
+}
+
+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 id = (new URL(req.url, 'http://x').searchParams.get('id') || '').trim();
+ if (!ID_RE.test(id)) {
+ return error(res, 400, 'bad_id', 'id must be a DeFiLlama stablecoin id (1–6 digits)');
+ }
+
+ try {
+ const payload = await build(id);
+ return json(res, 200, payload, {
+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
+ });
+ } catch (err) {
+ if (err?.status === 404) {
+ return error(res, 404, 'not_found', `no stablecoin found for id "${id}"`);
+ }
+ return error(
+ res,
+ 502,
+ 'upstream_error',
+ 'stablecoin data is unavailable right now — retry shortly',
+ );
+ }
+});
diff --git a/api/defi/stablecoins.js b/api/defi/stablecoins.js
index d0b1c708a..905189cca 100644
--- a/api/defi/stablecoins.js
+++ b/api/defi/stablecoins.js
@@ -38,6 +38,9 @@ function shape(assets) {
const chains = Array.isArray(a.chains) ? a.chains.filter((c) => typeof c === 'string') : [];
rows.push({
+ // DeFiLlama's numeric asset id ("1", "2", …) — the /stablecoin/:id
+ // detail page keys off it; null when upstream omits it.
+ id: a.id != null ? String(a.id) : null,
name: typeof a.name === 'string' ? a.name : 'Unknown',
symbol: typeof a.symbol === 'string' ? a.symbol : '',
price: Number.isFinite(price) ? price : null,
diff --git a/data/changelog.json b/data/changelog.json
index b2fd9db67..d32e668d2 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$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": "Detail pages for protocols, chains, and stablecoins — plus fees, DEX volumes, hacks, and trending",
+ "summary": "Every DeFiLlama list now opens into a full detail page. A protocol page charts its whole TVL history with funding-round and event markers, breaks TVL down per chain, and shows its fees, revenue, and methodology. A chain page charts TVL, stablecoin supply, and DEX volume side by side with the top protocols on that chain. A stablecoin page charts circulating supply over time, shows the per-chain distribution, and flags how far off-peg it is in basis points. On top of the detail pages there are four new market surfaces: protocol fees and revenue ranked and charted, the DEX-volume leaderboard with market share, a searchable database of every major DeFi hack ($16.7B stolen all-time), and a trending page of the most-searched coins, categories, and NFTs on CoinGecko. Everything is real, key-free data, and the yields, DeFi, chains, and stablecoin tables now link straight into the new detail pages.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/fees"
+ },
{
"date": "2026-07-11",
"title": "Documentation accuracy pass: every tutorial verified against the shipped platform",
diff --git a/data/pages.json b/data/pages.json
index 7a30343a0..53d9c7eaf 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1282,6 +1282,38 @@
"changefreq": "hourly",
"added": "2026-07-11"
},
+ {
+ "path": "/fees",
+ "title": "Protocol Fees & Revenue",
+ "description": "Fees paid by users and revenue kept by protocols across all of DeFi, ranked with 24h/7d/30d totals and an aggregate history chart. Toggle between fees and revenue; each protocol links to its detail page. Live from DeFiLlama.",
+ "priority": 0.7,
+ "changefreq": "hourly",
+ "added": "2026-07-11"
+ },
+ {
+ "path": "/dex-volumes",
+ "title": "DEX Volume Leaderboard",
+ "description": "Every decentralized exchange ranked by trading volume, with 24h and 7d totals, 7-day change, and market share, plus an aggregate volume history chart. Live from DeFiLlama.",
+ "priority": 0.7,
+ "changefreq": "hourly",
+ "added": "2026-07-11"
+ },
+ {
+ "path": "/hacks",
+ "title": "DeFi Hacks Database",
+ "description": "A searchable database of every major DeFi exploit — amount stolen, classification, technique, chains affected, whether it was a bridge hack, and the source, with all-time and trailing-12-month totals. Live from DeFiLlama.",
+ "priority": 0.6,
+ "changefreq": "weekly",
+ "added": "2026-07-11"
+ },
+ {
+ "path": "/markets/trending",
+ "title": "Trending Crypto",
+ "description": "The most-searched coins, categories, and NFTs on CoinGecko over the last 24 hours — trending rank, price, 24h change, market cap, and volume, each coin and category linking to its detail page. Auto-refreshing.",
+ "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.md
index 484478003..058d1bfe8 100644
--- a/docs/coin-pages.md
+++ b/docs/coin-pages.md
@@ -150,8 +150,21 @@ data" rule:
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}`).
+ the URL for shareable views; project and chain link to their detail pages.
+ New `/api/defi/yields` (DeFiLlama `yields.llama.fi/pools` + `/chart/{pool}`).
+- **`/fees`** — fees paid by users and revenue kept by protocols across all of
+ DeFi, with 24h/7d/30d totals, an aggregate history chart, and a Fees|Revenue
+ toggle. New `/api/defi/fees` (DeFiLlama `/overview/fees`).
+- **`/dex-volumes`** — every DEX ranked by volume with 24h/7d totals, 7-day
+ change, market share, and an aggregate volume chart. New
+ `/api/defi/dex-volumes` (DeFiLlama `/overview/dexs`).
+- **`/hacks`** — a searchable database of every major DeFi exploit: amount
+ stolen, classification, technique, chains, bridge flag, and source, with
+ all-time and trailing-12-month totals. New `/api/defi/hacks` (DeFiLlama
+ `/hacks`).
+- **`/markets/trending`** — the most-searched coins, categories, and NFTs on
+ CoinGecko over the last 24h, auto-refreshing; coins and categories link to
+ their detail pages. New `/api/coin/trending` (CoinGecko `/search/trending`).
## Detail pages
@@ -180,6 +193,34 @@ 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.
+### `/protocol/:slug` — DeFi protocol detail
+
+A full profile for one protocol, reached from a `/defi`, `/fees`,
+`/dex-volumes`, or `/yields` row: hero (logo, category, audit badge,
+forked-from/parent chips, website + twitter); stat cards for TVL, Mcap/TVL,
+24h fees, 24h revenue, and 24h DEX volume (null cards hidden); a full TVL
+history chart with 30D/90D/1Y/All ranges and event (hallmark) markers; a
+per-chain TVL breakdown (each chain linking to `/chain/:name`); a funding-rounds
+table; and a methodology section. New `/api/defi/protocol` (DeFiLlama
+`/protocol/{slug}` enriched with `/summary/fees` and `/summary/dexs`).
+
+### `/chain/:name` — chain detail
+
+A per-chain page reached from `/chains`: hero (native token, chain id, rank,
+dominance); stat cards for TVL, share of DeFi, stablecoin supply, 24h DEX
+volume, 24h fees, and protocol count; interactive TVL, stablecoin-supply, and
+DEX-volume history charts; and the top protocols on that chain (each linking to
+`/protocol/:slug`). New `/api/defi/chain` (a fan-out over DeFiLlama's chains,
+historical-TVL, protocols, stablecoin-charts, and dimensions endpoints).
+
+### `/stablecoin/:id` — stablecoin detail
+
+A per-issuer page reached from `/stablecoins`: hero (peg, mechanism, price with
+a basis-point peg-deviation badge, audits, and a cross-link to the coin's
+`/coin/:id` market data); circulating-supply history chart; and a per-chain
+distribution table (each chain linking to `/chain/:name`). New
+`/api/defi/stablecoin` (DeFiLlama `stablecoins.llama.fi/stablecoin/{id}`).
+
## News & the markets hub
The suite's news wing and its front door, added 2026-07-10:
@@ -287,6 +328,13 @@ All data is real and fetched at runtime — nothing is hardcoded or sampled:
| `/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/trending` | CoinGecko `/search/trending` (coins + categories + NFTs) | 120 s |
+| `/api/defi/protocol` | DeFiLlama `/protocol/{slug}` (+ `/summary/fees` + `/summary/dexs`) | 300 s |
+| `/api/defi/chain` | DeFiLlama `/v2/chains` + `/v2/historicalChainTvl` + `/protocols` + stablecoin/DEX/fees per chain | 300 s |
+| `/api/defi/stablecoin` | DeFiLlama `stablecoins.llama.fi/stablecoin/{id}` | 300 s |
+| `/api/defi/fees` | DeFiLlama `/overview/fees` (`?type=fees\|revenue`) | 600 s |
+| `/api/defi/dex-volumes` | DeFiLlama `/overview/dexs` | 600 s |
+| `/api/defi/hacks` | DeFiLlama `/hacks` (exploit database) | 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 |
@@ -326,6 +374,12 @@ text before they reach the client.
| 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) |
+| Protocol detail | [`pages/protocol.html`](../pages/protocol.html) + `src/protocol-page.js` + `src/protocol-page.css`, API [`api/defi/protocol.js`](../api/defi/protocol.js) |
+| Chain detail | [`pages/chain.html`](../pages/chain.html) + `src/chain-page.js` + `src/chain-page.css`, API [`api/defi/chain.js`](../api/defi/chain.js) |
+| Stablecoin detail | [`pages/stablecoin.html`](../pages/stablecoin.html) + `src/stablecoin-page.js` + `src/stablecoin-page.css`, API [`api/defi/stablecoin.js`](../api/defi/stablecoin.js) |
+| Fees / DEX volumes | `pages/{fees,dex-volumes}.html` (+ `src/*.js`, `src/*.css`), APIs [`api/defi/fees.js`](../api/defi/fees.js), [`api/defi/dex-volumes.js`](../api/defi/dex-volumes.js) |
+| Hacks database | [`pages/hacks.html`](../pages/hacks.html) + `src/hacks.js` + `src/hacks.css`, API [`api/defi/hacks.js`](../api/defi/hacks.js) |
+| Trending | [`pages/markets-trending.html`](../pages/markets-trending.html) + `src/markets-trending.js`, API [`api/coin/trending.js`](../api/coin/trending.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/chain.html b/pages/chain.html
new file mode 100644
index 000000000..a8e400255
--- /dev/null
+++ b/pages/chain.html
@@ -0,0 +1,99 @@
+<!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>Chain TVL · three.ws</title>
+ <meta
+ name="description"
+ content="A rich profile for any blockchain — total value locked, dominance share, stablecoin supply, DEX volume, fees, and the top protocols deployed on the chain. Real DeFiLlama 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/chains" />
+ <meta property="og:title" content="Chain TVL · three.ws" />
+ <meta
+ property="og:description"
+ content="Total value locked, dominance share, stablecoin supply, DEX volume, fees, and the top protocols for any blockchain. Real DeFiLlama 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="Chain TVL · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Total value locked, dominance share, stablecoin supply, DEX volume, and top protocols for any blockchain."
+ />
+ <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/chain-page.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/chains" />
+ <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="ch-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="/chains">Chains</a>
+ <span class="sep" aria-hidden="true">/</span>
+ <span class="here" id="ch-crumb-name">…</span>
+ </nav>
+
+ <!-- Hero: chain name, native-token / chainId / rank / dominance chips. -->
+ <section id="ch-hero" aria-label="Chain overview"></section>
+
+ <!-- Stat cards: TVL, share, stablecoins, DEX volume, fees, protocols. -->
+ <section id="ch-stats" class="cv-section" aria-label="Chain stats"></section>
+
+ <!-- TVL history chart. -->
+ <section id="ch-tvl-chart" aria-label="Total value locked history"></section>
+
+ <!-- Stablecoin supply chart (hidden when unavailable). -->
+ <section id="ch-stable-chart" aria-label="Stablecoin supply history"></section>
+
+ <!-- DEX volume chart (hidden when unavailable). -->
+ <section id="ch-dex-chart" aria-label="DEX volume history"></section>
+
+ <!-- Top-protocols table. -->
+ <section id="ch-protocols" class="cv-section" aria-label="Top protocols"></section>
+
+ <p class="cv-updated" id="ch-updated" hidden></p>
+ </main>
+
+ <script type="module" src="/src/chain-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/dex-volumes.html b/pages/dex-volumes.html
new file mode 100644
index 000000000..b5eba7a42
--- /dev/null
+++ b/pages/dex-volumes.html
@@ -0,0 +1,122 @@
+<!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>DEX Volumes · three.ws</title>
+ <meta
+ name="description"
+ content="Live decentralized-exchange trading volume — the top DEXs ranked by 24h volume, with the chains they run on, 7d volume, 7d change, and each venue's share of total on-chain trading."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/dex-volumes" />
+ <meta property="og:title" content="DEX Volumes · three.ws" />
+ <meta
+ property="og:description"
+ content="Live decentralized-exchange trading volume — the top DEXs ranked by 24h volume, with chains, 7d volume, 7d change, and market share."
+ />
+ <meta
+ property="og:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=DEX+Volume+Leaderboard&amp;d=Every+decentralized+exchange+ranked+by+trading+volume%2C+with+24h+and+7d+totals%2C+7-day+change%2C+and+market+share%2C+plus+an+aggregate+volume+history+chart.+Live+from&amp;p=%2Fdex-volumes"
+ />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta property="og:image:alt" content="DEX Volumes — three.ws" />
+ <meta property="og:locale" content="en_US" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="DEX Volumes · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Live decentralized-exchange trading volume — the top DEXs ranked by 24h volume, with chains, 7d volume, 7d change, and market share."
+ />
+ <meta
+ name="twitter:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=DEX+Volume+Leaderboard&amp;d=Every+decentralized+exchange+ranked+by+trading+volume%2C+with+24h+and+7d+totals%2C+7-day+change%2C+and+market+share%2C+plus+an+aggregate+volume+history+chart.+Live+from&amp;p=%2Fdex-volumes"
+ />
+ <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/dex-volumes.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/dex-volumes" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+
+ <script type="application/ld+json">
+ {
+ "@context": "https://schema.org",
+ "@graph": [
+ {
+ "@type": "WebPage",
+ "name": "DEX Volumes",
+ "description": "Live decentralized-exchange trading volume: the top DEXs ranked by 24h volume, with the chains they run on, 7d volume, 7d change, and each venue's share of total on-chain trading. Sourced from DeFiLlama.",
+ "url": "https://three.ws/dex-volumes",
+ "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">
+ <nav class="cv-crumbs" aria-label="Breadcrumb">
+ <a href="/markets">Markets</a><span class="sep">/</span
+ ><a href="/defi">DeFi</a><span class="sep">/</span
+ ><span class="here">DEX Volumes</span>
+ </nav>
+ <h1 class="cv-h1">DEX Volumes</h1>
+ <p class="cv-sub">
+ Where on-chain trading happens — decentralized exchanges ranked by 24-hour volume,
+ with the chains they run on, 7-day volume, weekly change, and each venue's share of
+ total DEX activity.
+ </p>
+
+ <!-- Header stat cards. Hydrated by src/dex-volumes.js. -->
+ <section id="dx-stats" class="cv-section" aria-label="DEX volume statistics"></section>
+
+ <!-- Aggregate volume chart. Hydrated by src/dex-volumes.js. -->
+ <section id="dx-chart" class="cv-section" aria-label="Aggregate DEX volume over time"></section>
+
+ <div class="cv-toolbar">
+ <h2 class="cv-h2" style="margin: 0">Top DEXs by Volume</h2>
+ <div class="cv-pills">
+ <a class="cv-pill" href="/fees">Fees &amp; Revenue →</a>
+ <a class="cv-pill" href="/defi">DeFi TVL →</a>
+ </div>
+ </div>
+
+ <!-- DEX table. Hydrated by src/dex-volumes.js. -->
+ <section id="dx-table" aria-label="Top DEXs by 24h volume"></section>
+ <p class="cv-updated" id="dx-updated"></p>
+ </main>
+
+ <script type="module" src="/src/dex-volumes.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/pages/fees.html b/pages/fees.html
new file mode 100644
index 000000000..2808af2f9
--- /dev/null
+++ b/pages/fees.html
@@ -0,0 +1,149 @@
+<!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>Protocol Fees &amp; Revenue · three.ws</title>
+ <meta
+ name="description"
+ content="Live protocol fees and revenue across DeFi — the top protocols ranked by 24h fees, with category, chains, and 24h/7d/30d totals. See what users pay to use each protocol and what it keeps."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/fees" />
+ <meta property="og:title" content="Protocol Fees &amp; Revenue · three.ws" />
+ <meta
+ property="og:description"
+ content="Live protocol fees and revenue across DeFi — the top protocols ranked by 24h fees, with category, chains, and 24h/7d/30d totals."
+ />
+ <meta
+ property="og:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Protocol+Fees+%26+Revenue&amp;d=Fees+paid+by+users+and+revenue+kept+by+protocols+across+all+of+DeFi%2C+ranked+with+24h%2F7d%2F30d+totals+and+an+aggregate+history+chart.+Toggle+between+fees+and+reven&amp;p=%2Ffees"
+ />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta property="og:image:alt" content="Protocol Fees & Revenue — three.ws" />
+ <meta property="og:locale" content="en_US" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Protocol Fees &amp; Revenue · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Live protocol fees and revenue across DeFi — the top protocols ranked by 24h fees, with category, chains, and 24h/7d/30d totals."
+ />
+ <meta
+ name="twitter:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Protocol+Fees+%26+Revenue&amp;d=Fees+paid+by+users+and+revenue+kept+by+protocols+across+all+of+DeFi%2C+ranked+with+24h%2F7d%2F30d+totals+and+an+aggregate+history+chart.+Toggle+between+fees+and+reven&amp;p=%2Ffees"
+ />
+ <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/fees.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/fees" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+
+ <script type="application/ld+json">
+ {
+ "@context": "https://schema.org",
+ "@graph": [
+ {
+ "@type": "WebPage",
+ "name": "Protocol Fees & Revenue",
+ "description": "Live protocol fees and revenue across DeFi: the top protocols ranked by 24h fees, with category, the chains they run on, and 24h/7d/30d totals. Fees are what users pay; revenue is what the protocol keeps. Sourced from DeFiLlama.",
+ "url": "https://three.ws/fees",
+ "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">
+ <nav class="cv-crumbs" aria-label="Breadcrumb">
+ <a href="/markets">Markets</a><span class="sep">/</span
+ ><a href="/defi">DeFi</a><span class="sep">/</span
+ ><span class="here">Fees &amp; Revenue</span>
+ </nav>
+ <h1 class="cv-h1">Protocol Fees &amp; Revenue</h1>
+ <p class="cv-sub">
+ What DeFi protocols earn — the top protocols ranked by the fees they generate, with
+ category, the chains they run on, and 24-hour, 7-day, and 30-day totals.
+ </p>
+
+ <div class="fx-toggle" role="tablist" aria-label="Metric">
+ <button
+ type="button"
+ class="fx-toggle-btn"
+ role="tab"
+ id="fx-tab-fees"
+ data-type="fees"
+ aria-selected="true"
+ >
+ Fees
+ </button>
+ <button
+ type="button"
+ class="fx-toggle-btn"
+ role="tab"
+ id="fx-tab-revenue"
+ data-type="revenue"
+ aria-selected="false"
+ >
+ Revenue
+ </button>
+ </div>
+ <p class="fx-explainer" id="fx-explainer">
+ <strong>Fees</strong> are the total amount users pay to use a protocol.
+ <strong>Revenue</strong> is the slice the protocol itself keeps after paying suppliers
+ and liquidity providers.
+ </p>
+
+ <!-- Header stat cards. Hydrated by src/fees.js. -->
+ <section id="fx-stats" class="cv-section" aria-label="Fee statistics"></section>
+
+ <!-- Aggregate fees chart. Hydrated by src/fees.js. -->
+ <section id="fx-chart" class="cv-section" aria-label="Aggregate fees over time"></section>
+
+ <div class="cv-toolbar">
+ <h2 class="cv-h2" style="margin: 0" id="fx-table-heading">Top Protocols by Fees</h2>
+ <div class="cv-pills">
+ <a class="cv-pill" href="/dex-volumes">DEX Volumes →</a>
+ <a class="cv-pill" href="/defi">DeFi TVL →</a>
+ </div>
+ </div>
+
+ <!-- Protocol table. Hydrated by src/fees.js. -->
+ <section id="fx-table" aria-label="Top protocols by fees"></section>
+ <p class="cv-updated" id="fx-updated"></p>
+ </main>
+
+ <script type="module" src="/src/fees.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/pages/hacks.html b/pages/hacks.html
new file mode 100644
index 000000000..f3392058a
--- /dev/null
+++ b/pages/hacks.html
@@ -0,0 +1,156 @@
+<!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 Hacks Database · three.ws</title>
+ <meta
+ name="description"
+ content="Every major DeFi exploit, bridge hack, and protocol breach — amounts stolen, attack technique, chains hit, and whether funds were returned. A searchable record of crypto's biggest security failures."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/hacks" />
+ <meta property="og:title" content="DeFi Hacks Database · three.ws" />
+ <meta
+ property="og:description"
+ content="Every major DeFi exploit, bridge hack, and protocol breach — amounts stolen, attack technique, chains hit, and whether funds were returned. A searchable record of crypto's biggest security failures."
+ />
+ <meta
+ property="og:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=DeFi+Hacks+Database&amp;d=A+searchable+database+of+every+major+DeFi+exploit+%E2%80%94+amount+stolen%2C+classification%2C+technique%2C+chains+affected%2C+whether+it+was+a+bridge+hack%2C+and+the+source%2C+wit&amp;p=%2Fhacks"
+ />
+ <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 Hacks Database · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Every major DeFi exploit, bridge hack, and protocol breach — amounts stolen, attack technique, chains hit, and whether funds were returned."
+ />
+ <meta
+ name="twitter:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=DeFi+Hacks+Database&amp;d=A+searchable+database+of+every+major+DeFi+exploit+%E2%80%94+amount+stolen%2C+classification%2C+technique%2C+chains+affected%2C+whether+it+was+a+bridge+hack%2C+and+the+source%2C+wit&amp;p=%2Fhacks"
+ />
+ <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/hacks.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/hacks" />
+ <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 Hacks Database — three.ws" />
+
+ <script type="application/ld+json">
+ {
+ "@context": "https://schema.org",
+ "@graph": [
+ {
+ "@type": "WebPage",
+ "name": "DeFi Hacks Database",
+ "description": "A searchable record of major DeFi exploits, bridge hacks, and protocol breaches: amounts stolen, attack technique, chains hit, target type, and whether funds were returned. Sourced from DeFiLlama's hacks database.",
+ "url": "https://three.ws/hacks",
+ "isPartOf": {
+ "@type": "WebSite",
+ "name": "three.ws",
+ "url": "https://three.ws"
+ },
+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&amp;t=DeFi+Hacks+Database&amp;d=A+searchable+record+of+major+DeFi+exploits%2C+bridge+hacks%2C+and+protocol+breaches&amp;p=%2Fhacks"
+ }
+ ]
+ }
+ </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
+ ><a href="/defi">DeFi</a><span class="sep">/</span
+ ><span class="here">Hacks</span>
+ </nav>
+ <h1 class="cv-h1">DeFi Hacks Database</h1>
+ <p class="cv-sub">
+ Every major on-chain exploit on record — how much was taken, the technique behind
+ the breach, which chains were hit, and whether any funds came back. A sober look at
+ where and how decentralized finance has failed.
+ </p>
+
+ <!-- Header stat cards. Hydrated by src/hacks.js. -->
+ <section id="hacks-stats" class="cv-section" aria-label="Hack statistics"></section>
+
+ <div class="cv-toolbar">
+ <h2 class="cv-h2" style="margin: 0">Incidents</h2>
+ <div class="hacks-filter">
+ <label class="hacks-search-label" for="hacks-search">Search</label>
+ <div class="hacks-search-wrap">
+ <svg
+ class="hacks-search-icon"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <circle cx="11" cy="11" r="8" />
+ <line x1="21" y1="21" x2="16.65" y2="16.65" />
+ </svg>
+ <input
+ id="hacks-search"
+ class="hacks-search"
+ type="search"
+ inputmode="search"
+ autocomplete="off"
+ spellcheck="false"
+ placeholder="Name, technique, classification…"
+ aria-label="Search hacks by name, technique, or classification"
+ />
+ </div>
+ <a class="cv-pill" href="/defi">DeFi TVL →</a>
+ </div>
+ </div>
+
+ <!-- Incident table. Hydrated by src/hacks.js. -->
+ <section id="hacks-table" aria-label="DeFi hack incidents"></section>
+
+ <div id="hacks-more" class="hacks-more"></div>
+
+ <p class="cv-updated" id="hacks-updated"></p>
+ <p class="hacks-attribution">
+ Data: DeFiLlama hacks database. Figures are best-effort public estimates of funds
+ stolen at the time of each incident and may be revised as investigations conclude.
+ </p>
+ </main>
+
+ <script type="module" src="/src/hacks.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-trending.html b/pages/markets-trending.html
new file mode 100644
index 000000000..acdf8a4fa
--- /dev/null
+++ b/pages/markets-trending.html
@@ -0,0 +1,130 @@
+<!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>Trending Crypto · three.ws</title>
+ <meta
+ name="description"
+ content="The most-searched crypto over the last 24 hours — trending coins, sectors, and NFT collections, ranked live from CoinGecko with price, market cap, 24h volume, and change."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/markets/trending" />
+ <meta property="og:title" content="Trending Crypto · three.ws" />
+ <meta
+ property="og:description"
+ content="The most-searched crypto over the last 24 hours — trending coins, sectors, and NFT collections, ranked live from CoinGecko."
+ />
+ <meta
+ property="og:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Trending+Crypto&amp;d=The+most-searched+coins%2C+categories%2C+and+NFTs+on+CoinGecko+over+the+last+24+hours+%E2%80%94+trending+rank%2C+price%2C+24h+change%2C+market+cap%2C+and+volume%2C+each+coin+and+cate&amp;p=%2Fmarkets%2Ftrending"
+ />
+ <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="Trending Crypto · three.ws" />
+ <meta
+ name="twitter:description"
+ content="The most-searched crypto over the last 24 hours — trending coins, sectors, and NFT collections, ranked live from CoinGecko."
+ />
+ <meta
+ name="twitter:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Trending+Crypto&amp;d=The+most-searched+coins%2C+categories%2C+and+NFTs+on+CoinGecko+over+the+last+24+hours+%E2%80%94+trending+rank%2C+price%2C+24h+change%2C+market+cap%2C+and+volume%2C+each+coin+and+cate&amp;p=%2Fmarkets%2Ftrending"
+ />
+ <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/markets-trending.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/markets/trending" />
+ <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="Trending Crypto — three.ws" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Trending Crypto","description":"The most-searched crypto over the last 24 hours — trending coins, sectors, and NFT collections, ranked live from CoinGecko.","url":"https://three.ws/markets/trending","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 trd">
+ <nav class="cv-crumbs" aria-label="Breadcrumb">
+ <a href="/markets">Markets</a><span class="sep">/</span><span class="here">Trending</span>
+ </nav>
+
+ <header class="trd-head">
+ <div class="trd-head-id">
+ <h1 class="cv-h1">Trending</h1>
+ <p class="trd-sub">Most-searched assets on CoinGecko over the last 24h</p>
+ </div>
+ <div class="trd-head-meta">
+ <span class="trd-updated" id="trd-updated" role="status" aria-live="polite"></span>
+ <a class="cv-pill" href="/markets">← Back to Markets</a>
+ </div>
+ </header>
+
+ <!-- (1) Trending coins -->
+ <section class="cv-section trd-section" aria-labelledby="trd-coins-h">
+ <h2 class="cv-h2 trd-section-h" id="trd-coins-h">
+ <span class="trd-section-ico" aria-hidden="true">🔥</span> Trending coins
+ </h2>
+ <div id="trd-coins" class="trd-coins" aria-live="polite"></div>
+ </section>
+
+ <!-- (2) Trending categories -->
+ <section class="cv-section trd-section" aria-labelledby="trd-cats-h">
+ <h2 class="cv-h2 trd-section-h" id="trd-cats-h">
+ <span class="trd-section-ico" aria-hidden="true">📊</span> Trending sectors
+ </h2>
+ <div id="trd-cats" class="trd-cards" aria-live="polite"></div>
+ </section>
+
+ <!-- (3) Trending NFTs -->
+ <section class="cv-section trd-section" aria-labelledby="trd-nfts-h">
+ <h2 class="cv-h2 trd-section-h" id="trd-nfts-h">
+ <span class="trd-section-ico" aria-hidden="true">🖼</span> Trending NFT collections
+ </h2>
+ <div id="trd-nfts" class="trd-cards" aria-live="polite"></div>
+ </section>
+
+ <!-- Sibling market surfaces. -->
+ <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/trending" aria-current="page">Trending</a>
+ <a class="cv-pill" href="/markets/news">News</a>
+ <a class="cv-pill" href="/coins">Coins</a>
+ <a class="cv-pill" href="/categories">Sectors</a>
+ <a class="cv-pill" href="/heatmap">Heatmap</a>
+ <a class="cv-pill" href="/screener">Screener</a>
+ <a class="cv-pill" href="/fear-greed">Fear &amp; Greed</a>
+ <a class="cv-pill" href="/gas">Gas</a>
+ </nav>
+ </main>
+
+ <script type="module" src="/src/markets-trending.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/pages/protocol.html b/pages/protocol.html
new file mode 100644
index 000000000..1938eae58
--- /dev/null
+++ b/pages/protocol.html
@@ -0,0 +1,102 @@
+<!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 Protocol · three.ws</title>
+ <meta
+ name="description"
+ content="A rich profile for any DeFi protocol — total value locked with full history, per-chain breakdown, fees, revenue, DEX volume, audits, and funding rounds. Real DeFiLlama 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/defi" />
+ <meta property="og:title" content="DeFi Protocol · three.ws" />
+ <meta
+ property="og:description"
+ content="TVL history, per-chain breakdown, fees, revenue, DEX volume, audits, and funding rounds for any DeFi protocol. Real DeFiLlama 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="DeFi Protocol · three.ws" />
+ <meta
+ name="twitter:description"
+ content="TVL history, per-chain breakdown, fees, revenue, and funding rounds for any DeFi protocol."
+ />
+ <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/protocol-page.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/defi" />
+ <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="pr-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="/defi">DeFi</a>
+ <span class="sep" aria-hidden="true">/</span>
+ <span class="here" id="pr-crumb-name">…</span>
+ </nav>
+
+ <!-- Hero: logo, name, symbol, category, audit badge, fork/parent chips, links, description. -->
+ <section id="pr-hero" aria-label="Protocol overview"></section>
+
+ <!-- Stat cards: TVL, Mcap/TVL, 24h Fees, 24h Revenue, 24h DEX Volume. -->
+ <section id="pr-stats" class="cv-section" aria-label="Protocol stats"></section>
+
+ <!-- TVL history chart (SVG area, range toggle, crosshair, hallmark markers). -->
+ <section id="pr-chart" aria-label="Total value locked history"></section>
+
+ <!-- Per-chain TVL breakdown. -->
+ <section id="pr-chains" class="cv-section" aria-label="TVL by chain"></section>
+
+ <!-- Fees & revenue grid. -->
+ <section id="pr-fees" class="cv-section" aria-label="Fees and revenue"></section>
+
+ <!-- Funding rounds. -->
+ <section id="pr-raises" class="cv-section" aria-label="Funding rounds"></section>
+
+ <!-- Methodology prose. -->
+ <section id="pr-methodology" class="cv-section" aria-label="TVL methodology"></section>
+
+ <p class="cv-updated" id="pr-updated" hidden></p>
+ </main>
+
+ <script type="module" src="/src/protocol-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/stablecoin.html b/pages/stablecoin.html
new file mode 100644
index 000000000..79e75972e
--- /dev/null
+++ b/pages/stablecoin.html
@@ -0,0 +1,99 @@
+<!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>Stablecoin · three.ws</title>
+ <meta
+ name="description"
+ content="A rich profile for any stablecoin — peg health, backing mechanism, per-chain circulation, supply history, and audits. Live 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/stablecoins" />
+ <meta property="og:title" content="Stablecoin · three.ws" />
+ <meta
+ property="og:description"
+ content="Peg health, backing mechanism, per-chain circulation, supply history, and audits for any stablecoin. Real DeFiLlama 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="Stablecoin · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Peg health, backing mechanism, per-chain circulation, and supply history for any stablecoin."
+ />
+ <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/stablecoin-page.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/stablecoins" />
+ <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="sc-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="/stablecoins">Stablecoins</a>
+ <span class="sep" aria-hidden="true">/</span>
+ <span class="here" id="sc-crumb-name">…</span>
+ </nav>
+
+ <!-- Hero: name, symbol, peg + mechanism chips, price + peg-health badge, links, description. -->
+ <section id="sc-hero" aria-label="Stablecoin overview"></section>
+
+ <!-- Stat cards: circulating, chains, price, peg deviation. -->
+ <section id="sc-stats" class="cv-section" aria-label="Stablecoin stats"></section>
+
+ <!-- Circulating-supply history chart. -->
+ <section id="sc-chart" aria-label="Supply history"></section>
+
+ <!-- Per-chain circulation distribution. -->
+ <section id="sc-chains" class="cv-section" aria-label="Chain distribution"></section>
+
+ <!-- Mint / redeem mechanism prose. -->
+ <section id="sc-mint" class="cv-section" aria-label="Mint and redeem"></section>
+
+ <!-- Audit reports. -->
+ <section id="sc-audits" class="cv-section" aria-label="Audits"></section>
+
+ <p class="cv-updated" id="sc-updated" hidden></p>
+ </main>
+
+ <script type="module" src="/src/stablecoin-page.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.json
index a3d4c9ac2..fc3914012 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-11T04:07:32.412Z",
+ "generated_at": "2026-07-11T07:01:31.915Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -26,6 +26,16 @@
"launch"
]
},
+ {
+ "date": "2026-07-11",
+ "type": "launch",
+ "title": "DeFi Hacks Database",
+ "summary": "A searchable database of every major DeFi exploit — amount stolen, classification, technique, chains affected, whether it was a bridge hack, and the source, with all-time and trailing-12-month totals. Live from DeFiLlama.",
+ "link": "/hacks",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-07-11",
"type": "launch",
@@ -36,6 +46,16 @@
"launch"
]
},
+ {
+ "date": "2026-07-11",
+ "type": "launch",
+ "title": "DEX Volume Leaderboard",
+ "summary": "Every decentralized exchange ranked by trading volume, with 24h and 7d totals, 7-day change, and market share, plus an aggregate volume history chart. Live from DeFiLlama.",
+ "link": "/dex-volumes",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-07-11",
"type": "launch",
@@ -46,6 +66,36 @@
"launch"
]
},
+ {
+ "date": "2026-07-11",
+ "type": "launch",
+ "title": "Protocol Fees & Revenue",
+ "summary": "Fees paid by users and revenue kept by protocols across all of DeFi, ranked with 24h/7d/30d totals and an aggregate history chart. Toggle between fees and revenue; each protocol links to its detail page. Live from DeFiLlama.",
+ "link": "/fees",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-07-11",
+ "type": "launch",
+ "title": "Trending Crypto",
+ "summary": "The most-searched coins, categories, and NFTs on CoinGecko over the last 24 hours — trending rank, price, 24h change, market cap, and volume, each coin and category linking to its detail page. Auto-refreshing.",
+ "link": "/markets/trending",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-07-11",
+ "type": "update",
+ "title": "Detail pages for protocols, chains, and stablecoins — plus fees, DEX volumes, hacks, and trending",
+ "summary": "Every DeFiLlama list now opens into a full detail page. A protocol page charts its whole TVL history with funding-round and event markers, breaks TVL down per chain, and shows its fees, revenue, and methodology. A chain page charts TVL, stablecoin supply, and DEX volume side by side with the top protocols on that chain. A stablecoin page charts circulating supply over time, shows the per-chain distribution, and flags how far off-peg it is in basis points. On top of the detail pages there are four new market surfaces: protocol fees and revenue ranked and charted, the DEX-volume leaderboard with market share, a searchable database of every major DeFi hack ($16.7B stolen all-time), and a trending page of the most-searched coins, categories, and NFTs on CoinGecko. Everything is real, key-free data, and the yields, DeFi, chains, and stablecoin tables now link straight into the new detail pages.",
+ "link": "/fees",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-11",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 1114db28f..56f39d2ef 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,14 @@
<category>launch</category>
<description>Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage API keys, watch usage, and copy quickstarts.</description>
</item>
+ <item>
+ <title>DeFi Hacks Database</title>
+ <link>https://three.ws/hacks</link>
+ <guid isPermaLink="false">2026-07-11:DeFi Hacks Database</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>A searchable database of every major DeFi exploit — amount stolen, classification, technique, chains affected, whether it was a bridge hack, and the source, with all-time and trailing-12-month totals. Live from DeFiLlama.</description>
+ </item>
<item>
<title>DeFi Yields Explorer</title>
<link>https://three.ws/yields</link>
@@ -30,6 +38,14 @@
<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>DEX Volume Leaderboard</title>
+ <link>https://three.ws/dex-volumes</link>
+ <guid isPermaLink="false">2026-07-11:DEX Volume Leaderboard</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Every decentralized exchange ranked by trading volume, with 24h and 7d totals, 7-day change, and market share, plus an aggregate volume history chart. Live from DeFiLlama.</description>
+ </item>
<item>
<title>Premium Pass — Monthly Data API Access</title>
<link>https://three.ws/docs/premium</link>
@@ -38,6 +54,30 @@
<category>launch</category>
<description>One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.</description>
</item>
+ <item>
+ <title>Protocol Fees &amp; Revenue</title>
+ <link>https://three.ws/fees</link>
+ <guid isPermaLink="false">2026-07-11:Protocol Fees &amp; Revenue</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Fees paid by users and revenue kept by protocols across all of DeFi, ranked with 24h/7d/30d totals and an aggregate history chart. Toggle between fees and revenue; each protocol links to its detail page. Live from DeFiLlama.</description>
+ </item>
+ <item>
+ <title>Trending Crypto</title>
+ <link>https://three.ws/markets/trending</link>
+ <guid isPermaLink="false">2026-07-11:Trending Crypto</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>The most-searched coins, categories, and NFTs on CoinGecko over the last 24 hours — trending rank, price, 24h change, market cap, and volume, each coin and category linking to its detail page. Auto-refreshing.</description>
+ </item>
+ <item>
+ <title>Detail pages for protocols, chains, and stablecoins — plus fees, DEX volumes, hacks, and trending</title>
+ <link>https://three.ws/fees</link>
+ <guid isPermaLink="false">2026-07-11:Detail pages for protocols, chains, and stablecoins — plus fees, DEX volumes, hacks, and trending</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every DeFiLlama list now opens into a full detail page. A protocol page charts its whole TVL history with funding-round and event markers, breaks TVL down per chain, and shows its fees, revenue, and methodology. A chain page charts TVL, stablecoin supply, and DEX volume side by side with the top protocols on that chain. A stablecoin page charts circulating supply over time, shows the per-chain distribution, and flags how far off-peg it is in basis points. On top of the detail pages there are four new market surfaces: protocol fees and revenue ranked and charted, the DEX-volume leaderboard with market share, a searchable database of every major DeFi hack ($16.7B stolen all-time), and a trending page of the most-searched coins, categories, and NFTs on CoinGecko. Everything is real, key-free data, and the yields, DeFi, chains, and stablecoin tables now link straight into the new detail pages.</description>
+ </item>
<item>
<title>Documentation accuracy pass: every tutorial verified against the shipped platform</title>
<link>https://three.ws/docs/tutorials/embed-in-30-seconds</link>
diff --git a/public/features.json b/public/features.json
index 3b6369763..15c614542 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-11T04:07:32.399Z",
+ "generated_at": "2026-07-11T07:01:31.902Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -1576,6 +1576,46 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/fees",
+ "title": "Protocol Fees & Revenue",
+ "description": "Fees paid by users and revenue kept by protocols across all of DeFi, ranked with 24h/7d/30d totals and an aggregate history chart. Toggle between fees and revenue; each protocol links to its detail page. Live from DeFiLlama.",
+ "added": "2026-07-11",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
+ {
+ "path": "/dex-volumes",
+ "title": "DEX Volume Leaderboard",
+ "description": "Every decentralized exchange ranked by trading volume, with 24h and 7d totals, 7-day change, and market share, plus an aggregate volume history chart. Live from DeFiLlama.",
+ "added": "2026-07-11",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
+ {
+ "path": "/hacks",
+ "title": "DeFi Hacks Database",
+ "description": "A searchable database of every major DeFi exploit — amount stolen, classification, technique, chains affected, whether it was a bridge hack, and the source, with all-time and trailing-12-month totals. Live from DeFiLlama.",
+ "added": "2026-07-11",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
+ {
+ "path": "/markets/trending",
+ "title": "Trending Crypto",
+ "description": "The most-searched coins, categories, and NFTs on CoinGecko over the last 24 hours — trending rank, price, 24h change, market cap, and volume, each coin and category linking to its detail page. Auto-refreshing.",
+ "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.txt
index 8ae3bc8e0..99cb8bf2b 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -957,6 +957,30 @@ 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.
+### Protocol Fees & Revenue
+
+URL: https://three.ws/fees
+
+Fees paid by users and revenue kept by protocols across all of DeFi, ranked with 24h/7d/30d totals and an aggregate history chart. Toggle between fees and revenue; each protocol links to its detail page. Live from DeFiLlama.
+
+### DEX Volume Leaderboard
+
+URL: https://three.ws/dex-volumes
+
+Every decentralized exchange ranked by trading volume, with 24h and 7d totals, 7-day change, and market share, plus an aggregate volume history chart. Live from DeFiLlama.
+
+### DeFi Hacks Database
+
+URL: https://three.ws/hacks
+
+A searchable database of every major DeFi exploit — amount stolen, classification, technique, chains affected, whether it was a bridge hack, and the source, with all-time and trailing-12-month totals. Live from DeFiLlama.
+
+### Trending Crypto
+
+URL: https://three.ws/markets/trending
+
+The most-searched coins, categories, and NFTs on CoinGecko over the last 24 hours — trending rank, price, 24h change, market cap, and volume, each coin and category linking to its detail page. Auto-refreshing.
+
### BNB Chain — Three Genuinely-Unique Demos
URL: https://three.ws/bnb
diff --git a/public/llms.txt b/public/llms.txt
index 081f685eb..b7ce7b993 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -175,6 +175,10 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [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.
+- [Protocol Fees & Revenue](https://three.ws/fees): Fees paid by users and revenue kept by protocols across all of DeFi, ranked with 24h/7d/30d totals and an aggregate history chart. Toggle between fees and revenue; each protocol links to its detail page. Live from DeFiLlama.
+- [DEX Volume Leaderboard](https://three.ws/dex-volumes): Every decentralized exchange ranked by trading volume, with 24h and 7d totals, 7-day change, and market share, plus an aggregate volume history chart. Live from DeFiLlama.
+- [DeFi Hacks Database](https://three.ws/hacks): A searchable database of every major DeFi exploit — amount stolen, classification, technique, chains affected, whether it was a bridge hack, and the source, with all-time and trailing-12-month totals. Live from DeFiLlama.
+- [Trending Crypto](https://three.ws/markets/trending): The most-searched coins, categories, and NFTs on CoinGecko over the last 24 hours — trending rank, price, 24h change, market cap, and volume, each coin and category linking to its detail page. Auto-refreshing.
- [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.js
index b16d24138..7bc377c25 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -417,6 +417,26 @@ export const NAV_GROUPS = [
href: '/yields',
desc: 'Explore ~15k live yield pools — APY, TVL, and per-pool history from DeFiLlama',
},
+ {
+ title: 'Protocol Fees',
+ href: '/fees',
+ desc: 'Fees paid and revenue kept across DeFi protocols, ranked and charted',
+ },
+ {
+ title: 'DEX Volumes',
+ href: '/dex-volumes',
+ desc: 'Decentralized-exchange volume leaderboard with 24h/7d totals and share',
+ },
+ {
+ title: 'Hacks Database',
+ href: '/hacks',
+ desc: 'Every major DeFi exploit — amount stolen, technique, chain, and source',
+ },
+ {
+ title: 'Trending',
+ href: '/markets/trending',
+ desc: 'The most-searched coins, categories, and NFTs on CoinGecko right now',
+ },
{
title: 'Coin Intelligence',
href: '/coin-intel',
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 07602d647..69b61e505 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,6 +56,25 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
+
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:title" content="Sitemap · three.ws">
+ <meta property="og:description" content="Human-readable index of every page on three.ws.">
+ <meta property="og:url" content="https://three.ws/sitemap">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="og:image:type" content="image/png">
+ <meta property="og:image:alt" content="Sitemap — three.ws">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="twitter:title" content="Sitemap · three.ws">
+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script>
</head>
<body>
<header class="sm-topbar">
@@ -65,7 +84,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 419 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 423 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 +96,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 419 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 423 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 +737,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>106</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>110</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -1205,6 +1224,34 @@
<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="/fees">
+ <span class="sm-title">Protocol Fees &amp; Revenue</span>
+ <span class="sm-path">/fees</span>
+ <span class="sm-desc">Fees paid by users and revenue kept by protocols across all of DeFi, ranked with 24h/7d/30d totals and an aggregate history chart. Toggle between fees and revenue; each protocol links to its detail page. Live from DeFiLlama.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/dex-volumes">
+ <span class="sm-title">DEX Volume Leaderboard</span>
+ <span class="sm-path">/dex-volumes</span>
+ <span class="sm-desc">Every decentralized exchange ranked by trading volume, with 24h and 7d totals, 7-day change, and market share, plus an aggregate volume history chart. Live from DeFiLlama.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/hacks">
+ <span class="sm-title">DeFi Hacks Database</span>
+ <span class="sm-path">/hacks</span>
+ <span class="sm-desc">A searchable database of every major DeFi exploit — amount stolen, classification, technique, chains affected, whether it was a bridge hack, and the source, with all-time and trailing-12-month totals. Live from DeFiLlama.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/markets/trending">
+ <span class="sm-title">Trending Crypto</span>
+ <span class="sm-path">/markets/trending</span>
+ <span class="sm-desc">The most-searched coins, categories, and NFTs on CoinGecko over the last 24 hours — trending rank, price, 24h change, market cap, and volume, each coin and category linking to its detail page. Auto-refreshing.</span>
+ </a>
+ </li>
<li>
<a href="/bnb">
<span class="sm-title">BNB Chain — Three Genuinely-Unique Demos</span>
diff --git a/src/chain-page.css b/src/chain-page.css
new file mode 100644
index 000000000..f7cf26c1a
--- /dev/null
+++ b/src/chain-page.css
@@ -0,0 +1,196 @@
+/*
+ * /chain/:name — feature styles layered on top of /src/coin-pages.css.
+ * Reuses the shared cv-* container, card, chart, table, pill, toolbar, and
+ * state system; adds only the hero, meta chips, protocol-cell, and sortable-
+ * header affordances unique to this detail page.
+ */
+
+/* ── Hero ──────────────────────────────────────────────────────────────────── */
+
+.ch-hero {
+ margin: 0.5rem 0 2rem;
+}
+.ch-title-row {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 0.625rem 0.75rem;
+}
+.ch-title {
+ margin: 0;
+ font-size: clamp(1.75rem, 5vw, 2.5rem);
+ line-height: 1.05;
+}
+.ch-meta {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.375rem;
+ margin: 0.875rem 0 0;
+}
+.ch-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;
+}
+.ch-chip-rank {
+ 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);
+ font-weight: 600;
+ font-family: var(--cv-font-mono);
+ font-variant-numeric: tabular-nums;
+}
+.ch-lede {
+ margin: 1.125rem 0 0;
+ max-width: 62ch;
+ color: var(--cv-text-2);
+ font-size: 0.9375rem;
+ line-height: 1.55;
+}
+.ch-back {
+ margin: 1rem 0 0;
+ font-size: 0.875rem;
+}
+.ch-back a {
+ color: var(--cv-text-3);
+ text-decoration: none;
+ transition: color 0.15s;
+}
+.ch-back a:hover,
+.ch-back a:focus-visible {
+ color: var(--cv-accent);
+}
+.ch-back a:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+ border-radius: var(--cv-radius-sm);
+}
+
+/* ── Stat cards ────────────────────────────────────────────────────────────── */
+
+.ch-stat .sub {
+ margin-top: 0.25rem;
+}
+
+/* ── Chart spacing (three stacked panels) ──────────────────────────────────── */
+
+#ch-tvl-chart:not(:empty),
+#ch-stable-chart:not(:empty),
+#ch-dex-chart:not(:empty) {
+ display: block;
+ margin-top: 1.25rem;
+}
+.cv-chart-tip .ch-tip-date {
+ font-size: 0.75rem;
+ color: var(--cv-text-3);
+ margin-top: 0.125rem;
+}
+
+/* ── Protocol table ────────────────────────────────────────────────────────── */
+
+.ch-proto {
+ display: inline-flex;
+ align-items: center;
+ min-width: 0;
+}
+.ch-proto-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ color: var(--cv-text);
+ text-decoration: none;
+ font-weight: 500;
+ transition: color 0.15s;
+ min-width: 0;
+}
+.ch-proto-link:hover,
+.ch-proto-link:focus-visible {
+ color: var(--cv-accent);
+}
+.ch-proto-link:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+ border-radius: var(--cv-radius-sm);
+}
+.ch-proto-logo {
+ width: 22px;
+ height: 22px;
+ border-radius: 6px;
+ object-fit: contain;
+ background: var(--cv-surface-2);
+ border: 1px solid var(--cv-border);
+ flex-shrink: 0;
+}
+.ch-proto-logo-fallback {
+ display: inline-block;
+}
+
+.ch-proto-table td .dim {
+ color: var(--cv-text-3);
+}
+
+.ch-mkt-note {
+ margin: 0.875rem 0 0;
+ font-size: 0.8125rem;
+ color: var(--cv-text-3);
+}
+
+/* Sortable column headers. */
+.ch-sortable {
+ cursor: pointer;
+ user-select: none;
+ white-space: nowrap;
+ transition: color 0.15s;
+}
+.ch-sortable:hover {
+ color: var(--cv-text);
+}
+.ch-sortable.active {
+ color: var(--cv-accent);
+}
+.ch-sortable:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: -2px;
+ border-radius: var(--cv-radius-sm);
+}
+
+/* ── Error-state retry button ──────────────────────────────────────────────── */
+
+.ch-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;
+}
+.ch-retry:hover {
+ border-color: var(--cv-border-hover);
+ background: var(--cv-surface-3);
+}
+.ch-retry:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ch-proto-link,
+ .ch-back a,
+ .ch-sortable,
+ .ch-retry {
+ transition: none;
+ }
+}
diff --git a/src/chain-page.js b/src/chain-page.js
new file mode 100644
index 000000000..a376ccad0
--- /dev/null
+++ b/src/chain-page.js
@@ -0,0 +1,560 @@
+// /chain/:name — rich profile for one blockchain, part of the three.ws Markets
+// surface. Hero (chain name + native-token / chainId / rank / dominance chips),
+// stat cards (TVL, share of DeFi, stablecoin supply, 24h DEX volume, 24h fees,
+// protocol count), three interactive SVG charts (TVL history, stablecoin supply,
+// DEX volume) each with a range toggle and crosshair tooltip, and a sortable
+// table of the top protocols deployed on the chain (each linking to its
+// /protocol/:slug page). Data comes from the /api/defi/chain proxy (DeFiLlama) —
+// never mocked. Mirrors the /exchange/:id detail-page pattern (src/exchange-page.js).
+
+import {
+ formatUsd,
+ formatPercent,
+ formatChartTick,
+ escapeHtml as esc,
+} from './shared/coin-format.js';
+
+const $ = (id) => document.getElementById(id);
+
+// Matches the /chain/:name route; falls back to the ?name= query for direct
+// links and dev proxies that don't rewrite the path.
+function nameFromLocation() {
+ const m = location.pathname.match(/^\/chain\/([A-Za-z0-9 ._%-]{1,40})$/);
+ if (m) {
+ try {
+ return decodeURIComponent(m[1]);
+ } catch {
+ return m[1];
+ }
+ }
+ const q = new URLSearchParams(location.search).get('name');
+ return q && /^[A-Za-z0-9 ._-]{1,40}$/.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();
+}
+
+// ── Skeletons ────────────────────────────────────────────────────────────────
+
+function renderSkeletons() {
+ $('ch-hero').innerHTML = `
+ <div class="ch-hero">
+ <div class="cv-skel" style="width:14rem;height:2.25rem"></div>
+ <div class="cv-skel" style="width:26rem;max-width:100%;height:1.5rem;margin-top:0.875rem"></div>
+ </div>`;
+ $('ch-stats').innerHTML =
+ '<div class="cv-stats-grid">' +
+ Array.from({ length: 6 }, () => '<div class="cv-skel" style="height:5.5rem"></div>').join('') +
+ '</div>';
+ $('ch-tvl-chart').innerHTML =
+ '<div class="cv-chart-panel"><div class="cv-skel" style="height:300px;border-radius:8px"></div></div>';
+ $('ch-stable-chart').innerHTML = '';
+ $('ch-dex-chart').innerHTML = '';
+ $('ch-protocols').innerHTML = `
+ <h2 class="cv-h2">Top protocols</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 chip(text, title) {
+ return `<span class="ch-chip"${title ? ` title="${esc(title)}"` : ''}>${esc(text)}</span>`;
+}
+
+function renderHero(c) {
+ $('ch-crumb-name').textContent = c.name;
+ const chips = [];
+ if (c.token_symbol) chips.push(chip(c.token_symbol, 'Native token'));
+ if (c.chain_id != null) chips.push(chip(`Chain ID ${c.chain_id}`, 'EVM chain ID'));
+ if (c.rank != null)
+ chips.push(`<span class="ch-chip ch-chip-rank" title="Rank by total value locked">#${esc(String(c.rank))} by TVL</span>`);
+ if (c.share_pct != null)
+ chips.push(chip(`${c.share_pct.toFixed(2)}% of DeFi TVL`, "This chain's dominance share of all on-chain DeFi TVL"));
+
+ $('ch-hero').innerHTML = `
+ <div class="ch-hero">
+ <div class="ch-title-row">
+ <h1 class="cv-h1 ch-title">${esc(c.name)}</h1>
+ </div>
+ ${chips.length ? `<div class="ch-meta">${chips.join('')}</div>` : ''}
+ <p class="ch-lede">
+ Total value locked, stablecoin supply, DEX volume, fees, and the protocols
+ deployed on ${esc(c.name)} — live from DeFiLlama.
+ </p>
+ <p class="ch-back"><a href="/chains">← All chains by TVL</a></p>
+ </div>`;
+}
+
+// ── Stat cards ───────────────────────────────────────────────────────────────
+
+function statCard({ label, value, sub }) {
+ return `
+ <div class="cv-mini-stat ch-stat">
+ <p class="label">${esc(label)}</p>
+ <p class="value cv-mono">${esc(value)}</p>
+ ${sub ? `<p class="sub">${esc(sub)}</p>` : ''}
+ </div>`;
+}
+
+function renderStats(payload) {
+ const c = payload.chain;
+ const cards = [];
+ cards.push(statCard({ label: 'Total Value Locked', value: formatUsd(c.tvl) }));
+ if (c.share_pct != null)
+ cards.push(
+ statCard({
+ label: 'Share of DeFi',
+ value: `${c.share_pct.toFixed(2)}%`,
+ sub: c.rank != null ? `Rank #${c.rank}` : undefined,
+ }),
+ );
+ if (payload.stablecoins && payload.stablecoins.total != null)
+ cards.push(statCard({ label: 'Stablecoin Supply', value: formatUsd(payload.stablecoins.total) }));
+ if (payload.dex && payload.dex.total24h != null)
+ cards.push(
+ statCard({
+ label: '24h DEX Volume',
+ value: formatUsd(payload.dex.total24h),
+ sub: payload.dex.total7d != null ? `${formatUsd(payload.dex.total7d)} 7d` : undefined,
+ }),
+ );
+ if (payload.fees && payload.fees.total24h != null)
+ cards.push(
+ statCard({
+ label: '24h Fees',
+ value: formatUsd(payload.fees.total24h),
+ sub: payload.fees.total7d != null ? `${formatUsd(payload.fees.total7d)} 7d` : undefined,
+ }),
+ );
+ if (payload.protocol_count != null)
+ cards.push(statCard({ label: 'Protocols', value: payload.protocol_count.toLocaleString('en-US') }));
+
+ $('ch-stats').innerHTML = `<div class="cv-stats-grid">${cards.join('')}</div>`;
+}
+
+// ── Reusable SVG area chart with range toggle + crosshair ────────────────────
+
+const CHART_W = 800;
+const CHART_H = 300;
+const PAD = { top: 20, right: 84, bottom: 30, left: 10 };
+
+const RANGES = [
+ { label: '30D', days: 30 },
+ { label: '90D', days: 90 },
+ { label: '1Y', days: 365 },
+ { label: 'All', days: Infinity },
+];
+
+// Build a self-contained chart instance bound to a container. `series` is the
+// full history [{ t, value }]; the range toggle slices it client-side (the API
+// already returns full downsampled history, so no refetch is needed).
+function makeChart({ el, title, series, color, format }) {
+ const state = { days: rangeDefault(series), series };
+
+ function visible() {
+ if (!Number.isFinite(state.days)) return state.series;
+ const cutoff = Date.now() - state.days * 86_400_000;
+ const win = state.series.filter((p) => p.t >= cutoff);
+ return win.length >= 2 ? win : state.series;
+ }
+
+ function geometry(pts) {
+ const vals = pts.map((p) => p.value);
+ const min = Math.min(...vals, 0);
+ 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 coords = pts.map((p, i) => ({
+ x: PAD.left + (pts.length === 1 ? w / 2 : (i / (pts.length - 1)) * w),
+ y: PAD.top + h - ((p.value - min) / range) * h,
+ }));
+ const line = coords.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(2)},${p.y.toFixed(2)}`).join(' ');
+ const area = `${line} L${coords[coords.length - 1].x.toFixed(2)},${(PAD.top + h).toFixed(2)} L${coords[0].x.toFixed(2)},${(PAD.top + h).toFixed(2)} Z`;
+ return { min, max, range, coords, line, area };
+ }
+
+ function draw() {
+ const pts = visible();
+ const rangeBtns = RANGES.map(
+ (r) =>
+ `<button type="button" class="cv-range-btn" data-days="${r.days}" aria-pressed="${r.days === state.days}">${r.label}</button>`,
+ ).join('');
+
+ let body;
+ if (pts.length < 2) {
+ body = '<div class="cv-chart-state">No history available for this range.</div>';
+ } else {
+ const g = geometry(pts);
+ 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(format(v))}</text></g>`;
+ }).join('');
+ const gid = `grad-${title.replace(/\W+/g, '')}`;
+ body = `
+ <div class="cv-chart-area">
+ <svg viewBox="0 0 ${CHART_W} ${CHART_H}" role="img" aria-label="${esc(title)} history">
+ <defs>
+ <linearGradient id="${gid}" 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(#${gid})"/>
+ <path d="${g.line}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
+ <g class="ch-crosshair" hidden>
+ <line class="ch-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 class="ch-cross-dot" r="4" fill="${color}" stroke="var(--cv-surface)" stroke-width="2"/>
+ </g>
+ </svg>
+ <div class="cv-chart-tip" hidden>
+ <p class="p cv-mono ch-tip-val"></p>
+ <p class="d ch-tip-date"></p>
+ </div>
+ </div>`;
+ }
+
+ el.innerHTML = `
+ <div class="cv-chart-panel">
+ <div class="cv-chart-bar">
+ <div class="left"><span class="title">${esc(title)}</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 === state.days) return;
+ state.days = dd;
+ draw();
+ });
+ });
+
+ wirePointer(pts);
+ }
+
+ function wirePointer(pts) {
+ const svg = el.querySelector('svg');
+ const tip = el.querySelector('.cv-chart-tip');
+ if (!svg || !tip || pts.length < 2) return;
+ const g = geometry(pts);
+ const cross = svg.querySelector('.ch-crosshair');
+ const crossLine = svg.querySelector('.ch-cross-line');
+ const crossDot = svg.querySelector('.ch-cross-dot');
+ const usableW = CHART_W - PAD.left - PAD.right;
+ const usableH = CHART_H - PAD.top - PAD.bottom;
+ const days = Number.isFinite(state.days) ? state.days : 3650;
+
+ const show = (clientX) => {
+ const rect = svg.getBoundingClientRect();
+ const mouseX = ((clientX - rect.left) / rect.width) * CHART_W;
+ const n = pts.length;
+ const i = Math.max(0, Math.min(n - 1, Math.round(((mouseX - PAD.left) / usableW) * (n - 1))));
+ const p = pts[i];
+ const x = PAD.left + (i / (n - 1)) * usableW;
+ const y = PAD.top + usableH - ((p.value - 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}%`;
+ tip.querySelector('.ch-tip-val').textContent = format(p.value);
+ tip.querySelector('.ch-tip-date').textContent = formatChartTick(p.t, days);
+ };
+ const 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));
+ }
+
+ draw();
+}
+
+// Default range: the tightest window that still shows ≥2 points, so a young
+// chain with only weeks of history doesn't open on an empty "1Y" view.
+function rangeDefault(series) {
+ for (const days of [30, 90, 365]) {
+ const cutoff = Date.now() - days * 86_400_000;
+ if (series.filter((p) => p.t >= cutoff).length >= 2) return days;
+ }
+ return Infinity;
+}
+
+// ── Top-protocols table (sortable) ───────────────────────────────────────────
+
+const protoState = { rows: [], sort: 'tvl', dir: -1, chainName: '' };
+
+function sortRows() {
+ const { rows, sort, dir } = protoState;
+ const keyed = rows.slice().sort((a, b) => {
+ let av;
+ let bv;
+ if (sort === 'name') {
+ av = (a.name || '').toLowerCase();
+ bv = (b.name || '').toLowerCase();
+ return av < bv ? -dir : av > bv ? dir : 0;
+ }
+ if (sort === 'category') {
+ av = (a.category || '').toLowerCase();
+ bv = (b.category || '').toLowerCase();
+ return av < bv ? -dir : av > bv ? dir : 0;
+ }
+ av = sort === 'change_7d' ? (a.change_7d ?? -Infinity) : (a.tvl_on_chain ?? -Infinity);
+ bv = sort === 'change_7d' ? (b.change_7d ?? -Infinity) : (b.tvl_on_chain ?? -Infinity);
+ return (av - bv) * dir;
+ });
+ return keyed;
+}
+
+function changeCell(v) {
+ if (v == null || !Number.isFinite(v)) return '<span class="dim">—</span>';
+ return `<span class="${v >= 0 ? 'cv-up' : 'cv-down'}">${esc(formatPercent(v))}</span>`;
+}
+
+function protoRow(p) {
+ const label = esc(p.name || 'Unknown');
+ const logo = p.logo
+ ? `<img class="ch-proto-logo" src="${esc(p.logo)}" alt="" width="22" height="22" loading="lazy" data-no-dark-filter />`
+ : '<span class="ch-proto-logo ch-proto-logo-fallback" aria-hidden="true"></span>';
+ const nameCell = p.slug
+ ? `<a class="ch-proto-link" href="/protocol/${encodeURIComponent(p.slug)}">${logo}<span>${label}</span></a>`
+ : `<span class="ch-proto-link">${logo}<span>${label}</span></span>`;
+ return `
+ <tr>
+ <td class="left"><span class="ch-proto">${nameCell}</span></td>
+ <td>${p.category ? esc(p.category) : '<span class="dim">—</span>'}</td>
+ <td class="cv-mono">${esc(formatUsd(p.tvl_on_chain))}</td>
+ <td class="cv-mono">${changeCell(p.change_7d)}</td>
+ </tr>`;
+}
+
+function sortHeader(key, label, extraClass) {
+ const active = protoState.sort === key;
+ const arrow = active ? (protoState.dir === -1 ? ' ▼' : ' ▲') : '';
+ return `<th scope="col" class="ch-sortable${extraClass ? ` ${extraClass}` : ''}${active ? ' active' : ''}" data-sort="${key}" role="button" tabindex="0" aria-sort="${active ? (protoState.dir === -1 ? 'descending' : 'ascending') : 'none'}">${esc(label)}${arrow}</th>`;
+}
+
+function renderProtocols(payload) {
+ const el = $('ch-protocols');
+ protoState.rows = Array.isArray(payload.protocols) ? payload.protocols : [];
+ protoState.chainName = payload.chain.name;
+
+ if (!protoState.rows.length) {
+ el.innerHTML = `
+ <div class="cv-toolbar">
+ <h2 class="cv-h2" style="margin:0">Top protocols</h2>
+ <a class="cv-pill" href="/defi">All protocols →</a>
+ </div>
+ <div class="cv-empty">No DeFi protocols are reporting TVL on ${esc(payload.chain.name)} right now. Once a protocol deploys and reports here, it will appear in this table.</div>`;
+ return;
+ }
+ drawProtoTable();
+}
+
+function drawProtoTable() {
+ const el = $('ch-protocols');
+ const rows = sortRows();
+ const total = protoState.rows.length;
+ const note =
+ protoState.chainName && total >= 50
+ ? `<p class="ch-mkt-note">Showing the top 50 protocols by TVL on ${esc(protoState.chainName)}.</p>`
+ : '';
+
+ el.innerHTML = `
+ <div class="cv-toolbar">
+ <h2 class="cv-h2" style="margin:0">Top protocols</h2>
+ <a class="cv-pill" href="/defi">All protocols →</a>
+ </div>
+ <div class="cv-table-wrap">
+ <table class="cv-table ch-proto-table">
+ <thead>
+ <tr>
+ ${sortHeader('name', 'Protocol', 'left')}
+ ${sortHeader('category', 'Category')}
+ ${sortHeader('tvl', 'TVL on chain')}
+ ${sortHeader('change_7d', '7d')}
+ </tr>
+ </thead>
+ <tbody>${rows.map(protoRow).join('')}</tbody>
+ </table>
+ </div>
+ ${note}`;
+
+ el.querySelectorAll('.ch-sortable').forEach((th) => {
+ const apply = () => {
+ const key = th.dataset.sort;
+ if (protoState.sort === key) protoState.dir *= -1;
+ else {
+ protoState.sort = key;
+ // Text columns default A→Z; numeric columns default high→low.
+ protoState.dir = key === 'name' || key === 'category' ? 1 : -1;
+ }
+ drawProtoTable();
+ };
+ th.addEventListener('click', apply);
+ th.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ apply();
+ }
+ });
+ });
+}
+
+// ── Error / not-found states ─────────────────────────────────────────────────
+
+function clearSections() {
+ $('ch-stats').innerHTML = '';
+ $('ch-tvl-chart').innerHTML = '';
+ $('ch-stable-chart').innerHTML = '';
+ $('ch-dex-chart').innerHTML = '';
+ $('ch-protocols').innerHTML = '';
+}
+
+function renderNotFound(name) {
+ $('ch-crumb-name').textContent = 'Not found';
+ $('ch-hero').innerHTML = `
+ <h1 class="cv-h1">Chain not found</h1>
+ <div class="cv-empty" style="text-align:left">
+ <p style="margin:0 0 0.75rem">Could not find a blockchain for “${esc(name)}”. It may not be
+ tracked by the market-data source, or the name is misspelled.</p>
+ <p style="margin:0">Browse the <a href="/chains">chains directory</a> or head back to
+ <a href="/markets">Markets</a>.</p>
+ </div>`;
+ clearSections();
+}
+
+function renderError() {
+ $('ch-hero').innerHTML = `
+ <h1 class="cv-h1">Chain 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="ch-retry" id="ch-retry">Retry</button>
+ <span style="margin-left:0.75rem">or return to the <a href="/chains">chains directory</a>.</span>
+ </div>`;
+ clearSections();
+ $('ch-retry')?.addEventListener('click', () => main());
+}
+
+// ── SEO / document metadata ──────────────────────────────────────────────────
+
+function updateMeta(c) {
+ const title = `${c.name} — Chain TVL · three.ws`;
+ document.title = title;
+ const url = `https://three.ws/chain/${encodeURIComponent(c.name)}`;
+ const set = (sel, attr, val) => document.querySelector(sel)?.setAttribute(attr, val);
+ const tvl = formatUsd(c.tvl);
+ const desc = `${c.name} blockchain profile — ${tvl} total value locked${c.rank != null ? ` (rank #${c.rank})` : ''}, stablecoin supply, DEX volume, fees, and top protocols. Real DeFiLlama 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);
+ 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 name = nameFromLocation();
+ const root = $('ch-main');
+ if (!name) {
+ location.replace('/chains');
+ return;
+ }
+ renderSkeletons();
+
+ let payload;
+ try {
+ payload = await getJson(`/api/defi/chain?name=${encodeURIComponent(name)}`);
+ } catch (err) {
+ root.removeAttribute('aria-busy');
+ if (err.status === 404 || err.status === 400) renderNotFound(name);
+ else renderError();
+ return;
+ }
+
+ const c = payload.chain || {};
+ root.removeAttribute('aria-busy');
+
+ updateMeta(c);
+ renderHero(c);
+ renderStats(payload);
+ renderProtocols(payload);
+
+ // TVL chart — always present for a tracked chain.
+ const tvlSeries = (payload.tvl_series || []).map((p) => ({ t: p.t, value: p.tvl }));
+ if (tvlSeries.length >= 2) {
+ makeChart({
+ el: $('ch-tvl-chart'),
+ title: 'Total Value Locked',
+ series: tvlSeries,
+ color: 'var(--cv-chart-green)',
+ format: formatUsd,
+ });
+ } else {
+ $('ch-tvl-chart').innerHTML = '';
+ }
+
+ // Stablecoin supply — hidden when the chain has no stablecoin history.
+ const stableSeries = (payload.stablecoins?.series || []).map((p) => ({ t: p.t, value: p.total }));
+ if (stableSeries.length >= 2 && stableSeries.some((p) => p.value > 0)) {
+ makeChart({
+ el: $('ch-stable-chart'),
+ title: 'Stablecoin Supply',
+ series: stableSeries,
+ color: 'var(--cv-accent)',
+ format: formatUsd,
+ });
+ } else {
+ $('ch-stable-chart').innerHTML = '';
+ }
+
+ // DEX volume — hidden when the chain has no DEX coverage.
+ const dexSeries = (payload.dex?.series || []).map((p) => ({ t: p.t, value: p.v }));
+ if (dexSeries.length >= 2 && dexSeries.some((p) => p.value > 0)) {
+ makeChart({
+ el: $('ch-dex-chart'),
+ title: 'DEX Volume',
+ series: dexSeries,
+ color: 'var(--cv-chart-red)',
+ format: formatUsd,
+ });
+ } else {
+ $('ch-dex-chart').innerHTML = '';
+ }
+
+ const upd = $('ch-updated');
+ upd.hidden = false;
+ upd.textContent = `Updated ${new Date(payload.updated_at || Date.now()).toLocaleTimeString('en-US')} · source: DeFiLlama`;
+}
+
+main();
diff --git a/src/chains.js b/src/chains.js
index 0ba83cc28..386b77241 100644
--- a/src/chains.js
+++ b/src/chains.js
@@ -155,8 +155,12 @@ function renderTable() {
const body = sortedChains()
.map((c) => {
const barPct = Math.max(2, ((c.share_pct || 0) / maxShare) * 100);
+ // Whole row opens the internal /chain/:name detail page; keyboard-accessible.
+ const nav = c.name
+ ? ` data-href="/chain/${encodeURIComponent(c.name)}" tabindex="0" role="link" aria-label="Open ${esc(c.name)} chain detail"`
+ : '';
return `
- <tr>
+ <tr${nav}>
<td class="rank hide-sm cv-mono">${c.__rank}</td>
<td class="left name-cell"><span class="inner">
<span class="nm">${esc(c.name)}</span>
@@ -200,6 +204,18 @@ function renderTable() {
}
});
});
+
+ // Row → /chain/:name navigation (header clicks sort, never navigate).
+ el.querySelectorAll('tr[data-href]').forEach((tr) => {
+ const go = () => location.assign(tr.dataset.href);
+ tr.addEventListener('click', go);
+ tr.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ go();
+ }
+ });
+ });
}
// ── Boot ──────────────────────────────────────────────────────────────────
diff --git a/src/defi.js b/src/defi.js
index a1f2232d7..67565bc75 100644
--- a/src/defi.js
+++ b/src/defi.js
@@ -212,8 +212,13 @@ function renderTable() {
const body = rows
.map((p) => {
+ // Whole row opens the internal /protocol/:slug detail page when we have
+ // a DeFiLlama slug; keyboard-accessible.
+ const nav = p.slug
+ ? ` data-href="/protocol/${encodeURIComponent(p.slug)}" tabindex="0" role="link" aria-label="Open ${esc(p.name)} protocol detail"`
+ : '';
return `
- <tr>
+ <tr${nav}>
<td class="rank hide-sm cv-mono">${p.__rank}</td>
<td class="left name-cell"><span class="inner">
${p.logo ? `<img src="${esc(p.logo)}" alt="" loading="lazy" width="24" height="24" data-no-dark-filter />` : '<span class="defi-logo-fallback" aria-hidden="true"></span>'}
@@ -256,6 +261,18 @@ function renderTable() {
}
});
});
+
+ // Row → /protocol/:slug navigation (header clicks sort, never navigate).
+ el.querySelectorAll('tr[data-href]').forEach((tr) => {
+ const go = () => location.assign(tr.dataset.href);
+ tr.addEventListener('click', go);
+ tr.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ go();
+ }
+ });
+ });
}
// ── Boot ──────────────────────────────────────────────────────────────────
diff --git a/src/dex-volumes.css b/src/dex-volumes.css
new file mode 100644
index 000000000..56286244e
--- /dev/null
+++ b/src/dex-volumes.css
@@ -0,0 +1,140 @@
+/*
+ * /dex-volumes — DEX volume rankings. Layered after coin-pages.css: reuses the
+ * cv-* token system, stat cards, chart panel, and table. This file only adds the
+ * stat grid, chain chips, the DEX name link, the logo fallback, and the inline
+ * market-share bar. Both themes inherit from the shared data-theme tokens.
+ */
+
+.dx-stat-grid {
+ display: grid;
+ gap: 1rem;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+}
+
+/* Rows are navigable only via the DEX-name link, not the whole row — reset the
+ shared table's pointer cursor so nothing else signals a click target. */
+#dx-table .cv-table tbody tr {
+ cursor: default;
+}
+
+/* ── Chain chips ───────────────────────────────────────────────────────────── */
+/* Flex lives on this inner wrapper, never the <td>, so the column's responsive
+ `hide-lg` display:none is not overridden at narrow widths. */
+.dx-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.3125rem;
+ align-items: center;
+}
+.dx-chip {
+ display: inline-block;
+ padding: 0.0625rem 0.4375rem;
+ font-size: 0.75rem;
+ line-height: 1.4;
+ color: var(--cv-text-2);
+ background: var(--cv-surface-3);
+ border: 1px solid var(--cv-border);
+ border-radius: 999px;
+ text-decoration: none;
+ white-space: nowrap;
+ transition:
+ border-color 0.15s,
+ color 0.15s,
+ background 0.15s;
+}
+.dx-chip:hover,
+.dx-chip:focus-visible {
+ color: var(--cv-text);
+ border-color: var(--cv-accent);
+ background: color-mix(in srgb, var(--cv-accent) 12%, var(--cv-surface-3));
+ outline: none;
+}
+.dx-more {
+ color: var(--cv-text-3);
+ font-size: 0.75rem;
+ font-variant-numeric: tabular-nums;
+}
+
+/* ── DEX name link ─────────────────────────────────────────────────────────── */
+.dx-name-link {
+ text-decoration: none;
+ color: inherit;
+ border-radius: var(--cv-radius-sm);
+}
+.dx-name-link .nm {
+ transition: color 0.15s;
+}
+.dx-name-link:hover .nm,
+.dx-name-link:focus-visible .nm {
+ color: var(--cv-accent);
+ text-decoration: underline;
+}
+.dx-name-link:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 25%, transparent);
+}
+
+.dx-logo-fallback {
+ display: inline-block;
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ background: var(--cv-surface-3);
+ flex-shrink: 0;
+}
+
+/* ── Market-share bar ──────────────────────────────────────────────────────── */
+.dx-share-cell {
+ min-width: 160px;
+}
+.dx-share {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+.dx-share-bar {
+ display: block;
+ flex: 1;
+ max-width: 160px;
+ height: 8px;
+ border-radius: 999px;
+ background: var(--cv-surface-3);
+ overflow: hidden;
+}
+.dx-share-fill {
+ display: block;
+ height: 100%;
+ border-radius: 999px;
+ background: linear-gradient(
+ 90deg,
+ var(--cv-accent),
+ color-mix(in srgb, var(--cv-accent) 55%, transparent)
+ );
+ transition: width 0.4s ease;
+}
+.dx-share-num {
+ font-size: 0.75rem;
+ color: var(--cv-text-3);
+ white-space: nowrap;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .dx-share-fill {
+ transition: none;
+ }
+}
+
+/* Retry button in the error / empty states reads as a link, matching cv-empty. */
+.dx-retry {
+ appearance: none;
+ border: 0;
+ background: transparent;
+ color: var(--cv-accent);
+ font: inherit;
+ cursor: pointer;
+ padding: 0;
+ text-decoration: underline;
+}
+.dx-retry:hover {
+ color: var(--cv-accent-hover);
+}
diff --git a/src/dex-volumes.js b/src/dex-volumes.js
new file mode 100644
index 000000000..441b4417d
--- /dev/null
+++ b/src/dex-volumes.js
@@ -0,0 +1,421 @@
+// /dex-volumes — DEX volume rankings. Header stat cards (24h volume, 7d volume,
+// 7d-over-prior-7d change), an aggregate SVG area chart with a range toggle +
+// crosshair, and a sortable table of the top DEXs by 24h volume with an inline
+// market-share bar. DEX names deep-link to /protocol/:slug and chain chips to
+// /chain/:name. Data comes from /api/defi/dex-volumes (DeFiLlama, keyless),
+// normalized server-side. Mirrors the /defi + /exchange + /fees page patterns:
+// stat cards, cv-chart-panel, sortable cv-table, designed loading/empty/error.
+
+import {
+ formatUsd,
+ formatPercent,
+ formatChartTick,
+ 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();
+}
+
+// ── State ───────────────────────────────────────────────────────────────────
+
+const state = {
+ total24h: null,
+ total7d: null,
+ change_7dover7d: null,
+ chart: [],
+ protocols: [],
+ updated_at: 0,
+ sortKey: 'total24h',
+ sortDir: 'desc',
+ loading: true,
+ error: false,
+};
+
+// ── Stat cards ──────────────────────────────────────────────────────────────
+
+const ICONS = {
+ swap: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>',
+ week: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>',
+ trend: '<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>',
+};
+
+function statCard({ label, value, delta, deltaClass, icon }) {
+ return `
+ <div class="cv-stat-card">
+ <div style="min-width:0">
+ <p class="label">${esc(label)}</p>
+ <p class="value cv-mono">${esc(value)}</p>
+ ${delta ? `<p class="delta ${deltaClass || ''}">${esc(delta)}</p>` : ''}
+ </div>
+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>
+ </div>`;
+}
+
+function renderStats() {
+ const el = $('dx-stats');
+ const c = state.change_7dover7d;
+ const deltaClass = c == null ? '' : c >= 0 ? 'cv-up' : 'cv-down';
+ const cards = [
+ statCard({ label: '24h DEX Volume', value: formatUsd(state.total24h), icon: 'swap' }),
+ statCard({ label: '7d DEX Volume', value: formatUsd(state.total7d), icon: 'week' }),
+ statCard({
+ label: '7d Change',
+ value: c == null ? '—' : formatPercent(c),
+ delta: 'vs prior 7 days',
+ deltaClass,
+ icon: 'trend',
+ }),
+ ];
+ el.innerHTML = `<div class="dx-stat-grid">${cards.join('')}</div>`;
+}
+
+function statsSkeleton() {
+ $('dx-stats').innerHTML =
+ '<div class="dx-stat-grid">' +
+ Array.from({ length: 3 }, () => '<div class="cv-skel" style="height:6rem"></div>').join('') +
+ '</div>';
+}
+
+// ── Aggregate chart ─────────────────────────────────────────────────────────
+
+const TIME_RANGES = [
+ { label: '30D', days: 30 },
+ { label: '90D', days: 90 },
+ { label: '1Y', days: 365 },
+ { label: 'All', days: Infinity },
+];
+
+const CHART_W = 800;
+const CHART_H = 300;
+const PAD = { top: 20, right: 80, bottom: 30, left: 10 };
+
+const chartState = { days: 365 };
+
+function seriesForRange() {
+ const s = state.chart;
+ if (!s.length || chartState.days === Infinity) return s;
+ const cutoff = s[s.length - 1].t - chartState.days * 86400_000;
+ const win = s.filter((p) => p.t >= cutoff);
+ return win.length >= 2 ? win : s.slice(-2);
+}
+
+function chartGeometry(series) {
+ const vals = series.map((p) => p.value);
+ const min = Math.min(...vals, 0);
+ 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 renderChart() {
+ const el = $('dx-chart');
+ const rangeBtns = TIME_RANGES.map(
+ (r) =>
+ `<button type="button" class="cv-range-btn" data-days="${r.days}" aria-pressed="${r.days === chartState.days}">${r.label}</button>`,
+ ).join('');
+
+ const series = seriesForRange();
+ let body;
+ if (state.loading) {
+ body = '<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading chart…</div>';
+ } else if (state.error) {
+ body = '<div class="cv-chart-state">Chart is temporarily unavailable.</div>';
+ } else if (series.length < 2) {
+ body = '<div class="cv-chart-state">No history available for this range.</div>';
+ } else {
+ const g = chartGeometry(series);
+ const color = 'var(--cv-accent)';
+ 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(formatUsd(v))}</text></g>`;
+ }).join('');
+ body = `
+ <div class="cv-chart-area">
+ <svg viewBox="0 0 ${CHART_W} ${CHART_H}" role="img"
+ aria-label="Daily DEX trading volume across all tracked venues">
+ <defs>
+ <linearGradient id="dx-grad" x1="0" x2="0" y1="0" y2="1">
+ <stop offset="0%" stop-color="${color}" stop-opacity="0.24"/>
+ <stop offset="100%" stop-color="${color}" stop-opacity="0.03"/>
+ </linearGradient>
+ </defs>
+ ${yLabels}
+ <path d="${g.area}" fill="url(#dx-grad)"/>
+ <path d="${g.line}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
+ <g id="dx-crosshair" hidden>
+ <line id="dx-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="dx-cross-dot" r="4" fill="${color}" stroke="var(--cv-surface)" stroke-width="2"/>
+ </g>
+ </svg>
+ <div class="cv-chart-tip" id="dx-tip" hidden>
+ <p class="p cv-mono" id="dx-tip-val"></p>
+ <p class="d" id="dx-tip-date"></p>
+ </div>
+ </div>`;
+ }
+
+ el.innerHTML = `
+ <div class="cv-chart-panel">
+ <div class="cv-chart-bar">
+ <div class="left"><span class="title">Daily DEX Volume · all venues</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;
+ renderChart();
+ });
+ });
+
+ wireChartPointer(series);
+}
+
+function wireChartPointer(series) {
+ const svg = $('dx-chart').querySelector('svg');
+ const tip = $('dx-tip');
+ if (!svg || !tip || series.length < 2) return;
+ const g = chartGeometry(series);
+ const cross = svg.querySelector('#dx-crosshair');
+ const crossLine = svg.querySelector('#dx-cross-line');
+ const crossDot = svg.querySelector('#dx-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 = series.length;
+ const i = Math.max(0, Math.min(n - 1, Math.round(((mouseX - PAD.left) / usableW) * (n - 1))));
+ const { t, value } = series[i];
+ const x = PAD.left + (i / (n - 1)) * usableW;
+ const y = PAD.top + usableH - ((value - 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}%`;
+ $('dx-tip-val').textContent = formatUsd(value);
+ $('dx-tip-date').textContent = formatChartTick(t, chartState.days === Infinity ? 365 : 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));
+}
+
+// ── Table ───────────────────────────────────────────────────────────────────
+
+const COLUMNS = [
+ { key: 'rank', label: '#', left: true, hide: 'hide-sm', num: true },
+ { key: 'name', label: 'DEX', left: true },
+ { key: 'chains', label: 'Chains', left: true, hide: 'hide-lg' },
+ { key: 'total24h', label: '24h Vol', num: true },
+ { key: 'total7d', label: '7d Vol', hide: 'hide-md', num: true },
+ { key: 'change_7d', label: 'Δ7d', num: true },
+ { key: 'share_pct', label: 'Share', left: true, hide: 'hide-md' },
+];
+
+function pctCell(v, extraClass = '') {
+ if (v == null) return `<td class="pct dim ${extraClass}">—</td>`;
+ const up = v >= 0;
+ return `<td class="pct ${up ? 'cv-up' : 'cv-down'} ${extraClass}"><span aria-hidden="true">${up ? '▲' : '▼'}</span>${esc(formatPercent(v))}</td>`;
+}
+
+function chainsCell(chains) {
+ if (!chains || !chains.length) return '<td class="left dim hide-lg">—</td>';
+ const shown = chains
+ .slice(0, 3)
+ .map((c) => `<a class="dx-chip" href="/chain/${encodeURIComponent(c)}">${esc(c)}</a>`)
+ .join('');
+ const extra = chains.length > 3 ? `<span class="dx-more">+${chains.length - 3}</span>` : '';
+ return `<td class="left hide-lg"><span class="dx-chips">${shown}${extra}</span></td>`;
+}
+
+function shareCell(share, maxShare) {
+ const pct = Math.max(0, share || 0);
+ const barPct = Math.max(2, (pct / maxShare) * 100);
+ return `<td class="left hide-md dx-share-cell">
+ <span class="dx-share">
+ <span class="dx-share-bar" role="img" aria-label="${pct.toFixed(2)}% of total DEX volume">
+ <span class="dx-share-fill" style="width:${barPct.toFixed(1)}%"></span>
+ </span>
+ <span class="dx-share-num cv-mono">${pct.toFixed(2)}%</span>
+ </span>
+ </td>`;
+}
+
+function nameCell(p) {
+ const logo = p.logo
+ ? `<img src="${esc(p.logo)}" alt="" loading="lazy" width="24" height="24" data-no-dark-filter />`
+ : '<span class="dx-logo-fallback" aria-hidden="true"></span>';
+ const inner = `${logo}<span class="nm">${esc(p.name)}</span>`;
+ if (p.slug) {
+ return `<td class="left name-cell"><a class="dx-name-link inner" href="/protocol/${encodeURIComponent(p.slug)}">${inner}</a></td>`;
+ }
+ return `<td class="left name-cell"><span class="inner">${inner}</span></td>`;
+}
+
+function sortValue(p, key) {
+ if (key === 'name') return (p.name || '').toLowerCase();
+ if (key === 'chains') return p.chains ? p.chains.length : 0;
+ if (key === 'rank') return p.__rank ?? Infinity;
+ return p[key] ?? -Infinity;
+}
+
+function sortedProtocols() {
+ const ranked = [...state.protocols].sort((a, b) => (b.total24h ?? 0) - (a.total24h ?? 0));
+ ranked.forEach((p, i) => (p.__rank = i + 1));
+ const { sortKey, sortDir } = state;
+ const sorted = [...ranked].sort((a, b) => {
+ const va = sortValue(a, sortKey);
+ const vb = sortValue(b, sortKey);
+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;
+ return sortDir === 'asc' ? cmp : -cmp;
+ });
+ return sorted;
+}
+
+function renderTable() {
+ const el = $('dx-table');
+
+ if (state.loading) {
+ el.innerHTML =
+ '<div class="cv-table-wrap" style="padding:0.75rem">' +
+ Array.from(
+ { length: 12 },
+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',
+ ).join('') +
+ '</div>';
+ return;
+ }
+ if (state.error) {
+ el.innerHTML =
+ '<div class="cv-empty">DEX volume data is temporarily unavailable. <button type="button" class="dx-retry">Try again</button> shortly.</div>';
+ el.querySelector('.dx-retry')?.addEventListener('click', () => load());
+ return;
+ }
+ if (!state.protocols.length) {
+ el.innerHTML =
+ '<div class="cv-empty">No DEX volume to show right now. <button type="button" class="dx-retry">Refresh</button> to retry.</div>';
+ el.querySelector('.dx-retry')?.addEventListener('click', () => load());
+ return;
+ }
+
+ // The share bar scales to the leader so the top DEX fills the cell and the
+ // rest read as a fraction of it — a clearer visual than raw share %.
+ const maxShare = Math.max(...state.protocols.map((p) => p.share_pct || 0), 0.0001);
+
+ const head = COLUMNS.map((col) => {
+ const active = col.key === state.sortKey;
+ const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';
+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;
+ }).join('');
+
+ const body = sortedProtocols()
+ .map(
+ (p) => `
+ <tr>
+ <td class="rank hide-sm cv-mono">${p.__rank}</td>
+ ${nameCell(p)}
+ ${chainsCell(p.chains)}
+ <td class="price">${esc(formatUsd(p.total24h))}</td>
+ <td class="price hide-md">${esc(formatUsd(p.total7d))}</td>
+ ${pctCell(p.change_7d)}
+ ${shareCell(p.share_pct, maxShare)}
+ </tr>`,
+ )
+ .join('');
+
+ el.innerHTML = `
+ <div class="cv-table-wrap">
+ <table class="cv-table">
+ <thead><tr>${head}</tr></thead>
+ <tbody>${body}</tbody>
+ </table>
+ </div>`;
+
+ el.querySelectorAll('th[data-key]').forEach((th) => {
+ const activate = () => {
+ const key = th.dataset.key;
+ if (key === state.sortKey) {
+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';
+ } else {
+ state.sortKey = key;
+ state.sortDir = key === 'name' ? 'asc' : 'desc';
+ }
+ renderTable();
+ };
+ th.addEventListener('click', activate);
+ th.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ activate();
+ }
+ });
+ });
+}
+
+// ── Boot ────────────────────────────────────────────────────────────────────
+
+async function load() {
+ state.loading = true;
+ state.error = false;
+ statsSkeleton();
+ renderChart();
+ renderTable();
+ try {
+ const data = await getJson('/api/defi/dex-volumes');
+ state.total24h = data.total24h ?? null;
+ state.total7d = data.total7d ?? null;
+ state.change_7dover7d = data.change_7dover7d ?? null;
+ state.chart = Array.isArray(data.chart) ? data.chart : [];
+ state.protocols = Array.isArray(data.protocols) ? data.protocols : [];
+ state.updated_at = data.updated_at || Date.now();
+ state.loading = false;
+ state.error = false;
+ renderStats();
+ renderChart();
+ renderTable();
+ $('dx-updated').textContent =
+ `Top ${state.protocols.length} DEXs by 24h volume · Data: DeFiLlama · updated ${new Date(state.updated_at).toLocaleTimeString('en-US')}`;
+ } catch {
+ state.loading = false;
+ state.error = true;
+ $('dx-stats').innerHTML = '';
+ renderChart();
+ renderTable();
+ $('dx-updated').textContent = '';
+ }
+}
+
+load();
diff --git a/src/fees.css b/src/fees.css
new file mode 100644
index 000000000..191f1d65d
--- /dev/null
+++ b/src/fees.css
@@ -0,0 +1,149 @@
+/*
+ * /fees — Protocol fees & revenue. Layered after coin-pages.css: reuses the
+ * cv-* token system, stat cards, chart panel, and table. This file only adds the
+ * Fees|Revenue toggle, the explainer line, chain chips, the protocol name link,
+ * and the logo fallback. Both themes inherit from the shared data-theme tokens.
+ */
+
+.fx-stat-grid {
+ display: grid;
+ gap: 1rem;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+}
+
+/* Rows are navigable only via the protocol-name link, not the whole row —
+ reset the shared table's pointer cursor so nothing else signals a click. */
+#fx-table .cv-table tbody tr {
+ cursor: default;
+}
+
+/* ── Fees | Revenue toggle ─────────────────────────────────────────────────── */
+.fx-toggle {
+ display: inline-flex;
+ gap: 0.25rem;
+ padding: 0.25rem;
+ margin: 0.25rem 0 0.75rem;
+ background: var(--cv-surface-2);
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-md);
+}
+.fx-toggle-btn {
+ appearance: none;
+ border: 0;
+ background: transparent;
+ color: var(--cv-text-2);
+ font: inherit;
+ font-size: 0.875rem;
+ font-weight: 600;
+ padding: 0.4375rem 1.125rem;
+ border-radius: calc(var(--cv-radius-md) - 0.25rem);
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ color 0.15s;
+}
+.fx-toggle-btn:hover {
+ color: var(--cv-text);
+}
+.fx-toggle-btn[aria-selected='true'] {
+ background: var(--cv-surface);
+ color: var(--cv-text);
+ box-shadow: 0 1px 2px rgb(0 0 0 / 0.15);
+}
+.fx-toggle-btn:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 30%, transparent);
+}
+
+.fx-explainer {
+ margin: 0 0 1.25rem;
+ font-size: 0.875rem;
+ line-height: 1.5;
+ color: var(--cv-text-3);
+ max-width: 60ch;
+}
+.fx-explainer strong {
+ color: var(--cv-text-2);
+ font-weight: 600;
+}
+
+/* ── Chain chips ───────────────────────────────────────────────────────────── */
+/* Flex lives on this inner wrapper, never the <td>, so the column's responsive
+ `hide-lg` display:none is not overridden at narrow widths. */
+.fx-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.3125rem;
+ align-items: center;
+}
+.fx-chip {
+ display: inline-block;
+ padding: 0.0625rem 0.4375rem;
+ font-size: 0.75rem;
+ line-height: 1.4;
+ color: var(--cv-text-2);
+ background: var(--cv-surface-3);
+ border: 1px solid var(--cv-border);
+ border-radius: 999px;
+ text-decoration: none;
+ white-space: nowrap;
+ transition:
+ border-color 0.15s,
+ color 0.15s,
+ background 0.15s;
+}
+.fx-chip:hover,
+.fx-chip:focus-visible {
+ color: var(--cv-text);
+ border-color: var(--cv-accent);
+ background: color-mix(in srgb, var(--cv-accent) 12%, var(--cv-surface-3));
+ outline: none;
+}
+.fx-more {
+ color: var(--cv-text-3);
+ font-size: 0.75rem;
+ font-variant-numeric: tabular-nums;
+}
+
+/* ── Protocol name link ────────────────────────────────────────────────────── */
+.fx-name-link {
+ text-decoration: none;
+ color: inherit;
+ border-radius: var(--cv-radius-sm);
+}
+.fx-name-link .nm {
+ transition: color 0.15s;
+}
+.fx-name-link:hover .nm,
+.fx-name-link:focus-visible .nm {
+ color: var(--cv-accent);
+ text-decoration: underline;
+}
+.fx-name-link:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 25%, transparent);
+}
+
+.fx-logo-fallback {
+ display: inline-block;
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ background: var(--cv-surface-3);
+ flex-shrink: 0;
+}
+
+/* Retry button in the error / empty states reads as a link, matching cv-empty. */
+.fx-retry {
+ appearance: none;
+ border: 0;
+ background: transparent;
+ color: var(--cv-accent);
+ font: inherit;
+ cursor: pointer;
+ padding: 0;
+ text-decoration: underline;
+}
+.fx-retry:hover {
+ color: var(--cv-accent-hover);
+}
diff --git a/src/fees.js b/src/fees.js
new file mode 100644
index 000000000..f8fd6baee
--- /dev/null
+++ b/src/fees.js
@@ -0,0 +1,453 @@
+// /fees — Protocol fees & revenue. A Fees|Revenue toggle (each refetches and
+// syncs ?type= in the URL), header stat cards (24h/7d/30d of the selected
+// metric), an aggregate SVG area chart with a range toggle + crosshair, and a
+// sortable table of the top protocols. Protocol names deep-link to /protocol/:slug
+// and chain chips to /chain/:name. Data comes from /api/defi/fees (DeFiLlama,
+// keyless), normalized server-side. Mirrors the /defi + /exchange page patterns:
+// stat cards, cv-chart-panel, sortable cv-table, designed loading/empty/error.
+
+import {
+ formatUsd,
+ formatPercent,
+ formatChartTick,
+ 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();
+}
+
+// ── State ───────────────────────────────────────────────────────────────────
+
+const state = {
+ type: 'fees', // 'fees' | 'revenue'
+ total24h: null,
+ total7d: null,
+ total30d: null,
+ change_1d: null,
+ chart: [],
+ protocols: [],
+ updated_at: 0,
+ sortKey: 'total24h',
+ sortDir: 'desc',
+ loading: true,
+ error: false,
+};
+
+const LABELS = {
+ fees: { noun: 'Fees', heading: 'Top Protocols by Fees', metric: 'fees' },
+ revenue: { noun: 'Revenue', heading: 'Top Protocols by Revenue', metric: 'revenue' },
+};
+
+// ── Stat cards ──────────────────────────────────────────────────────────────
+
+const ICONS = {
+ coins: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6"/><path d="M18.09 10.37A6 6 0 1 1 10.34 18"/><path d="M7 6h1v4"/><path d="m16.71 13.88.7.71-2.82 2.82"/></svg>',
+ week: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>',
+ month: '<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="m19 9-5 5-4-4-3 3"/></svg>',
+};
+
+function statCard({ label, value, delta, deltaClass, icon }) {
+ return `
+ <div class="cv-stat-card">
+ <div style="min-width:0">
+ <p class="label">${esc(label)}</p>
+ <p class="value cv-mono">${esc(value)}</p>
+ ${delta ? `<p class="delta ${deltaClass || ''}">${esc(delta)}</p>` : ''}
+ </div>
+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>
+ </div>`;
+}
+
+function renderStats() {
+ const el = $('fx-stats');
+ const noun = LABELS[state.type].noun;
+ const c1 = state.change_1d;
+ const deltaClass = c1 == null ? '' : c1 >= 0 ? 'cv-up' : 'cv-down';
+ const cards = [
+ statCard({
+ label: `24h ${noun}`,
+ value: formatUsd(state.total24h),
+ delta: c1 == null ? '' : `${formatPercent(c1)} vs prior day`,
+ deltaClass,
+ icon: 'coins',
+ }),
+ statCard({ label: `7d ${noun}`, value: formatUsd(state.total7d), icon: 'week' }),
+ statCard({ label: `30d ${noun}`, value: formatUsd(state.total30d), icon: 'month' }),
+ ];
+ el.innerHTML = `<div class="fx-stat-grid">${cards.join('')}</div>`;
+}
+
+function statsSkeleton() {
+ $('fx-stats').innerHTML =
+ '<div class="fx-stat-grid">' +
+ Array.from({ length: 3 }, () => '<div class="cv-skel" style="height:6rem"></div>').join('') +
+ '</div>';
+}
+
+// ── Aggregate chart ─────────────────────────────────────────────────────────
+
+const TIME_RANGES = [
+ { label: '30D', days: 30 },
+ { label: '90D', days: 90 },
+ { label: '1Y', days: 365 },
+ { label: 'All', days: Infinity },
+];
+
+const CHART_W = 800;
+const CHART_H = 300;
+const PAD = { top: 20, right: 80, bottom: 30, left: 10 };
+
+const chartState = { days: 365 };
+
+// Slice the full aggregate series to the active range window.
+function seriesForRange() {
+ const s = state.chart;
+ if (!s.length || chartState.days === Infinity) return s;
+ const cutoff = s[s.length - 1].t - chartState.days * 86400_000;
+ const win = s.filter((p) => p.t >= cutoff);
+ return win.length >= 2 ? win : s.slice(-2);
+}
+
+function chartGeometry(series) {
+ const vals = series.map((p) => p.value);
+ const min = Math.min(...vals, 0);
+ 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 renderChart() {
+ const el = $('fx-chart');
+ const noun = LABELS[state.type].noun;
+ const rangeBtns = TIME_RANGES.map(
+ (r) =>
+ `<button type="button" class="cv-range-btn" data-days="${r.days}" aria-pressed="${r.days === chartState.days}">${r.label}</button>`,
+ ).join('');
+
+ const series = seriesForRange();
+ let body;
+ if (state.loading) {
+ body = '<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading chart…</div>';
+ } else if (state.error) {
+ body = '<div class="cv-chart-state">Chart is temporarily unavailable.</div>';
+ } else if (series.length < 2) {
+ body = '<div class="cv-chart-state">No 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(formatUsd(v))}</text></g>`;
+ }).join('');
+ body = `
+ <div class="cv-chart-area">
+ <svg viewBox="0 0 ${CHART_W} ${CHART_H}" role="img"
+ aria-label="Daily ${esc(noun.toLowerCase())} across all tracked protocols">
+ <defs>
+ <linearGradient id="fx-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(#fx-grad)"/>
+ <path d="${g.line}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
+ <g id="fx-crosshair" hidden>
+ <line id="fx-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="fx-cross-dot" r="4" fill="${color}" stroke="var(--cv-surface)" stroke-width="2"/>
+ </g>
+ </svg>
+ <div class="cv-chart-tip" id="fx-tip" hidden>
+ <p class="p cv-mono" id="fx-tip-val"></p>
+ <p class="d" id="fx-tip-date"></p>
+ </div>
+ </div>`;
+ }
+
+ el.innerHTML = `
+ <div class="cv-chart-panel">
+ <div class="cv-chart-bar">
+ <div class="left"><span class="title">Daily ${esc(noun)} · all protocols</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;
+ renderChart();
+ });
+ });
+
+ wireChartPointer(series);
+}
+
+function wireChartPointer(series) {
+ const svg = $('fx-chart').querySelector('svg');
+ const tip = $('fx-tip');
+ if (!svg || !tip || series.length < 2) return;
+ const g = chartGeometry(series);
+ const cross = svg.querySelector('#fx-crosshair');
+ const crossLine = svg.querySelector('#fx-cross-line');
+ const crossDot = svg.querySelector('#fx-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 = series.length;
+ const i = Math.max(0, Math.min(n - 1, Math.round(((mouseX - PAD.left) / usableW) * (n - 1))));
+ const { t, value } = series[i];
+ const x = PAD.left + (i / (n - 1)) * usableW;
+ const y = PAD.top + usableH - ((value - 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}%`;
+ $('fx-tip-val').textContent = formatUsd(value);
+ $('fx-tip-date').textContent = formatChartTick(t, chartState.days === Infinity ? 365 : 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));
+}
+
+// ── Table ───────────────────────────────────────────────────────────────────
+
+const COLUMNS = [
+ { key: 'rank', label: '#', left: true, hide: 'hide-sm', num: true },
+ { key: 'name', label: 'Protocol', left: true },
+ { key: 'category', label: 'Category', left: true, hide: 'hide-md' },
+ { key: 'chains', label: 'Chains', left: true, hide: 'hide-lg' },
+ { key: 'total24h', label: '24h', num: true },
+ { key: 'total7d', label: '7d', hide: 'hide-md', num: true },
+ { key: 'total30d', label: '30d', hide: 'hide-lg', num: true },
+ { key: 'change_1d', label: '24h Δ', num: true },
+];
+
+function pctCell(v, extraClass = '') {
+ if (v == null) return `<td class="pct dim ${extraClass}">—</td>`;
+ const up = v >= 0;
+ return `<td class="pct ${up ? 'cv-up' : 'cv-down'} ${extraClass}"><span aria-hidden="true">${up ? '▲' : '▼'}</span>${esc(formatPercent(v))}</td>`;
+}
+
+function chainsCell(chains) {
+ if (!chains || !chains.length) return '<td class="left dim hide-lg">—</td>';
+ const shown = chains
+ .slice(0, 3)
+ .map(
+ (c) =>
+ `<a class="fx-chip" href="/chain/${encodeURIComponent(c)}">${esc(c)}</a>`,
+ )
+ .join('');
+ const extra =
+ chains.length > 3 ? `<span class="fx-more">+${chains.length - 3}</span>` : '';
+ return `<td class="left hide-lg"><span class="fx-chips">${shown}${extra}</span></td>`;
+}
+
+function sortValue(p, key) {
+ if (key === 'name') return (p.name || '').toLowerCase();
+ if (key === 'category') return (p.category || '').toLowerCase();
+ if (key === 'chains') return p.chains ? p.chains.length : 0;
+ if (key === 'rank') return p.__rank ?? Infinity;
+ return p[key] ?? -Infinity;
+}
+
+function sortedProtocols() {
+ const ranked = [...state.protocols].sort((a, b) => (b.total24h ?? 0) - (a.total24h ?? 0));
+ ranked.forEach((p, i) => (p.__rank = i + 1));
+ const { sortKey, sortDir } = state;
+ const sorted = [...ranked].sort((a, b) => {
+ const va = sortValue(a, sortKey);
+ const vb = sortValue(b, sortKey);
+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;
+ return sortDir === 'asc' ? cmp : -cmp;
+ });
+ return sorted;
+}
+
+function nameCell(p) {
+ const logo = p.logo
+ ? `<img src="${esc(p.logo)}" alt="" loading="lazy" width="24" height="24" data-no-dark-filter />`
+ : '<span class="fx-logo-fallback" aria-hidden="true"></span>';
+ const inner = `${logo}<span class="nm">${esc(p.name)}</span>`;
+ if (p.slug) {
+ return `<td class="left name-cell"><a class="fx-name-link inner" href="/protocol/${encodeURIComponent(p.slug)}">${inner}</a></td>`;
+ }
+ return `<td class="left name-cell"><span class="inner">${inner}</span></td>`;
+}
+
+function renderTable() {
+ const el = $('fx-table');
+
+ if (state.loading) {
+ el.innerHTML =
+ '<div class="cv-table-wrap" style="padding:0.75rem">' +
+ Array.from(
+ { length: 12 },
+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',
+ ).join('') +
+ '</div>';
+ return;
+ }
+ if (state.error) {
+ el.innerHTML =
+ '<div class="cv-empty">Fee data is temporarily unavailable. <button type="button" class="fx-retry">Try again</button> shortly.</div>';
+ el.querySelector('.fx-retry')?.addEventListener('click', () => load(state.type));
+ return;
+ }
+ if (!state.protocols.length) {
+ el.innerHTML =
+ '<div class="cv-empty">No protocols reporting fees right now. <button type="button" class="fx-retry">Refresh</button> to retry.</div>';
+ el.querySelector('.fx-retry')?.addEventListener('click', () => load(state.type));
+ return;
+ }
+
+ const head = COLUMNS.map((col) => {
+ const active = col.key === state.sortKey;
+ const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';
+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;
+ }).join('');
+
+ const body = sortedProtocols()
+ .map(
+ (p) => `
+ <tr>
+ <td class="rank hide-sm cv-mono">${p.__rank}</td>
+ ${nameCell(p)}
+ <td class="left dim hide-md">${p.category ? esc(p.category) : '—'}</td>
+ ${chainsCell(p.chains)}
+ <td class="price">${esc(formatUsd(p.total24h))}</td>
+ <td class="price hide-md">${esc(formatUsd(p.total7d))}</td>
+ <td class="price hide-lg">${esc(formatUsd(p.total30d))}</td>
+ ${pctCell(p.change_1d)}
+ </tr>`,
+ )
+ .join('');
+
+ el.innerHTML = `
+ <div class="cv-table-wrap">
+ <table class="cv-table">
+ <thead><tr>${head}</tr></thead>
+ <tbody>${body}</tbody>
+ </table>
+ </div>`;
+
+ el.querySelectorAll('th[data-key]').forEach((th) => {
+ const activate = () => {
+ const key = th.dataset.key;
+ if (key === state.sortKey) {
+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';
+ } else {
+ state.sortKey = key;
+ state.sortDir = key === 'name' || key === 'category' ? 'asc' : 'desc';
+ }
+ renderTable();
+ };
+ th.addEventListener('click', activate);
+ th.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ activate();
+ }
+ });
+ });
+}
+
+// ── Toggle + URL sync ───────────────────────────────────────────────────────
+
+function syncToggle() {
+ for (const type of ['fees', 'revenue']) {
+ const btn = $(`fx-tab-${type}`);
+ if (btn) btn.setAttribute('aria-selected', String(type === state.type));
+ }
+ $('fx-table-heading').textContent = LABELS[state.type].heading;
+ document.title = `${LABELS[state.type].noun === 'Fees' ? 'Protocol Fees & Revenue' : 'Protocol Revenue & Fees'} · three.ws`;
+}
+
+function wireToggle() {
+ for (const type of ['fees', 'revenue']) {
+ $(`fx-tab-${type}`)?.addEventListener('click', () => {
+ if (state.type === type) return;
+ const url = new URL(location.href);
+ if (type === 'fees') url.searchParams.delete('type');
+ else url.searchParams.set('type', 'revenue');
+ history.replaceState(null, '', url);
+ load(type);
+ });
+ }
+}
+
+// ── Boot ────────────────────────────────────────────────────────────────────
+
+async function load(type) {
+ state.type = type === 'revenue' ? 'revenue' : 'fees';
+ state.loading = true;
+ state.error = false;
+ syncToggle();
+ statsSkeleton();
+ renderChart();
+ renderTable();
+ try {
+ const data = await getJson(`/api/defi/fees?type=${state.type}`);
+ state.total24h = data.total24h ?? null;
+ state.total7d = data.total7d ?? null;
+ state.total30d = data.total30d ?? null;
+ state.change_1d = data.change_1d ?? null;
+ state.chart = Array.isArray(data.chart) ? data.chart : [];
+ state.protocols = Array.isArray(data.protocols) ? data.protocols : [];
+ state.updated_at = data.updated_at || Date.now();
+ state.loading = false;
+ state.error = false;
+ renderStats();
+ renderChart();
+ renderTable();
+ $('fx-updated').textContent =
+ `Top ${state.protocols.length} protocols by ${LABELS[state.type].metric} · Data: DeFiLlama · updated ${new Date(state.updated_at).toLocaleTimeString('en-US')}`;
+ } catch {
+ state.loading = false;
+ state.error = true;
+ $('fx-stats').innerHTML = '';
+ renderChart();
+ renderTable();
+ $('fx-updated').textContent = '';
+ }
+}
+
+function initialType() {
+ return new URLSearchParams(location.search).get('type') === 'revenue' ? 'revenue' : 'fees';
+}
+
+wireToggle();
+load(initialType());
diff --git a/src/hacks.css b/src/hacks.css
new file mode 100644
index 000000000..de1377055
--- /dev/null
+++ b/src/hacks.css
@@ -0,0 +1,266 @@
+/*
+ * /hacks — DeFi hacks database. Layered after coin-pages.css: reuses the cv-*
+ * token system, cards, and table; this file only adds the stat grid, the
+ * search box, the amount red-scale, and the small incident-table affordances
+ * (chain chips, classification/technique cells, bridge flag, source link).
+ * Both themes inherit from the shared data-theme tokens.
+ */
+
+.hacks-stat-grid {
+ display: grid;
+ gap: 1rem;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+}
+
+/* Incident rows are informational, not navigable. */
+#hacks-table .cv-table tbody tr {
+ cursor: default;
+}
+
+/* ── Search cluster ─────────────────────────────────────────────────────── */
+
+.hacks-filter {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+}
+.hacks-search-label {
+ font-size: 0.75rem;
+ font-weight: 500;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--cv-text-3);
+}
+.hacks-search-wrap {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+}
+.hacks-search-icon {
+ position: absolute;
+ left: 0.625rem;
+ width: 16px;
+ height: 16px;
+ color: var(--cv-text-3);
+ pointer-events: none;
+}
+.hacks-search {
+ appearance: none;
+ background: var(--cv-surface);
+ color: var(--cv-text);
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-md);
+ font: inherit;
+ font-size: 0.875rem;
+ padding: 0.4375rem 0.75rem 0.4375rem 2.125rem;
+ width: min(20rem, 62vw);
+ transition:
+ border-color 0.15s,
+ box-shadow 0.15s;
+}
+.hacks-search::placeholder {
+ color: var(--cv-text-3);
+}
+.hacks-search:hover {
+ border-color: var(--cv-border-hover);
+}
+.hacks-search:focus-visible {
+ outline: none;
+ border-color: var(--cv-accent);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 20%, transparent);
+}
+
+/* ── Table cells ────────────────────────────────────────────────────────── */
+
+.hacks-table {
+ table-layout: auto;
+}
+.hacks-date {
+ white-space: nowrap;
+ font-size: 0.8125rem;
+}
+
+/* Amount: bold red heat scale by magnitude. */
+.hacks-amount {
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ line-height: 1.3;
+}
+.hacks-amount.amt-1 {
+ color: color-mix(in srgb, var(--cv-red) 55%, var(--cv-text-2));
+}
+.hacks-amount.amt-2 {
+ color: color-mix(in srgb, var(--cv-red) 75%, var(--cv-text));
+}
+.hacks-amount.amt-3 {
+ color: var(--cv-red);
+}
+.hacks-amount.amt-4 {
+ color: var(--cv-red);
+ font-weight: 800;
+}
+.hacks-returned {
+ display: inline-block;
+ font-size: 0.6875rem;
+ font-weight: 600;
+ color: var(--cv-green);
+ white-space: nowrap;
+}
+
+.hacks-class {
+ display: inline-block;
+ padding: 0.125rem 0.5rem;
+ border-radius: 999px;
+ font-size: 0.75rem;
+ font-weight: 500;
+ background: var(--cv-surface-3);
+ color: var(--cv-text-2);
+ white-space: nowrap;
+}
+
+.hacks-tech {
+ max-width: 16rem;
+ font-size: 0.8125rem;
+}
+
+/* Chain chips. */
+.hacks-chains {
+ white-space: nowrap;
+}
+.hacks-chip {
+ display: inline-block;
+ padding: 0.0625rem 0.4375rem;
+ margin-right: 0.25rem;
+ border-radius: var(--cv-radius-sm);
+ font-size: 0.75rem;
+ background: var(--cv-surface-3);
+ color: var(--cv-text-2);
+}
+.hacks-more-chip {
+ font-size: 0.75rem;
+ color: var(--cv-text-3);
+ font-variant-numeric: tabular-nums;
+}
+
+/* Flags cell: bridge badge + source link. */
+.hacks-flags {
+ white-space: nowrap;
+}
+.hacks-flag {
+ display: inline-block;
+ padding: 0.0625rem 0.4375rem;
+ border-radius: var(--cv-radius-sm);
+ font-size: 0.6875rem;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+}
+.hacks-flag-bridge {
+ background: var(--cv-red-soft);
+ color: var(--cv-red);
+}
+.hacks-src {
+ display: inline-block;
+ margin-left: 0.375rem;
+ font-size: 0.75rem;
+ color: var(--cv-accent);
+ text-decoration: none;
+ white-space: nowrap;
+ transition: color 0.15s;
+}
+.hacks-src:hover {
+ color: var(--cv-accent-hover);
+ text-decoration: underline;
+}
+.hacks-src:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+ border-radius: var(--cv-radius-sm);
+}
+
+/* ── Load more ──────────────────────────────────────────────────────────── */
+
+.hacks-more {
+ display: flex;
+ justify-content: center;
+ margin: 1.25rem 0 0.5rem;
+}
+.hacks-load-more {
+ appearance: none;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.625rem;
+ background: var(--cv-surface);
+ color: var(--cv-text);
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-md);
+ font: inherit;
+ font-size: 0.875rem;
+ font-weight: 500;
+ padding: 0.5rem 1.125rem;
+ cursor: pointer;
+ transition:
+ border-color 0.15s,
+ background 0.15s,
+ transform 0.05s;
+}
+.hacks-load-more:hover:not(:disabled) {
+ border-color: var(--cv-border-hover);
+ background: var(--cv-surface-3);
+}
+.hacks-load-more:active:not(:disabled) {
+ transform: translateY(1px);
+}
+.hacks-load-more:focus-visible {
+ outline: none;
+ border-color: var(--cv-accent);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 20%, transparent);
+}
+.hacks-load-more:disabled {
+ opacity: 0.6;
+ cursor: default;
+}
+.hacks-remaining {
+ font-size: 0.75rem;
+ color: var(--cv-text-3);
+ font-variant-numeric: tabular-nums;
+}
+
+/* Empty/error inline controls read as links, matching cv-empty's anchors. */
+.hacks-reset,
+.hacks-retry {
+ appearance: none;
+ border: 0;
+ background: transparent;
+ color: var(--cv-accent);
+ font: inherit;
+ cursor: pointer;
+ padding: 0;
+}
+.hacks-reset:hover,
+.hacks-retry:hover {
+ color: var(--cv-accent-hover);
+ text-decoration: underline;
+}
+
+.hacks-attribution {
+ margin-top: 0.5rem;
+ font-size: 0.75rem;
+ line-height: 1.5;
+ color: var(--cv-text-3);
+ max-width: 46rem;
+}
+
+@media (max-width: 640px) {
+ .hacks-search {
+ width: 100%;
+ }
+ .hacks-filter {
+ width: 100%;
+ }
+ .hacks-search-wrap {
+ flex: 1;
+ }
+}
diff --git a/src/hacks.js b/src/hacks.js
new file mode 100644
index 000000000..b683f027d
--- /dev/null
+++ b/src/hacks.js
@@ -0,0 +1,348 @@
+// /hacks — DeFi exploit & hack history. Header stat cards (all-time stolen,
+// last-12mo stolen, incidents 12mo, bridge-hack share), a debounced search
+// synced to the URL, and a paginated table of incidents (newest first) with a
+// "Load more" control. Data comes from /api/defi/hacks (DeFiLlama's keyless
+// hacks database), normalized server-side. Mirrors the /defi list-page
+// pattern: stat cards, cv-table, designed loading / empty / error states.
+
+import { formatUsd, formatDateShort, escapeHtml as esc } from './shared/coin-format.js';
+
+const $ = (id) => document.getElementById(id);
+const PAGE_SIZE = 50;
+
+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();
+}
+
+// ── State ───────────────────────────────────────────────────────────────────
+
+const state = {
+ stats: null,
+ rows: [], // accumulated incidents across loaded pages
+ count: 0, // total matching the active search
+ updatedAt: 0,
+ search: '',
+ offset: 0,
+ loading: true, // first page in flight
+ loadingMore: false,
+ error: false,
+};
+
+// ── Stat cards ────────────────────────────────────────────────────────────
+
+const ICONS = {
+ skull: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="12" r="1"/><circle cx="15" cy="12" r="1"/><path d="M8 20v2h8v-2"/><path d="m12.5 17-.5-1-.5 1h1z"/><path d="M16 20a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20"/></svg>',
+ calendar: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>',
+ list: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>',
+ bridge: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12h20"/><path d="M4 12v6"/><path d="M20 12v6"/><path d="M2 12a10 10 0 0 1 20 0"/><path d="M9 12v3"/><path d="M15 12v3"/></svg>',
+};
+
+function statCard({ label, value, delta, icon }) {
+ return `
+ <div class="cv-stat-card">
+ <div style="min-width:0">
+ <p class="label">${esc(label)}</p>
+ <p class="value cv-mono">${esc(value)}</p>
+ ${delta ? `<p class="delta">${esc(delta)}</p>` : ''}
+ </div>
+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>
+ </div>`;
+}
+
+function renderStats() {
+ const el = $('hacks-stats');
+ const s = state.stats;
+ if (!s) {
+ el.innerHTML = '';
+ return;
+ }
+ const pct = Number.isFinite(s.bridge_hack_share_pct) ? s.bridge_hack_share_pct : 0;
+ el.innerHTML =
+ '<div class="hacks-stat-grid">' +
+ [
+ statCard({ label: 'Total Stolen · All Time', value: formatUsd(s.total_stolen_all_time), icon: 'skull' }),
+ statCard({ label: 'Stolen · Last 12 Months', value: formatUsd(s.total_stolen_12mo), icon: 'calendar' }),
+ statCard({
+ label: 'Incidents · Last 12 Months',
+ value: (s.incidents_12mo || 0).toLocaleString('en-US'),
+ icon: 'list',
+ }),
+ statCard({
+ label: 'Bridge-Hack Share',
+ value: `${pct.toFixed(1)}%`,
+ delta: 'of all-time losses',
+ icon: 'bridge',
+ }),
+ ].join('') +
+ '</div>';
+}
+
+function statsSkeleton() {
+ $('hacks-stats').innerHTML =
+ '<div class="hacks-stat-grid">' +
+ Array.from({ length: 4 }, () => '<div class="cv-skel" style="height:6rem"></div>').join('') +
+ '</div>';
+}
+
+// ── Table ─────────────────────────────────────────────────────────────────
+
+const COLUMNS = [
+ { label: 'Date', cls: 'left' },
+ { label: 'Name', cls: 'left' },
+ { label: 'Amount', cls: 'num' },
+ { label: 'Classification', cls: 'left hide-md' },
+ { label: 'Technique', cls: 'left hide-lg' },
+ { label: 'Chains', cls: 'left hide-lg' },
+ { label: 'Target', cls: 'left hide-md' },
+ { label: '', cls: 'num' }, // bridge flag + source
+];
+
+// Bold red scale by magnitude — the larger the theft, the hotter the amount.
+function amountClass(usd) {
+ if (usd == null) return '';
+ if (usd >= 1e8) return 'amt-4';
+ if (usd >= 1e7) return 'amt-3';
+ if (usd >= 1e6) return 'amt-2';
+ return 'amt-1';
+}
+
+function truncate(s, n) {
+ if (!s) return '';
+ return s.length > n ? `${s.slice(0, n - 1)}…` : s;
+}
+
+function chainsCell(chains) {
+ if (!chains || !chains.length) return '<td class="left dim hide-lg">—</td>';
+ const shown = chains.slice(0, 2).map((c) => `<span class="hacks-chip">${esc(c)}</span>`).join('');
+ const extra =
+ chains.length > 2
+ ? `<span class="hacks-more-chip" title="${esc(chains.slice(2).join(', '))}">+${chains.length - 2}</span>`
+ : '';
+ return `<td class="left hide-lg hacks-chains">${shown}${extra}</td>`;
+}
+
+function rowHtml(h) {
+ const dateIso = new Date(h.date).toISOString();
+ const amtCls = amountClass(h.amount_usd);
+ const returned =
+ h.returned_usd != null
+ ? `<span class="hacks-returned" title="Funds returned / recovered">↩ ${esc(formatUsd(h.returned_usd))}</span>`
+ : '';
+ const flags = [];
+ if (h.bridge) flags.push('<span class="hacks-flag hacks-flag-bridge" title="Cross-chain bridge exploit">Bridge</span>');
+ if (h.source) {
+ flags.push(
+ `<a class="hacks-src" href="${esc(h.source)}" target="_blank" rel="noopener noreferrer" aria-label="Read source report for ${esc(h.name)}">source <span aria-hidden="true">↗</span></a>`,
+ );
+ }
+ return `
+ <tr>
+ <td class="left dim cv-mono hacks-date">${esc(formatDateShort(dateIso))}</td>
+ <td class="left name-cell"><span class="nm">${esc(h.name)}</span></td>
+ <td class="price hacks-amount ${amtCls}">${esc(formatUsd(h.amount_usd))}${returned ? `<br>${returned}` : ''}</td>
+ <td class="left hide-md">${h.classification ? `<span class="hacks-class">${esc(h.classification)}</span>` : '<span class="dim">—</span>'}</td>
+ <td class="left dim hide-lg hacks-tech" title="${esc(h.technique || '')}">${h.technique ? esc(truncate(h.technique, 40)) : '—'}</td>
+ ${chainsCell(h.chains)}
+ <td class="left dim hide-md">${h.target_type ? esc(h.target_type) : '—'}</td>
+ <td class="num hacks-flags">${flags.join('') || '<span class="dim">—</span>'}</td>
+ </tr>`;
+}
+
+function tableSkeleton() {
+ return (
+ '<div class="cv-table-wrap" style="padding:0.75rem">' +
+ Array.from(
+ { length: 12 },
+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',
+ ).join('') +
+ '</div>'
+ );
+}
+
+function renderTable() {
+ const el = $('hacks-table');
+
+ if (state.loading) {
+ el.innerHTML = tableSkeleton();
+ renderMore();
+ return;
+ }
+ if (state.error) {
+ el.innerHTML =
+ '<div class="cv-empty">DeFi hacks data is temporarily unavailable. <button type="button" class="hacks-retry">Try again</button></div>';
+ el.querySelector('.hacks-retry')?.addEventListener('click', () => load());
+ renderMore();
+ return;
+ }
+ if (!state.rows.length) {
+ el.innerHTML = state.search
+ ? `<div class="cv-empty">No incidents match “${esc(state.search)}”. <button type="button" class="hacks-reset">Clear search</button></div>`
+ : '<div class="cv-empty">No incidents on record.</div>';
+ el.querySelector('.hacks-reset')?.addEventListener('click', () => {
+ const input = $('hacks-search');
+ if (input) input.value = '';
+ applySearch('');
+ });
+ renderMore();
+ return;
+ }
+
+ const head = COLUMNS.map(
+ (c) => `<th scope="col" class="${c.cls}">${esc(c.label)}</th>`,
+ ).join('');
+ const body = state.rows.map(rowHtml).join('');
+
+ el.innerHTML = `
+ <div class="cv-table-wrap">
+ <table class="cv-table hacks-table">
+ <thead><tr>${head}</tr></thead>
+ <tbody>${body}</tbody>
+ </table>
+ </div>`;
+ renderMore();
+}
+
+function renderMore() {
+ const el = $('hacks-more');
+ if (!el) return;
+ const remaining = state.count - state.rows.length;
+ if (state.loading || state.error || remaining <= 0) {
+ el.innerHTML = '';
+ return;
+ }
+ el.innerHTML = `<button type="button" class="hacks-load-more"${state.loadingMore ? ' disabled' : ''}>
+ ${state.loadingMore ? 'Loading…' : `Load ${Math.min(PAGE_SIZE, remaining)} more`}
+ <span class="hacks-remaining">${remaining.toLocaleString('en-US')} more</span>
+ </button>`;
+ el.querySelector('.hacks-load-more')?.addEventListener('click', loadMore);
+}
+
+function renderUpdated() {
+ const el = $('hacks-updated');
+ if (!el) return;
+ if (state.loading || state.error) {
+ el.textContent = '';
+ return;
+ }
+ const scope = state.search
+ ? `${state.count.toLocaleString('en-US')} incidents match “${state.search}”`
+ : `${state.count.toLocaleString('en-US')} incidents on record`;
+ el.textContent = `${scope} · Data: DeFiLlama · updated ${new Date(state.updatedAt || Date.now()).toLocaleTimeString('en-US')}`;
+}
+
+// ── Data loading ────────────────────────────────────────────────────────────
+
+function apiUrl(offset) {
+ const p = new URLSearchParams();
+ if (state.search) p.set('search', state.search);
+ p.set('limit', String(PAGE_SIZE));
+ p.set('offset', String(offset));
+ return `/api/defi/hacks?${p.toString()}`;
+}
+
+async function load() {
+ state.loading = true;
+ state.error = false;
+ state.offset = 0;
+ statsSkeleton();
+ renderTable();
+ renderUpdated();
+ try {
+ const data = await getJson(apiUrl(0));
+ state.stats = data.stats || null;
+ state.rows = Array.isArray(data.hacks) ? data.hacks : [];
+ state.count = Number.isFinite(data.count) ? data.count : state.rows.length;
+ state.updatedAt = data.updated_at || Date.now();
+ state.offset = state.rows.length;
+ state.loading = false;
+ state.error = false;
+ renderStats();
+ renderTable();
+ renderUpdated();
+ } catch {
+ state.loading = false;
+ state.error = true;
+ state.stats = null;
+ $('hacks-stats').innerHTML = '';
+ renderTable();
+ renderUpdated();
+ }
+}
+
+async function loadMore() {
+ if (state.loadingMore || state.rows.length >= state.count) return;
+ state.loadingMore = true;
+ renderMore();
+ try {
+ const data = await getJson(apiUrl(state.offset));
+ const more = Array.isArray(data.hacks) ? data.hacks : [];
+ state.rows = state.rows.concat(more);
+ state.offset += more.length;
+ state.count = Number.isFinite(data.count) ? data.count : state.count;
+ state.loadingMore = false;
+ renderTable();
+ renderUpdated();
+ } catch {
+ state.loadingMore = false;
+ // Keep what we have; surface a retryable affordance in the more slot.
+ const el = $('hacks-more');
+ if (el) {
+ el.innerHTML =
+ '<button type="button" class="hacks-load-more">Couldn’t load more — retry</button>';
+ el.querySelector('.hacks-load-more')?.addEventListener('click', loadMore);
+ }
+ }
+}
+
+// ── Search (debounced + URL-synced) ──────────────────────────────────────────
+
+let searchTimer = 0;
+
+function syncUrl() {
+ const url = new URL(window.location.href);
+ if (state.search) url.searchParams.set('search', state.search);
+ else url.searchParams.delete('search');
+ window.history.replaceState(null, '', url);
+}
+
+function applySearch(value) {
+ const next = value.trim();
+ if (next === state.search) return;
+ state.search = next;
+ syncUrl();
+ load();
+}
+
+function initSearch() {
+ const input = $('hacks-search');
+ if (!input) return;
+ // Hydrate from the URL so a shared /hacks?search=… link lands pre-filtered.
+ const initial = new URL(window.location.href).searchParams.get('search') || '';
+ if (initial) {
+ input.value = initial;
+ state.search = initial.trim();
+ }
+ input.addEventListener('input', () => {
+ clearTimeout(searchTimer);
+ searchTimer = window.setTimeout(() => applySearch(input.value), 300);
+ });
+ // Enter applies immediately (skip the debounce).
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ clearTimeout(searchTimer);
+ applySearch(input.value);
+ }
+ });
+}
+
+// ── Boot ──────────────────────────────────────────────────────────────────
+
+initSearch();
+load();
diff --git a/src/markets-page.js b/src/markets-page.js
index e6400ee3f..9505e9619 100644
--- a/src/markets-page.js
+++ b/src/markets-page.js
@@ -122,6 +122,12 @@ const G = {
'<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>',
+ fees: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 10h18M8 15h3"/></svg>',
+ volume:
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20V10M9 20V4M14 20v-8M19 20V8"/></svg>',
+ shield:
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9.5 12 2 2 3.5-4"/></svg>',
+ fire: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2c1 3 4 5 4 9a4 4 0 0 1-8 0c0-1 .5-2 1-3-2 1-4 3-4 6a7 7 0 0 0 14 0c0-5-4-8-7-12z"/></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>',
};
@@ -144,6 +150,10 @@ const SUITE = [
{ 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: '/fees', glyph: 'fees', title: 'Protocol Fees', desc: 'Fees paid and revenue kept across DeFi, ranked and charted.' },
+ { href: '/dex-volumes', glyph: 'volume', title: 'DEX Volumes', desc: 'The decentralized-exchange volume leaderboard, with share.' },
+ { href: '/hacks', glyph: 'shield', title: 'Hacks Database', desc: 'Every major DeFi exploit — amount, technique, chain, source.' },
+ { href: '/markets/trending', glyph: 'fire', title: 'Trending', desc: 'The most-searched coins, categories, and NFTs right now.' },
{ href: '/coin-intel', glyph: 'radar', title: 'Coin Intelligence', desc: 'Every launch classified — organic vs bundle, with a learning score.' },
];
diff --git a/src/markets-trending.css b/src/markets-trending.css
new file mode 100644
index 000000000..b26d9f50b
--- /dev/null
+++ b/src/markets-trending.css
@@ -0,0 +1,298 @@
+/* /markets/trending — Trending crypto surface. Layers on top of coin-pages.css,
+ reusing its design tokens (--cv-*), the .cv-container chrome, .cv-up/.cv-down
+ colors, .cv-mono, .cv-skel shimmer, and .cv-empty. Only the trending-specific
+ layout lives here. Responsive at 320 / 768 / 1440. */
+
+/* ── Masthead ─────────────────────────────────────────────────────────────── */
+.trd-head {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: 1rem;
+ margin: 0.5rem 0 1.75rem;
+}
+.trd-sub {
+ margin: 0.35rem 0 0;
+ color: var(--cv-text-2);
+ font-size: 0.95rem;
+}
+.trd-head-meta {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+}
+.trd-updated {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ font-size: 0.8rem;
+ color: var(--cv-text-3);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+.trd-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--cv-green);
+ box-shadow: 0 0 0 0 var(--cv-green-soft);
+ animation: trd-pulse 2.4s ease-out infinite;
+}
+@keyframes trd-pulse {
+ 0% { box-shadow: 0 0 0 0 var(--cv-green-soft); }
+ 70% { box-shadow: 0 0 0 6px transparent; }
+ 100% { box-shadow: 0 0 0 0 transparent; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .trd-live-dot { animation: none; }
+}
+
+/* ── Sections ─────────────────────────────────────────────────────────────── */
+.trd-section {
+ margin-top: 2rem;
+}
+.trd-section-h {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+.trd-section-ico {
+ font-size: 1rem;
+ line-height: 1;
+}
+
+/* ── Trending coins (ranked rows) ─────────────────────────────────────────── */
+.trd-coins {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+.trd-coins-head,
+.trd-coin {
+ display: grid;
+ grid-template-columns: 3rem 28px minmax(0, 1.6fr) minmax(0, 1fr) minmax(0, 0.9fr) minmax(0, 1fr) minmax(0, 1fr) 120px;
+ align-items: center;
+ gap: 0.75rem;
+}
+.trd-coins-head {
+ padding: 0 0.75rem 0.5rem;
+ font-size: 0.7rem;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--cv-text-3);
+}
+.trd-coins-head span:nth-child(n + 4) { text-align: right; }
+.trd-coins-head span:last-child { text-align: right; }
+
+.trd-coin {
+ padding: 0.6rem 0.75rem;
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-md);
+ background: var(--cv-surface);
+ text-decoration: none;
+ color: var(--cv-text);
+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.15s ease;
+}
+.trd-coin:hover {
+ border-color: var(--cv-border-hover);
+ background: var(--cv-surface-2);
+ transform: translateY(-1px);
+}
+.trd-coin:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+}
+.trd-rank {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.2rem;
+ font-variant-numeric: tabular-nums;
+ color: var(--cv-text-2);
+ font-size: 0.85rem;
+ font-weight: 600;
+}
+.trd-flame { font-size: 0.9rem; }
+.trd-coin-img {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ object-fit: cover;
+ background: var(--cv-surface-3);
+}
+.trd-coin-id {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+.trd-coin-name {
+ font-weight: 600;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.trd-coin-sym {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ font-size: 0.78rem;
+ color: var(--cv-text-3);
+ text-transform: uppercase;
+ letter-spacing: 0.02em;
+}
+.trd-mcap-rank {
+ padding: 0.05rem 0.35rem;
+ border-radius: var(--cv-radius-sm);
+ background: var(--cv-surface-3);
+ color: var(--cv-text-2);
+ font-size: 0.68rem;
+ letter-spacing: 0;
+}
+.trd-coin-price,
+.trd-coin-chg,
+.trd-coin-mcap,
+.trd-coin-vol {
+ text-align: right;
+ font-size: 0.88rem;
+ white-space: nowrap;
+}
+.trd-coin-mcap,
+.trd-coin-vol { color: var(--cv-text-2); }
+.trd-pct { font-weight: 600; }
+.trd-spark {
+ justify-self: end;
+ width: 120px;
+ height: 40px;
+ object-fit: contain;
+ opacity: 0.9;
+}
+.trd-spark-empty { display: block; width: 120px; height: 40px; }
+
+/* ── Card grids (sectors + NFTs) ──────────────────────────────────────────── */
+.trd-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
+ gap: 0.75rem;
+}
+.trd-card {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ padding: 1rem;
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-lg);
+ background: var(--cv-surface);
+ color: var(--cv-text);
+ text-decoration: none;
+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.15s ease, box-shadow 0.15s ease;
+}
+.trd-card-link:hover {
+ border-color: var(--cv-border-hover);
+ background: var(--cv-surface-2);
+ transform: translateY(-2px);
+ box-shadow: var(--cv-shadow-card-hover);
+}
+.trd-card-link:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+}
+.trd-card-name {
+ font-weight: 600;
+ font-size: 0.95rem;
+ line-height: 1.3;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.trd-card-stats {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem 1.25rem;
+ margin: 0;
+}
+.trd-card-stats > div {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+}
+.trd-card-stats dt {
+ font-size: 0.68rem;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--cv-text-3);
+}
+.trd-card-stats dd {
+ margin: 0;
+ font-size: 0.9rem;
+ font-weight: 600;
+}
+
+/* NFT card head (thumb + name) */
+.trd-nft-head {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ min-width: 0;
+}
+.trd-nft-img {
+ width: 40px;
+ height: 40px;
+ flex: none;
+ border-radius: var(--cv-radius);
+ object-fit: cover;
+ background: var(--cv-surface-3);
+}
+.trd-usd {
+ display: block;
+ font-size: 0.72rem;
+ font-weight: 400;
+ color: var(--cv-text-3);
+}
+
+/* ── States ───────────────────────────────────────────────────────────────── */
+.trd-empty,
+.trd-error {
+ margin: 0;
+}
+.trd-skel-coins {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+.trd-skel-row {
+ height: 54px;
+ border-radius: var(--cv-radius-md);
+}
+.trd-skel-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
+ gap: 0.75rem;
+}
+.trd-skel-card {
+ height: 128px;
+ border-radius: var(--cv-radius-lg);
+}
+
+/* ── Responsive ───────────────────────────────────────────────────────────── */
+@media (max-width: 900px) {
+ .trd-coins-head { display: none; }
+ .trd-coin {
+ grid-template-columns: 2.4rem 28px minmax(0, 1fr) auto;
+ grid-template-areas:
+ 'rank img id price'
+ 'rank img chg mcap';
+ row-gap: 0.25rem;
+ }
+ .trd-rank { grid-area: rank; }
+ .trd-coin-img { grid-area: img; }
+ .trd-coin-id { grid-area: id; }
+ .trd-coin-price { grid-area: price; }
+ .trd-coin-chg { grid-area: chg; text-align: left; }
+ .trd-coin-mcap { grid-area: mcap; }
+ .trd-coin-vol,
+ .trd-spark { display: none; }
+}
+@media (max-width: 480px) {
+ .trd-head { align-items: flex-start; }
+ .trd-cards,
+ .trd-skel-cards { grid-template-columns: 1fr; }
+}
diff --git a/src/markets-trending.js b/src/markets-trending.js
new file mode 100644
index 000000000..0bceb0de3
--- /dev/null
+++ b/src/markets-trending.js
@@ -0,0 +1,235 @@
+// /markets/trending — "Trending": the most-searched crypto on CoinGecko over
+// the last 24h, sibling to /markets/news. One serverless read (/api/coin/trending
+// → CoinGecko /search/trending) hydrates three sections: trending coins (ranked
+// with price, market cap, 24h volume, change, sparkline), trending sectors, and
+// trending NFT collections. Coins link into /coin/:id, sectors into /category/:slug
+// (only when CoinGecko gives a slug); NFTs are display-only — the platform has no
+// NFT pages, so no dead links are ever rendered.
+//
+// The whole surface is one endpoint, so a fault shows a single retry panel; a
+// success auto-refreshes every 120s (matching the CDN window) and stamps a real
+// "updated Xs ago" timestamp — no fake spinner, no fake progress.
+
+import { formatUsd, formatPrice, formatPercent, escapeHtml as esc } from './shared/coin-format.js';
+
+const $ = (id) => document.getElementById(id);
+const REFRESH_MS = 120_000;
+
+const state = {
+ loading: false,
+ lastLoadedAt: 0,
+ timer: null,
+ tick: 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();
+}
+
+// ── Formatting helpers ───────────────────────────────────────────────────────
+
+function pct(n) {
+ if (n == null || !Number.isFinite(n)) return '<span class="trd-pct">—</span>';
+ const dir = n >= 0 ? 'cv-up' : 'cv-down';
+ return `<span class="trd-pct ${dir} cv-mono">${esc(formatPercent(n))}</span>`;
+}
+
+function floorNative(n, sym) {
+ if (n == null || !Number.isFinite(n)) return '—';
+ const val = n >= 1 ? n.toLocaleString('en-US', { maximumFractionDigits: 4 }) : n.toPrecision(3);
+ return `${val}${sym ? ` ${esc(sym)}` : ''}`;
+}
+
+// ── Coins ────────────────────────────────────────────────────────────────────
+
+function coinRow(c, i) {
+ const flame = i === 0 ? '<span class="trd-flame" aria-hidden="true">🔥</span>' : '';
+ const href = `/coin/${encodeURIComponent(c.id)}`;
+ const spark = c.sparkline_url
+ ? `<img class="trd-spark" src="${esc(c.sparkline_url)}" loading="lazy" alt="" width="120" height="40" onerror="this.remove()" />`
+ : '<span class="trd-spark trd-spark-empty" aria-hidden="true"></span>';
+ const img = c.image
+ ? `<img class="trd-coin-img" src="${esc(c.image)}" loading="lazy" alt="" width="28" height="28" onerror="this.style.visibility='hidden'" />`
+ : '<span class="trd-coin-img" aria-hidden="true"></span>';
+ return `
+ <a class="trd-coin" href="${esc(href)}">
+ <span class="trd-rank" aria-label="Trending rank ${i + 1}">${flame}<span class="trd-rank-n">#${i + 1}</span></span>
+ ${img}
+ <span class="trd-coin-id">
+ <span class="trd-coin-name">${esc(c.name)}</span>
+ <span class="trd-coin-sym">${esc(c.symbol || '')}${c.rank != null ? `<span class="trd-mcap-rank" title="Market-cap rank">#${c.rank}</span>` : ''}</span>
+ </span>
+ <span class="trd-coin-price cv-mono">${esc(formatPrice(c.price_usd))}</span>
+ <span class="trd-coin-chg">${pct(c.change_24h_pct)}</span>
+ <span class="trd-coin-mcap cv-mono" title="Market cap">${esc(formatUsd(c.market_cap_usd))}</span>
+ <span class="trd-coin-vol cv-mono" title="24h volume">${esc(formatUsd(c.volume_24h_usd))}</span>
+ ${spark}
+ </a>`;
+}
+
+function renderCoins(coins) {
+ const el = $('trd-coins');
+ if (!coins.length) {
+ el.innerHTML = emptyPanel('No trending coins', 'CoinGecko has no coins on its 24-hour trending list right now. Check back shortly.');
+ return;
+ }
+ el.innerHTML = `
+ <div class="trd-coins-head" aria-hidden="true">
+ <span>Rank</span><span></span><span>Asset</span><span>Price</span>
+ <span>24h</span><span>Market cap</span><span>Volume</span><span>Last 7d</span>
+ </div>
+ ${coins.map(coinRow).join('')}`;
+}
+
+// ── Categories (sectors) ─────────────────────────────────────────────────────
+
+function categoryCard(c) {
+ const inner = `
+ <span class="trd-card-name">${esc(c.name)}</span>
+ <dl class="trd-card-stats">
+ <div><dt>Coins</dt><dd>${c.coins_count != null ? c.coins_count.toLocaleString('en-US') : '—'}</dd></div>
+ <div><dt>1h mcap</dt><dd>${pct(c.mcap_change_1h_pct)}</dd></div>
+ <div><dt>Market cap</dt><dd class="cv-mono">${esc(formatUsd(c.market_cap_usd))}</dd></div>
+ </dl>`;
+ // Only link when CoinGecko provides a slug — /category/:slug exists, but an
+ // unslugged sector would produce a dead link, so it stays unlinked.
+ return c.slug
+ ? `<a class="trd-card trd-card-link" href="/category/${encodeURIComponent(c.slug)}">${inner}</a>`
+ : `<div class="trd-card">${inner}</div>`;
+}
+
+function renderCategories(cats) {
+ const el = $('trd-cats');
+ if (!cats.length) {
+ el.innerHTML = emptyPanel('No trending sectors', 'No crypto sectors are trending on CoinGecko right now.');
+ return;
+ }
+ el.innerHTML = cats.map(categoryCard).join('');
+}
+
+// ── NFTs (display-only) ──────────────────────────────────────────────────────
+
+function nftCard(n) {
+ const thumb = n.thumb
+ ? `<img class="trd-nft-img" src="${esc(n.thumb)}" loading="lazy" alt="" width="40" height="40" onerror="this.style.visibility='hidden'" />`
+ : '<span class="trd-nft-img" aria-hidden="true"></span>';
+ return `
+ <div class="trd-card trd-nft">
+ <span class="trd-nft-head">
+ ${thumb}
+ <span class="trd-card-name">${esc(n.name)}${n.symbol ? ` <span class="trd-coin-sym">${esc(n.symbol)}</span>` : ''}</span>
+ </span>
+ <dl class="trd-card-stats">
+ <div><dt>Floor</dt><dd class="cv-mono">${esc(floorNative(n.floor_price_native, n.native_currency_symbol))}${n.floor_price_usd != null ? `<span class="trd-usd">${esc(formatUsd(n.floor_price_usd))}</span>` : ''}</dd></div>
+ <div><dt>24h floor</dt><dd>${pct(n.floor_change_24h_pct)}</dd></div>
+ <div><dt>24h vol</dt><dd class="cv-mono">${esc(formatUsd(n.volume_24h_usd))}</dd></div>
+ </dl>
+ </div>`;
+}
+
+function renderNfts(nfts) {
+ const el = $('trd-nfts');
+ if (!nfts.length) {
+ el.innerHTML = emptyPanel('No trending NFTs', 'CoinGecko has no NFT collections on its trending list right now.');
+ return;
+ }
+ el.innerHTML = nfts.map(nftCard).join('');
+}
+
+// ── States ───────────────────────────────────────────────────────────────────
+
+function emptyPanel(title, body) {
+ return `<div class="cv-empty trd-empty"><p><strong>${esc(title)}</strong></p><p>${esc(body)}</p></div>`;
+}
+
+function skeleton(kind) {
+ if (kind === 'coins') {
+ return `<div class="trd-skel-coins" aria-hidden="true">${'<div class="cv-skel trd-skel-row"></div>'.repeat(7)}</div>`;
+ }
+ return `<div class="trd-skel-cards" aria-hidden="true">${'<div class="cv-skel trd-skel-card"></div>'.repeat(kind === 'cats' ? 6 : 4)}</div>`;
+}
+
+function showSkeletons() {
+ $('trd-coins').innerHTML = skeleton('coins');
+ $('trd-cats').innerHTML = skeleton('cats');
+ $('trd-nfts').innerHTML = skeleton('nfts');
+}
+
+function showError(status) {
+ const msg =
+ status === 429
+ ? 'You’re moving fast — give it a few seconds and retry.'
+ : 'CoinGecko’s trending feed didn’t respond. It usually recovers on its own.';
+ $('trd-coins').innerHTML = `
+ <div class="cv-empty trd-error">
+ <p><strong>Couldn’t load trending data.</strong></p>
+ <p>${esc(msg)}</p>
+ <p><button class="arc-btn" type="button" id="trd-retry">Retry</button></p>
+ </div>`;
+ $('trd-cats').innerHTML = '';
+ $('trd-nfts').innerHTML = '';
+ $('trd-retry')?.addEventListener('click', () => load());
+}
+
+// ── Updated timestamp ────────────────────────────────────────────────────────
+
+function stampUpdated() {
+ const el = $('trd-updated');
+ if (!el || !state.lastLoadedAt) return;
+ const s = Math.max(0, Math.floor((Date.now() - state.lastLoadedAt) / 1000));
+ const rel = s < 5 ? 'just now' : s < 60 ? `${s}s ago` : `${Math.floor(s / 60)}m ago`;
+ el.innerHTML = `<span class="trd-live-dot" aria-hidden="true"></span>Updated ${rel}`;
+}
+
+// ── Load / refresh ───────────────────────────────────────────────────────────
+
+async function load() {
+ if (state.loading) return;
+ state.loading = true;
+ // Only paint skeletons on the first load — a background refresh keeps the
+ // current data on screen so the page never flickers to empty every 2 min.
+ if (!state.lastLoadedAt) showSkeletons();
+ try {
+ const data = await getJson('/api/coin/trending');
+ renderCoins(Array.isArray(data.coins) ? data.coins : []);
+ renderCategories(Array.isArray(data.categories) ? data.categories : []);
+ renderNfts(Array.isArray(data.nfts) ? data.nfts : []);
+ state.lastLoadedAt = Date.now();
+ stampUpdated();
+ } catch (err) {
+ // A background refresh that fails leaves the last good render in place;
+ // only a cold first load shows the retry panel.
+ if (!state.lastLoadedAt) showError(err.status);
+ } finally {
+ state.loading = false;
+ }
+}
+
+function init() {
+ load();
+ // Auto-refresh on the CDN window; pause while the tab is hidden so a
+ // backgrounded page doesn't keep hitting the endpoint.
+ const start = () => {
+ if (!state.timer) state.timer = setInterval(load, REFRESH_MS);
+ if (!state.tick) state.tick = setInterval(stampUpdated, 1000);
+ };
+ const stop = () => {
+ clearInterval(state.timer);
+ clearInterval(state.tick);
+ state.timer = null;
+ state.tick = null;
+ };
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) stop();
+ else { load(); start(); }
+ });
+ start();
+}
+
+init();
diff --git a/src/protocol-page.css b/src/protocol-page.css
new file mode 100644
index 000000000..5a09c5c8b
--- /dev/null
+++ b/src/protocol-page.css
@@ -0,0 +1,319 @@
+/*
+ * /protocol/:slug — feature styles layered on top of /src/coin-pages.css.
+ * Reuses the shared cv-* container, card, chart, table, pill, prose, and state
+ * system; adds only the hero, audit badge, meta chips, chain share-bars,
+ * fees grid, funding-rounds table, and hallmark markers unique to this page.
+ */
+
+/* ── Hero ──────────────────────────────────────────────────────────────────── */
+
+.pr-hero {
+ display: flex;
+ gap: 1.25rem;
+ align-items: flex-start;
+ margin: 0.5rem 0 2rem;
+}
+.pr-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;
+}
+.pr-logo-fallback {
+ background: var(--cv-surface-2);
+}
+.pr-hero-body {
+ flex: 1;
+ min-width: 0;
+}
+.pr-title-row {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 0.625rem 0.75rem;
+}
+.pr-title {
+ margin: 0;
+ font-size: clamp(1.5rem, 4vw, 2rem);
+ line-height: 1.1;
+}
+.pr-symbol {
+ 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;
+}
+
+/* Audit badge — links to the audit report(s) when available. */
+.pr-audit {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3125rem;
+ padding: 0.25rem 0.625rem;
+ border-radius: 999px;
+ font-size: 0.75rem;
+ font-weight: 600;
+ line-height: 1;
+ text-decoration: none;
+ color: var(--cv-green);
+ background: var(--cv-green-soft);
+ border: 1px solid color-mix(in srgb, var(--cv-green) 30%, transparent);
+ transition:
+ border-color 0.15s,
+ background 0.15s;
+}
+.pr-audit svg {
+ flex-shrink: 0;
+}
+a.pr-audit:hover,
+a.pr-audit:focus-visible {
+ border-color: color-mix(in srgb, var(--cv-green) 55%, transparent);
+ background: color-mix(in srgb, var(--cv-green) 16%, transparent);
+ outline: none;
+}
+a.pr-audit:focus-visible {
+ outline: 2px solid var(--cv-green);
+ outline-offset: 2px;
+}
+.pr-audit-static {
+ cursor: help;
+}
+
+/* Meta chips: category, fork-of, parent family, listed date. */
+.pr-meta {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.375rem;
+ margin: 0.875rem 0 0;
+}
+.pr-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;
+}
+.pr-chip-cat {
+ 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);
+}
+
+.pr-desc {
+ margin-top: 1rem;
+ font-size: 0.9375rem;
+ max-width: 68ch;
+}
+.pr-links {
+ margin-top: 1.125rem;
+}
+
+/* ── Stat cards ────────────────────────────────────────────────────────────── */
+
+.pr-stat .sub {
+ margin-top: 0.25rem;
+}
+
+/* ── Chart tooltip + hallmark markers ──────────────────────────────────────── */
+
+.cv-chart-tip .d {
+ font-size: 0.75rem;
+ color: var(--cv-text-3);
+}
+.pr-hallmark {
+ cursor: help;
+}
+.pr-hallmark polygon {
+ transition: opacity 0.15s;
+}
+.pr-hallmark:hover polygon {
+ opacity: 0.75;
+}
+
+/* ── Chain breakdown: share bars ───────────────────────────────────────────── */
+
+.pr-chain-link {
+ color: var(--cv-text);
+ text-decoration: none;
+ font-weight: 500;
+ transition: color 0.15s;
+}
+.pr-chain-link:hover,
+.pr-chain-link:focus-visible {
+ color: var(--cv-accent);
+}
+.pr-chain-link:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+ border-radius: var(--cv-radius-sm);
+}
+.pr-share-cell {
+ display: flex;
+ align-items: center;
+ gap: 0.625rem;
+ min-width: 8rem;
+}
+.pr-share-track {
+ flex: 1;
+ height: 6px;
+ border-radius: 999px;
+ background: var(--cv-surface-3);
+ overflow: hidden;
+ min-width: 3rem;
+}
+.pr-share-fill {
+ display: block;
+ height: 100%;
+ border-radius: 999px;
+ background: var(--cv-accent);
+ min-width: 2px;
+ transition: width 0.4s ease;
+}
+.pr-share-num {
+ color: var(--cv-text-2);
+ font-size: 0.8125rem;
+ min-width: 3.25rem;
+ text-align: right;
+}
+
+.pr-note {
+ margin: 0.875rem 0 0;
+ font-size: 0.8125rem;
+ color: var(--cv-text-3);
+}
+
+/* ── Fees & revenue grid ───────────────────────────────────────────────────── */
+
+.pr-fees-sub {
+ margin: 0 0 1rem;
+ font-size: 0.875rem;
+ color: var(--cv-text-2);
+ max-width: 68ch;
+}
+.pr-fee-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
+ gap: 0.75rem;
+}
+.pr-fee-item {
+ padding: 0.875rem 1rem;
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-md);
+ background: var(--cv-surface-2);
+}
+.pr-fee-label {
+ margin: 0 0 0.375rem;
+ font-size: 0.75rem;
+ color: var(--cv-text-3);
+ text-transform: uppercase;
+ letter-spacing: 0.03em;
+}
+.pr-fee-val {
+ margin: 0;
+ font-size: 1.0625rem;
+ font-weight: 600;
+ color: var(--cv-text);
+}
+
+/* ── Funding rounds table ──────────────────────────────────────────────────── */
+
+.pr-val-sub {
+ display: block;
+ font-size: 0.75rem;
+ color: var(--cv-text-3);
+}
+.pr-investors {
+ color: var(--cv-text-2);
+ font-size: 0.875rem;
+}
+.pr-investors .dim {
+ color: var(--cv-text-3);
+}
+.pr-lead-tag {
+ display: inline-block;
+ margin-left: 0.25rem;
+ padding: 0.0625rem 0.375rem;
+ border-radius: 999px;
+ font-size: 0.625rem;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--cv-accent);
+ background: color-mix(in srgb, var(--cv-accent) 12%, transparent);
+ vertical-align: middle;
+}
+
+.pr-methodology {
+ font-size: 0.9375rem;
+ max-width: 72ch;
+}
+
+/* ── Error-state retry button ──────────────────────────────────────────────── */
+
+.pr-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;
+}
+.pr-retry:hover {
+ border-color: var(--cv-border-hover);
+ background: var(--cv-surface-3);
+}
+.pr-retry:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+}
+
+@media (max-width: 560px) {
+ .pr-share-cell {
+ min-width: 6rem;
+ }
+ .pr-share-track {
+ display: none; /* keep the % legible on narrow screens; drop the bar */
+ }
+}
+
+@media (max-width: 480px) {
+ .pr-hero {
+ gap: 0.875rem;
+ }
+ .pr-logo {
+ width: 56px;
+ height: 56px;
+ border-radius: 12px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .pr-chain-link,
+ .pr-audit,
+ .pr-retry,
+ .pr-share-fill,
+ .pr-hallmark polygon {
+ transition: none;
+ }
+}
diff --git a/src/protocol-page.js b/src/protocol-page.js
new file mode 100644
index 000000000..fde07efd2
--- /dev/null
+++ b/src/protocol-page.js
@@ -0,0 +1,632 @@
+// /protocol/:slug — rich profile for one DeFi protocol, part of the three.ws
+// Markets surface. Hero (logo / name / symbol / category / audit badge /
+// fork + parent chips / link pills / description), stat cards (TVL, Mcap/TVL,
+// 24h fees, 24h revenue, 24h DEX volume), an interactive SVG TVL-history chart
+// with a range toggle, crosshair tooltip, and hallmark event markers, a
+// per-chain TVL breakdown with share bars linking into /chain/:name, a funding-
+// rounds table, a fees & revenue grid, and the TVL methodology prose. Data
+// comes from the /api/defi/protocol proxy (DeFiLlama) — never mocked. Mirrors
+// the /exchange/:id detail-page pattern (src/exchange-page.js).
+
+import { formatUsd, formatDateShort, escapeHtml as esc } from './shared/coin-format.js';
+
+const $ = (id) => document.getElementById(id);
+
+// Matches the /protocol/:slug route; falls back to the ?slug= query for direct
+// links and dev proxies that don't rewrite the path.
+function slugFromLocation() {
+ const m = location.pathname.match(/^\/protocol\/([a-z0-9.-]{1,80})$/i);
+ if (m) return m[1].toLowerCase();
+ const q = new URLSearchParams(location.search).get('slug');
+ return q && /^[a-z0-9.-]{1,80}$/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();
+}
+
+// A twitter handle from DeFiLlama is a bare handle ("aave") 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() {
+ $('pr-hero').innerHTML = `
+ <div class="pr-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>`;
+ $('pr-stats').innerHTML =
+ '<div class="cv-stats-grid">' +
+ Array.from({ length: 4 }, () => '<div class="cv-skel" style="height:5.5rem"></div>').join('') +
+ '</div>';
+ $('pr-chart').innerHTML =
+ '<div class="cv-chart-panel"><div class="cv-skel" style="height:300px;border-radius:8px"></div></div>';
+ $('pr-chains').innerHTML = `
+ <h2 class="cv-h2">TVL by chain</h2>
+ <div class="cv-table-wrap" style="padding:0.75rem">
+ ${Array.from({ length: 5 }, () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>').join('')}
+ </div>`;
+ $('pr-fees').innerHTML = '';
+ $('pr-raises').innerHTML = '';
+ $('pr-methodology').innerHTML = '';
+}
+
+// ── Hero ─────────────────────────────────────────────────────────────────────
+
+const SHIELD_ICON =
+ '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>';
+
+function auditBadge(audits) {
+ if (!audits) return '';
+ const n = audits.count || 0;
+ const label = n > 0 ? `${n} audit${n === 1 ? '' : 's'}` : 'Audited';
+ const links = Array.isArray(audits.audit_links) ? audits.audit_links : [];
+ if (links.length) {
+ return `<a class="pr-audit" href="${esc(links[0])}" target="_blank" rel="noopener noreferrer"
+ title="View audit reports (opens in a new tab)">${SHIELD_ICON}${esc(label)} ↗</a>`;
+ }
+ return `<span class="pr-audit pr-audit-static" title="Independently audited">${SHIELD_ICON}${esc(label)}</span>`;
+}
+
+function metaChips(d) {
+ const chips = [];
+ if (d.category) chips.push(`<span class="pr-chip pr-chip-cat">${esc(d.category)}</span>`);
+ for (const fork of d.forkedFrom || [])
+ chips.push(`<span class="pr-chip" title="Forked from ${esc(fork)}">Fork of ${esc(fork)}</span>`);
+ if (d.parentProtocol) {
+ const p = d.parentProtocol.replace(/^parent#/, '');
+ chips.push(`<span class="pr-chip" title="Part of the ${esc(p)} protocol family">Part of ${esc(p)}</span>`);
+ }
+ if (d.listedAt) chips.push(`<span class="pr-chip">Listed ${esc(formatDateShort(d.listedAt * 1000))}</span>`);
+ return chips.length ? `<div class="pr-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 pills = [];
+ if (d.url) pills.push(linkPill(d.url, 'Website'));
+ const tw = d.twitter ? twitterUrl(d.twitter) : null;
+ if (tw) pills.push(linkPill(tw, 'Twitter'));
+ return pills.length ? `<div class="cv-pills pr-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 pr-desc">${paras}</div>` : '';
+}
+
+function renderHero(d) {
+ $('pr-crumb-name').textContent = d.name;
+ $('pr-hero').innerHTML = `
+ <div class="pr-hero">
+ ${
+ d.logo
+ ? `<img class="pr-logo" src="${esc(d.logo)}" alt="${esc(d.name)} logo" width="72" height="72" loading="eager" data-no-dark-filter />`
+ : '<div class="pr-logo pr-logo-fallback" aria-hidden="true"></div>'
+ }
+ <div class="pr-hero-body">
+ <div class="pr-title-row">
+ <h1 class="cv-h1 pr-title">${esc(d.name)}</h1>
+ ${d.symbol ? `<span class="pr-symbol">${esc(d.symbol)}</span>` : ''}
+ ${auditBadge(d.audits)}
+ </div>
+ ${metaChips(d)}
+ ${heroDescription(d)}
+ ${heroLinks(d)}
+ </div>
+ </div>`;
+}
+
+// ── Stat cards ───────────────────────────────────────────────────────────────
+
+function statCard({ label, value, sub }) {
+ return `
+ <div class="cv-mini-stat pr-stat">
+ <p class="label">${esc(label)}</p>
+ <p class="value cv-mono">${esc(value)}</p>
+ ${sub ? `<p class="sub">${esc(sub)}</p>` : ''}
+ </div>`;
+}
+
+function renderStats(d) {
+ const cards = [];
+ if (d.tvl_current != null) cards.push(statCard({ label: 'Total Value Locked', value: formatUsd(d.tvl_current) }));
+ if (d.mcap != null && d.tvl_current) {
+ const ratio = d.mcap / d.tvl_current;
+ cards.push(
+ statCard({
+ label: 'Mcap / TVL',
+ value: ratio.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }),
+ sub: `Mcap ${formatUsd(d.mcap)}`,
+ }),
+ );
+ }
+ if (d.fees?.total24h != null)
+ cards.push(statCard({ label: '24h Fees', value: formatUsd(d.fees.total24h) }));
+ if (d.fees?.revenue24h != null)
+ cards.push(statCard({ label: '24h Revenue', value: formatUsd(d.fees.revenue24h) }));
+ if (d.dex_volume?.total24h != null)
+ cards.push(statCard({ label: '24h DEX Volume', value: formatUsd(d.dex_volume.total24h) }));
+
+ if (!cards.length) {
+ $('pr-stats').innerHTML = '';
+ return;
+ }
+ $('pr-stats').innerHTML = `<div class="cv-stats-grid">${cards.join('')}</div>`;
+}
+
+// ── TVL history chart ─────────────────────────────────────────────────────────
+
+const TIME_RANGES = [
+ { label: '30D', days: 30 },
+ { label: '90D', days: 90 },
+ { label: '1Y', days: 365 },
+ { label: 'All', days: null },
+];
+
+const CHART_W = 800;
+const CHART_H = 300;
+const PAD = { top: 20, right: 80, bottom: 30, left: 10 };
+
+// series: [{ t: unix_s, tvl }], full history already downsampled server-side.
+// The range toggle slices this client-side (no refetch — we have it all).
+const chartState = { full: [], hallmarks: [], days: 30, name: '' };
+
+function visibleSeries() {
+ const { full, days } = chartState;
+ if (days == null) return full;
+ const cutoff = Date.now() / 1000 - days * 86400;
+ const win = full.filter((p) => p.t >= cutoff);
+ return win.length >= 2 ? win : full;
+}
+
+function chartGeometry(series) {
+ const vals = series.map((p) => p.tvl);
+ const min = Math.min(...vals);
+ const max = Math.max(...vals);
+ const range = max - min || 1;
+ const tMin = series[0].t;
+ const tMax = series[series.length - 1].t;
+ const tRange = tMax - tMin || 1;
+ const w = CHART_W - PAD.left - PAD.right;
+ const h = CHART_H - PAD.top - PAD.bottom;
+ const x = (t) => PAD.left + ((t - tMin) / tRange) * w;
+ const y = (v) => PAD.top + h - ((v - min) / range) * h;
+ const pts = series.map((p) => ({ x: x(p.t), y: y(p.tvl) }));
+ 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, tMin, tMax, tRange, x, y, line, area };
+}
+
+function tickLabel(ts, days) {
+ const d = new Date(ts * 1000);
+ if (Number.isNaN(d.getTime())) return '';
+ if (days != null && days <= 90) return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
+ return `${d.toLocaleDateString('en-US', { month: 'short' })} '${String(d.getFullYear() % 100).padStart(2, '0')}`;
+}
+
+function hallmarkMarkers(g, series) {
+ const items = (chartState.hallmarks || []).filter((h) => h[0] >= g.tMin && h[0] <= g.tMax);
+ if (!items.length) return '';
+ const top = PAD.top;
+ const bottom = CHART_H - PAD.bottom;
+ return items
+ .map((h) => {
+ const hx = g.x(h[0]);
+ return `<g class="pr-hallmark"><title>${esc(h[1])} — ${esc(formatDateShort(h[0] * 1000))}</title>
+ <line x1="${hx.toFixed(2)}" y1="${top}" x2="${hx.toFixed(2)}" y2="${bottom}" stroke="var(--cv-text-3)" stroke-width="0.75" stroke-dasharray="2 3" opacity="0.55"/>
+ <polygon points="${(hx - 4).toFixed(2)},${top - 8} ${(hx + 4).toFixed(2)},${top - 8} ${hx.toFixed(2)},${top - 1}" fill="var(--cv-accent)"/>
+ <rect x="${(hx - 7).toFixed(2)}" y="${top - 10}" width="14" height="14" fill="transparent"/></g>`;
+ })
+ .join('');
+}
+
+function renderChart() {
+ const el = $('pr-chart');
+ const { days, name } = chartState;
+ const series = visibleSeries();
+
+ const rangeBtns = TIME_RANGES.map(
+ (r) =>
+ `<button type="button" class="cv-range-btn" data-days="${r.days == null ? 'all' : r.days}" aria-pressed="${r.days === days}">${r.label}</button>`,
+ ).join('');
+
+ let body;
+ if (series.length < 2) {
+ body = '<div class="cv-chart-state">No TVL 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(formatUsd(v))}</text></g>`;
+ }).join('');
+ body = `
+ <div class="cv-chart-area">
+ <svg viewBox="0 0 ${CHART_W} ${CHART_H}" role="img"
+ aria-label="Total value locked history for ${esc(name)}">
+ <defs>
+ <linearGradient id="pr-grad" x1="0" x2="0" y1="0" y2="1">
+ <stop offset="0%" stop-color="${color}" stop-opacity="0.22"/>
+ <stop offset="100%" stop-color="${color}" stop-opacity="0.02"/>
+ </linearGradient>
+ </defs>
+ ${yLabels}
+ <path d="${g.area}" fill="url(#pr-grad)"/>
+ <path d="${g.line}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
+ ${hallmarkMarkers(g, series)}
+ <g id="pr-crosshair" hidden>
+ <line id="pr-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="pr-cross-dot" r="4" fill="${color}" stroke="var(--cv-surface)" stroke-width="2"/>
+ </g>
+ </svg>
+ <div class="cv-chart-tip" id="pr-tip" hidden>
+ <p class="p cv-mono" id="pr-tip-val"></p>
+ <p class="d" id="pr-tip-date"></p>
+ </div>
+ </div>`;
+ }
+
+ el.innerHTML = `
+ <div class="cv-chart-panel">
+ <div class="cv-chart-bar">
+ <div class="left"><span class="title">Total Value Locked</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 raw = btn.dataset.days;
+ const dd = raw === 'all' ? null : Number(raw);
+ if (dd === chartState.days) return;
+ chartState.days = dd;
+ renderChart();
+ });
+ });
+
+ wireChartPointer(series);
+}
+
+function wireChartPointer(series) {
+ const svg = $('pr-chart').querySelector('svg');
+ const tip = $('pr-tip');
+ if (!svg || !tip || series.length < 2) return;
+ const g = chartGeometry(series);
+ const cross = svg.querySelector('#pr-crosshair');
+ const crossLine = svg.querySelector('#pr-cross-line');
+ const crossDot = svg.querySelector('#pr-cross-dot');
+
+ function show(clientX) {
+ const rect = svg.getBoundingClientRect();
+ const mouseX = ((clientX - rect.left) / rect.width) * CHART_W;
+ // Nearest point by rendered x (series may be time-non-uniform after windowing).
+ let i = 0;
+ let best = Infinity;
+ for (let k = 0; k < series.length; k++) {
+ const dx = Math.abs(g.x(series[k].t) - mouseX);
+ if (dx < best) {
+ best = dx;
+ i = k;
+ }
+ }
+ const p = series[i];
+ const x = g.x(p.t);
+ const y = g.y(p.tvl);
+ 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}%`;
+ $('pr-tip-val').textContent = formatUsd(p.tvl);
+ $('pr-tip-date').textContent = formatDateShort(p.t * 1000);
+ }
+ 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));
+}
+
+// ── Chain breakdown ────────────────────────────────────────────────────────────
+
+function renderChains(d) {
+ const el = $('pr-chains');
+ const chains = Array.isArray(d.chain_tvls) ? d.chain_tvls : [];
+ if (!chains.length) {
+ el.innerHTML = '';
+ return;
+ }
+ const total = chains.reduce((s, c) => s + c.tvl, 0) || 1;
+ const rows = chains
+ .map((c) => {
+ const share = (c.tvl / total) * 100;
+ return `
+ <tr>
+ <td class="left">
+ <a class="pr-chain-link" href="/chain/${encodeURIComponent(c.chain)}">${esc(c.chain)}</a>
+ </td>
+ <td class="cv-mono">${esc(formatUsd(c.tvl))}</td>
+ <td class="pr-share-cell">
+ <span class="pr-share-track" aria-hidden="true"><span class="pr-share-fill" style="width:${share.toFixed(2)}%"></span></span>
+ <span class="cv-mono pr-share-num">${share.toFixed(share < 1 ? 2 : 1)}%</span>
+ </td>
+ </tr>`;
+ })
+ .join('');
+ const single = chains.length === 1 ? '<p class="pr-note">This protocol reports TVL on a single chain.</p>' : '';
+ el.innerHTML = `
+ <h2 class="cv-h2">TVL by chain</h2>
+ <div class="cv-table-wrap">
+ <table class="cv-table pr-chain-table">
+ <thead>
+ <tr>
+ <th scope="col" class="left">Chain</th>
+ <th scope="col">TVL</th>
+ <th scope="col">Share</th>
+ </tr>
+ </thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>
+ ${single}`;
+}
+
+// ── Fees & revenue grid ────────────────────────────────────────────────────────
+
+function feeItem(label, value) {
+ return `<div class="pr-fee-item"><p class="pr-fee-label">${esc(label)}</p><p class="pr-fee-val cv-mono">${esc(value)}</p></div>`;
+}
+
+function renderFees(d) {
+ const el = $('pr-fees');
+ const f = d.fees;
+ if (!f) {
+ el.innerHTML = '';
+ return;
+ }
+ const items = [];
+ const push = (label, v) => {
+ if (v != null) items.push(feeItem(label, formatUsd(v)));
+ };
+ push('Fees · 24h', f.total24h);
+ push('Fees · 7d', f.total7d);
+ push('Fees · 30d', f.total30d);
+ push('Fees · all-time', f.totalAllTime);
+ push('Revenue · 24h', f.revenue24h);
+ push('Revenue · 7d', f.revenue7d);
+ push('Revenue · 30d', f.revenue30d);
+ if (d.dex_volume?.total24h != null) push('DEX volume · 24h', d.dex_volume.total24h);
+ if (d.dex_volume?.total7d != null) push('DEX volume · 7d', d.dex_volume.total7d);
+ if (!items.length) {
+ el.innerHTML = '';
+ return;
+ }
+ el.innerHTML = `
+ <h2 class="cv-h2">Fees &amp; revenue</h2>
+ <p class="pr-fees-sub">Fees are what users pay to use the protocol; revenue is the share that accrues to the protocol and its token holders.</p>
+ <div class="pr-fee-grid">${items.join('')}</div>`;
+}
+
+// ── Funding rounds ─────────────────────────────────────────────────────────────
+
+function investorList(lead, other) {
+ const names = [...(lead || []), ...(other || [])];
+ if (!names.length) return '<span class="dim">—</span>';
+ const shown = names.slice(0, 4).map(esc).join(', ');
+ const extra = names.length > 4 ? ` +${names.length - 4}` : '';
+ const leadTag = (lead || []).length ? ' <span class="pr-lead-tag">lead</span>' : '';
+ return `${shown}${extra}${leadTag}`;
+}
+
+function renderRaises(d) {
+ const el = $('pr-raises');
+ const raises = d.raises;
+ if (!raises || !raises.length) {
+ el.innerHTML = '';
+ return;
+ }
+ const rows = raises
+ .map((r) => {
+ const amount = r.amount_usd != null ? formatUsd(r.amount_usd) : '—';
+ const valuation = r.valuation != null ? formatUsd(r.valuation * 1e6) : '';
+ const round = r.round ? esc(r.round) : '—';
+ const roundCell = r.source
+ ? `<a class="pr-chain-link" href="${esc(r.source)}" target="_blank" rel="noopener noreferrer">${round} ↗</a>`
+ : round;
+ return `
+ <tr>
+ <td class="left">${r.date ? esc(formatDateShort(r.date * 1000)) : '—'}</td>
+ <td>${roundCell}</td>
+ <td class="cv-mono">${esc(amount)}${valuation ? `<span class="pr-val-sub">@ ${esc(valuation)}</span>` : ''}</td>
+ <td class="pr-investors">${investorList(r.leadInvestors, r.otherInvestors)}</td>
+ </tr>`;
+ })
+ .join('');
+ const totalRaised = raises.reduce((s, r) => s + (r.amount_usd || 0), 0);
+ const totalNote = totalRaised > 0 ? `<p class="pr-note">Total disclosed funding: <span class="cv-mono">${esc(formatUsd(totalRaised))}</span> across ${raises.length} round${raises.length === 1 ? '' : 's'}.</p>` : '';
+ el.innerHTML = `
+ <h2 class="cv-h2">Funding rounds</h2>
+ <div class="cv-table-wrap">
+ <table class="cv-table pr-raise-table">
+ <thead>
+ <tr>
+ <th scope="col" class="left">Date</th>
+ <th scope="col">Round</th>
+ <th scope="col">Amount</th>
+ <th scope="col">Investors</th>
+ </tr>
+ </thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>
+ ${totalNote}`;
+}
+
+// ── Methodology ────────────────────────────────────────────────────────────────
+
+function renderMethodology(d) {
+ const el = $('pr-methodology');
+ if (!d.methodology) {
+ el.innerHTML = '';
+ return;
+ }
+ const paras = d.methodology
+ .split(/\n{2,}/)
+ .map((p) => p.trim())
+ .filter(Boolean)
+ .map((p) => `<p>${esc(p)}</p>`)
+ .join('');
+ el.innerHTML = `
+ <h2 class="cv-h2">How TVL is measured</h2>
+ <div class="cv-prose pr-methodology">${paras}</div>`;
+}
+
+// ── Error / not-found states ───────────────────────────────────────────────────
+
+function clearSections(except) {
+ for (const id of ['pr-stats', 'pr-chart', 'pr-chains', 'pr-fees', 'pr-raises', 'pr-methodology']) {
+ if (id !== except) $(id).innerHTML = '';
+ }
+}
+
+function renderNotFound(slug) {
+ $('pr-crumb-name').textContent = 'Not found';
+ $('pr-hero').innerHTML = `
+ <h1 class="cv-h1">Protocol not found</h1>
+ <div class="cv-empty" style="text-align:left">
+ <p style="margin:0 0 0.75rem">Could not find a DeFi protocol for “${esc(slug)}”. It may not be
+ tracked by DeFiLlama, or the slug is misspelled.</p>
+ <p style="margin:0">Browse the <a href="/defi">DeFi protocols directory</a> or head back to
+ <a href="/markets">Markets</a>.</p>
+ </div>`;
+ clearSections();
+}
+
+function renderError() {
+ $('pr-hero').innerHTML = `
+ <h1 class="cv-h1">Protocol 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="pr-retry" id="pr-retry">Retry</button>
+ <span style="margin-left:0.75rem">or return to the <a href="/defi">DeFi directory</a>.</span>
+ </div>`;
+ clearSections();
+ $('pr-retry')?.addEventListener('click', () => main());
+}
+
+// ── SEO / document metadata ────────────────────────────────────────────────────
+
+function updateMeta(d, slug) {
+ const title = `${d.name} — DeFi Protocol · three.ws`;
+ document.title = title;
+ const url = `https://three.ws/protocol/${slug}`;
+ const set = (sel, attr, val) => document.querySelector(sel)?.setAttribute(attr, val);
+ const tvl = d.tvl_current != null ? ` — ${formatUsd(d.tvl_current)} TVL` : '';
+ const cat = d.category ? `${d.category} protocol` : 'DeFi protocol';
+ const desc = `${d.name} ${cat}${tvl}: TVL history, per-chain breakdown, fees, revenue, and funding rounds. Real DeFiLlama 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.logo) {
+ set('meta[property="og:image"]', 'content', d.logo);
+ set('meta[name="twitter:image"]', 'content', d.logo);
+ }
+ 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 slug = slugFromLocation();
+ const root = $('pr-main');
+ if (!slug) {
+ location.replace('/defi');
+ return;
+ }
+ renderSkeletons();
+
+ let d;
+ try {
+ d = await getJson(`/api/defi/protocol?slug=${encodeURIComponent(slug)}`);
+ } catch (err) {
+ root.removeAttribute('aria-busy');
+ if (err.status === 404 || err.status === 400) renderNotFound(slug);
+ else renderError();
+ return;
+ }
+
+ root.removeAttribute('aria-busy');
+ updateMeta(d, slug);
+ renderHero(d);
+ renderStats(d);
+
+ if (Array.isArray(d.tvl_series) && d.tvl_series.length >= 2) {
+ chartState.full = d.tvl_series;
+ chartState.hallmarks = Array.isArray(d.hallmarks) ? d.hallmarks : [];
+ chartState.name = d.name;
+ // Default to the shortest range that still shows ≥2 points.
+ chartState.days = 30;
+ renderChart();
+ } else {
+ $('pr-chart').innerHTML = '';
+ }
+
+ renderChains(d);
+ renderFees(d);
+ renderRaises(d);
+ renderMethodology(d);
+
+ const upd = $('pr-updated');
+ upd.hidden = false;
+ upd.textContent = `Updated ${new Date(d.updated_at || Date.now()).toLocaleTimeString('en-US')} · source: DeFiLlama`;
+}
+
+main();
diff --git a/src/stablecoin-page.css b/src/stablecoin-page.css
new file mode 100644
index 000000000..30a6c10fd
--- /dev/null
+++ b/src/stablecoin-page.css
@@ -0,0 +1,298 @@
+/*
+ * /stablecoin/:id — feature styles layered on top of /src/coin-pages.css.
+ * Reuses the shared cv-* container, card, chart, table, pill, prose, and state
+ * system; adds only the hero, peg/mechanism chips, peg-health badge, supply-
+ * chart legend, and chain-dominance affordances unique to this detail page.
+ */
+
+/* ── Hero ──────────────────────────────────────────────────────────────────── */
+
+.sc-hero {
+ display: flex;
+ gap: 1.25rem;
+ align-items: flex-start;
+ margin: 0.5rem 0 2rem;
+}
+.sc-logo {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 64px;
+ height: 64px;
+ border-radius: 16px;
+ flex-shrink: 0;
+ font-family: var(--cv-font-mono);
+ font-size: 1.75rem;
+ font-weight: 700;
+ color: var(--cv-accent);
+ background: color-mix(in srgb, var(--cv-accent) 10%, var(--cv-surface-2));
+ border: 1px solid color-mix(in srgb, var(--cv-accent) 25%, var(--cv-border));
+}
+.sc-hero-body {
+ flex: 1;
+ min-width: 0;
+}
+.sc-title-row {
+ display: flex;
+ align-items: baseline;
+ flex-wrap: wrap;
+ gap: 0.5rem 0.75rem;
+}
+.sc-title {
+ margin: 0;
+ font-size: clamp(1.5rem, 4vw, 2rem);
+ line-height: 1.1;
+}
+.sc-symbol {
+ font-family: var(--cv-font-mono);
+ font-size: 0.9375rem;
+ font-weight: 600;
+ color: var(--cv-text-3);
+ letter-spacing: 0.02em;
+}
+
+/* Peg + mechanism chips. */
+.sc-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.375rem;
+ margin: 0.875rem 0 0;
+}
+.sc-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;
+}
+.sc-mech-fiat {
+ color: var(--cv-green);
+ border-color: color-mix(in srgb, var(--cv-green) 30%, transparent);
+ background: var(--cv-green-soft);
+}
+.sc-mech-crypto {
+ color: var(--cv-accent);
+ border-color: color-mix(in srgb, var(--cv-accent) 30%, transparent);
+ background: color-mix(in srgb, var(--cv-accent) 8%, transparent);
+}
+.sc-mech-algo {
+ color: #b45309;
+ border-color: rgba(234, 179, 8, 0.35);
+ background: rgba(234, 179, 8, 0.12);
+}
+:root[data-theme='dark'] .sc-mech-algo {
+ color: #fbbf24;
+}
+
+/* Price + peg-health badge. */
+.sc-price-row {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 0.625rem;
+ margin: 1rem 0 0;
+}
+.sc-price {
+ font-size: 1.625rem;
+ font-weight: 700;
+ line-height: 1;
+ font-variant-numeric: tabular-nums;
+}
+.sc-peg-badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 0.25rem 0.5rem;
+ border-radius: 999px;
+ font-family: var(--cv-font-mono);
+ font-size: 0.75rem;
+ font-weight: 600;
+ line-height: 1;
+ border: 1px solid transparent;
+ cursor: help;
+}
+.sc-peg-hi {
+ color: var(--cv-green);
+ background: var(--cv-green-soft);
+ border-color: color-mix(in srgb, var(--cv-green) 30%, transparent);
+}
+.sc-peg-mid {
+ color: #b45309;
+ background: rgba(234, 179, 8, 0.12);
+ border-color: rgba(234, 179, 8, 0.35);
+}
+:root[data-theme='dark'] .sc-peg-mid {
+ color: #fbbf24;
+}
+.sc-peg-lo {
+ color: var(--cv-red);
+ background: var(--cv-red-soft);
+ border-color: color-mix(in srgb, var(--cv-red) 30%, transparent);
+}
+
+.sc-desc {
+ margin-top: 1rem;
+ font-size: 0.9375rem;
+ max-width: 68ch;
+}
+.sc-links {
+ margin-top: 1.125rem;
+}
+/* Internal cross-links read as on-platform, not external. */
+.sc-pill-internal {
+ color: var(--cv-accent);
+ border-color: color-mix(in srgb, var(--cv-accent) 35%, transparent);
+}
+
+/* ── Stat cards ────────────────────────────────────────────────────────────── */
+
+.sc-stat .sub {
+ margin-top: 0.25rem;
+}
+.sc-dev-hi {
+ color: var(--cv-green);
+}
+.sc-dev-mid {
+ color: #b45309;
+}
+:root[data-theme='dark'] .sc-dev-mid {
+ color: #fbbf24;
+}
+.sc-dev-lo {
+ color: var(--cv-red);
+}
+
+/* ── Supply chart ──────────────────────────────────────────────────────────── */
+
+.sc-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem 1rem;
+ margin: 0 0 0.5rem;
+ padding: 0 0.25rem;
+}
+.sc-legend-item {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.375rem;
+ font-size: 0.75rem;
+ color: var(--cv-text-2);
+}
+.sc-legend-swatch {
+ width: 12px;
+ height: 3px;
+ border-radius: 2px;
+ flex-shrink: 0;
+}
+.cv-chart-tip .p + .p {
+ font-size: 0.75rem;
+ color: var(--cv-text-3);
+}
+
+/* ── Chain distribution ────────────────────────────────────────────────────── */
+
+.sc-chain-link {
+ color: var(--cv-text);
+ text-decoration: none;
+ font-weight: 500;
+ transition: color 0.15s;
+}
+.sc-chain-link:hover,
+.sc-chain-link:focus-visible {
+ color: var(--cv-accent);
+}
+.sc-chain-link:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+ border-radius: var(--cv-radius-sm);
+}
+.sc-share-cell {
+ display: flex;
+ align-items: center;
+ gap: 0.625rem;
+ justify-content: flex-end;
+}
+.sc-share-bar {
+ position: relative;
+ flex: 1;
+ max-width: 160px;
+ height: 6px;
+ border-radius: 999px;
+ background: var(--cv-surface-2);
+ overflow: hidden;
+}
+.sc-share-bar > span {
+ position: absolute;
+ inset: 0 auto 0 0;
+ height: 100%;
+ border-radius: 999px;
+ background: var(--cv-accent);
+ min-width: 2px;
+}
+.sc-share-pct {
+ min-width: 3.25rem;
+ text-align: right;
+ color: var(--cv-text-2);
+ font-size: 0.8125rem;
+}
+
+/* ── Mint / redeem + audits ────────────────────────────────────────────────── */
+
+.sc-prose {
+ font-size: 0.9375rem;
+ max-width: 72ch;
+}
+.sc-audit-pills {
+ margin-top: 0.25rem;
+}
+
+/* ── Error-state retry button ──────────────────────────────────────────────── */
+
+.sc-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;
+}
+.sc-retry:hover {
+ border-color: var(--cv-border-hover);
+ background: var(--cv-surface-3);
+}
+.sc-retry:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+}
+
+@media (max-width: 560px) {
+ .sc-hero {
+ gap: 0.875rem;
+ }
+ .sc-logo {
+ width: 52px;
+ height: 52px;
+ border-radius: 12px;
+ font-size: 1.375rem;
+ }
+ .sc-share-bar {
+ max-width: 84px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .sc-chain-link,
+ .sc-retry {
+ transition: none;
+ }
+}
diff --git a/src/stablecoin-page.js b/src/stablecoin-page.js
new file mode 100644
index 000000000..03bbdd78a
--- /dev/null
+++ b/src/stablecoin-page.js
@@ -0,0 +1,638 @@
+// /stablecoin/:id — rich profile for one stablecoin, part of the three.ws
+// Markets surface. Hero (name / symbol / peg + mechanism chips / price with a
+// peg-health badge / link pills / description), stat cards, an interactive SVG
+// supply-history chart (circulating over time with a range toggle + crosshair,
+// plus minted/unreleased lines when they materially diverge), a per-chain
+// circulation table with dominance bars, the mint/redeem mechanism prose, and
+// audit links. Data comes from the /api/defi/stablecoin proxy (DeFiLlama) —
+// never mocked. Mirrors the /exchange/:id detail-page pattern (src/exchange-page.js).
+
+import { formatUsd, formatPrice, formatChartTick, escapeHtml as esc } from './shared/coin-format.js';
+
+const $ = (id) => document.getElementById(id);
+
+// Matches the /stablecoin/: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(/^\/stablecoin\/(\d{1,6})$/);
+ if (m) return m[1];
+ const q = new URLSearchParams(location.search).get('id');
+ return q && /^\d{1,6}$/.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();
+}
+
+// A twitter URL from DeFiLlama arrives as a full profile URL, but normalize any
+// bare-handle stragglers to a canonical link.
+function twitterUrl(v) {
+ const s = String(v || '').trim();
+ if (!s) return null;
+ if (/^https?:\/\//i.test(s)) return s;
+ const h = s.replace(/^@/, '').replace(/\/+$/, '');
+ return h ? `https://twitter.com/${encodeURIComponent(h)}` : null;
+}
+
+// Peg deviation in basis points (1bp = 0.01%). Green within 10bp, amber within
+// 50bp, red beyond — the industry rule of thumb for a healthy dollar peg.
+function pegHealth(deviationPct) {
+ if (deviationPct == null || !Number.isFinite(deviationPct)) return null;
+ const bps = deviationPct * 100;
+ const abs = Math.abs(bps);
+ const band = abs <= 10 ? 'hi' : abs <= 50 ? 'mid' : 'lo';
+ const label = `${bps >= 0 ? '+' : '−'}${abs.toFixed(1)} bps`;
+ return { bps, band, label };
+}
+
+// ── Skeletons ────────────────────────────────────────────────────────────────
+
+function renderSkeletons() {
+ $('sc-hero').innerHTML = `
+ <div class="sc-hero">
+ <div class="cv-skel" style="width:64px;height:64px;border-radius:16px;flex-shrink:0"></div>
+ <div style="flex:1;min-width:0">
+ <div class="cv-skel" style="width:16rem;height:2rem"></div>
+ <div class="cv-skel" style="width:20rem;max-width:100%;height:1.25rem;margin-top:0.75rem"></div>
+ <div class="cv-skel" style="width:28rem;max-width:100%;height:3rem;margin-top:0.75rem"></div>
+ </div>
+ </div>`;
+ $('sc-stats').innerHTML =
+ '<div class="cv-stats-grid">' +
+ Array.from({ length: 4 }, () => '<div class="cv-skel" style="height:5.5rem"></div>').join('') +
+ '</div>';
+ $('sc-chart').innerHTML =
+ '<div class="cv-chart-panel"><div class="cv-skel" style="height:300px;border-radius:8px"></div></div>';
+ $('sc-chains').innerHTML = `
+ <h2 class="cv-h2">Circulation by chain</h2>
+ <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>`;
+ $('sc-mint').innerHTML = '';
+ $('sc-audits').innerHTML = '';
+}
+
+// ── Hero ─────────────────────────────────────────────────────────────────────
+
+function mechanismLabel(m) {
+ if (!m) return null;
+ return { 'fiat-backed': 'Fiat-backed', 'crypto-backed': 'Crypto-backed', algorithmic: 'Algorithmic' }[m] || m;
+}
+function mechanismClass(m) {
+ return { 'fiat-backed': 'sc-mech-fiat', 'crypto-backed': 'sc-mech-crypto', algorithmic: 'sc-mech-algo' }[m] || '';
+}
+
+function heroChips(d) {
+ const chips = [];
+ if (d.peg_type) chips.push(`<span class="sc-chip">${esc(d.peg_type)} peg</span>`);
+ const ml = mechanismLabel(d.mechanism);
+ if (ml) chips.push(`<span class="sc-chip ${mechanismClass(d.mechanism)}">${esc(ml)}</span>`);
+ return chips.length ? `<div class="sc-chips">${chips.join('')}</div>` : '';
+}
+
+function heroPrice(d) {
+ if (d.price == null) return '';
+ const health = pegHealth(d.peg_deviation_pct);
+ const badge = health
+ ? `<span class="sc-peg-badge sc-peg-${health.band}" title="Deviation from the $1.00 peg, in basis points">${esc(health.label)}</span>`
+ : '';
+ return `
+ <div class="sc-price-row">
+ <span class="sc-price cv-mono">${esc(formatPrice(d.price))}</span>
+ ${badge}
+ </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 pills = [];
+ if (d.url) pills.push(linkPill(d.url, 'Website'));
+ const tw = twitterUrl(d.twitter);
+ if (tw) pills.push(linkPill(tw, 'Twitter'));
+ if (Array.isArray(d.audit_links) && d.audit_links.length) {
+ pills.push(linkPill(d.audit_links[0], d.audit_links.length > 1 ? 'Audits' : 'Audit'));
+ }
+ // Internal cross-link to the coin's full market-data page when DeFiLlama
+ // carries a CoinGecko id — no new tab, it's an on-platform surface.
+ if (d.gecko_id) {
+ pills.push(
+ `<a class="cv-pill sc-pill-internal" href="/coin/${encodeURIComponent(d.gecko_id)}">Market data →</a>`,
+ );
+ }
+ return pills.length ? `<div class="cv-pills sc-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 sc-desc">${paras}</div>` : '';
+}
+
+function renderHero(d) {
+ $('sc-crumb-name').textContent = d.symbol || d.name;
+ const badgeChar = (d.symbol || d.name || '?').trim().charAt(0).toUpperCase();
+ $('sc-hero').innerHTML = `
+ <div class="sc-hero">
+ <div class="sc-logo" aria-hidden="true">${esc(badgeChar)}</div>
+ <div class="sc-hero-body">
+ <div class="sc-title-row">
+ <h1 class="cv-h1 sc-title">${esc(d.name)}</h1>
+ ${d.symbol ? `<span class="sc-symbol">${esc(d.symbol)}</span>` : ''}
+ </div>
+ ${heroChips(d)}
+ ${heroPrice(d)}
+ ${heroDescription(d)}
+ ${heroLinks(d)}
+ </div>
+ </div>`;
+}
+
+// ── Stat cards ───────────────────────────────────────────────────────────────
+
+function statCard({ label, value, valueClass = '', sub }) {
+ return `
+ <div class="cv-mini-stat sc-stat">
+ <p class="label">${esc(label)}</p>
+ <p class="value cv-mono ${valueClass}">${esc(value)}</p>
+ ${sub ? `<p class="sub">${esc(sub)}</p>` : ''}
+ </div>`;
+}
+
+function totalCirculating(d) {
+ if (!Array.isArray(d.chains)) return null;
+ let total = 0;
+ let any = false;
+ for (const c of d.chains) {
+ if (c.circulating_usd != null && Number.isFinite(c.circulating_usd)) {
+ total += c.circulating_usd;
+ any = true;
+ }
+ }
+ return any ? total : null;
+}
+
+function renderStats(d) {
+ const cards = [];
+ const total = totalCirculating(d);
+ const pegUnit = d.peg_type ? ` ${d.peg_type}` : '';
+ cards.push(
+ statCard({
+ label: 'Circulating',
+ value: total != null ? formatUsd(total) : '—',
+ sub: total != null && d.peg_type ? `denominated in${pegUnit}` : undefined,
+ }),
+ );
+ cards.push(
+ statCard({
+ label: 'Chains',
+ value: Array.isArray(d.chains) ? String(d.chains.length) : '—',
+ }),
+ );
+ cards.push(statCard({ label: 'Price', value: formatPrice(d.price) }));
+
+ const health = pegHealth(d.peg_deviation_pct);
+ if (health) {
+ cards.push(
+ statCard({
+ label: 'Peg deviation',
+ value: health.label,
+ valueClass: `sc-dev-${health.band}`,
+ }),
+ );
+ }
+ $('sc-stats').innerHTML = `<div class="cv-stats-grid">${cards.join('')}</div>`;
+}
+
+// ── Supply-history chart ─────────────────────────────────────────────────────
+
+const RANGES = [
+ { label: '30D', days: 30 },
+ { label: '90D', days: 90 },
+ { label: '1Y', days: 365 },
+ { label: 'All', days: null },
+];
+
+const CHART_W = 800;
+const CHART_H = 300;
+const PAD = { top: 20, right: 84, bottom: 30, left: 10 };
+
+// The metrics we can overlay. `circulating` is always drawn as the area; the
+// others become lines only when they materially diverge from circulating.
+const METRICS = {
+ circulating: { label: 'Circulating', color: 'var(--cv-chart-green)', area: true },
+ unreleased: { label: 'Unreleased', color: '#f59e0b', area: false },
+ minted: { label: 'Minted', color: 'var(--cv-accent)', area: false },
+};
+
+const chartState = { days: null, full: [], series: [], name: '', pegType: '', shown: ['circulating'] };
+
+// A secondary metric is worth its own line only when it rises above 0.5% of the
+// peak circulating supply somewhere in the window AND isn't just tracking
+// circulating exactly (which would draw a redundant overlapping line).
+function materiallyDiffers(series, key) {
+ let maxCirc = 0;
+ let maxMetric = 0;
+ let maxGap = 0;
+ for (const p of series) {
+ const c = p.circulating;
+ const v = p[key];
+ if (c != null && c > maxCirc) maxCirc = c;
+ if (v != null && v > maxMetric) maxMetric = v;
+ if (c != null && v != null) maxGap = Math.max(maxGap, Math.abs(c - v));
+ }
+ if (maxMetric <= 0 || maxCirc <= 0) return false;
+ if (maxMetric < maxCirc * 0.005) return false; // immaterial magnitude
+ return maxGap > maxCirc * 0.005; // and genuinely distinct from circulating
+}
+
+function computeShown(series) {
+ const shown = ['circulating'];
+ for (const key of ['unreleased', 'minted']) {
+ if (materiallyDiffers(series, key)) shown.push(key);
+ }
+ return shown;
+}
+
+function applyRange() {
+ const { full, days } = chartState;
+ if (days == null) {
+ chartState.series = full;
+ } else {
+ const cutoff = Date.now() - days * 86400_000;
+ const filtered = full.filter((p) => p.t >= cutoff);
+ // Keep at least the last two points so a short/quiet window never blanks.
+ chartState.series = filtered.length >= 2 ? filtered : full.slice(-2);
+ }
+ chartState.shown = computeShown(chartState.series);
+}
+
+function chartGeometry(series, shown) {
+ let min = 0; // supply floors at 0 — anchor the area there
+ let max = 0;
+ for (const p of series) {
+ for (const key of shown) {
+ const v = p[key];
+ if (v != null && v > max) max = v;
+ }
+ }
+ const range = max - min || 1;
+ const w = CHART_W - PAD.left - PAD.right;
+ const h = CHART_H - PAD.top - PAD.bottom;
+ const n = series.length;
+ const x = (i) => PAD.left + (n === 1 ? w / 2 : (i / (n - 1)) * w);
+ const y = (v) => PAD.top + h - ((v - min) / range) * h;
+
+ const paths = {};
+ for (const key of shown) {
+ const pts = [];
+ for (let i = 0; i < n; i++) {
+ const v = series[i][key];
+ if (v == null) continue;
+ pts.push(`${pts.length === 0 ? 'M' : 'L'}${x(i).toFixed(2)},${y(v).toFixed(2)}`);
+ }
+ paths[key] = pts.join(' ');
+ }
+ // Area under circulating.
+ let area = '';
+ if (paths.circulating) {
+ const first = x(0).toFixed(2);
+ const last = x(n - 1).toFixed(2);
+ const base = (PAD.top + h).toFixed(2);
+ area = `${paths.circulating} L${last},${base} L${first},${base} Z`;
+ }
+ return { min, max, range, paths, area, x, y };
+}
+
+function yAxis(g) {
+ const steps = 4;
+ const h = CHART_H - PAD.top - PAD.bottom;
+ return 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(formatUsd(v))}</text></g>`;
+ }).join('');
+}
+
+function legend(shown) {
+ if (shown.length < 2) return '';
+ const items = shown
+ .map(
+ (key) =>
+ `<span class="sc-legend-item"><span class="sc-legend-swatch" style="background:${METRICS[key].color}"></span>${esc(METRICS[key].label)}</span>`,
+ )
+ .join('');
+ return `<div class="sc-legend">${items}</div>`;
+}
+
+function renderChart() {
+ const el = $('sc-chart');
+ const { days, series, shown, name } = chartState;
+
+ const rangeBtns = RANGES.map(
+ (r) =>
+ `<button type="button" class="cv-range-btn" data-days="${r.days == null ? 'all' : r.days}" aria-pressed="${r.days === days}">${r.label}</button>`,
+ ).join('');
+
+ let body;
+ if (series.length < 2) {
+ body = '<div class="cv-chart-state">No supply history available for this range.</div>';
+ } else {
+ const g = chartGeometry(series, shown);
+ const lines = shown
+ .map((key) =>
+ METRICS[key].area
+ ? `<path d="${g.paths[key]}" fill="none" stroke="${METRICS[key].color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>`
+ : `<path d="${g.paths[key]}" fill="none" stroke="${METRICS[key].color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="${key === 'unreleased' ? '5 3' : '2 3'}"/>`,
+ )
+ .join('');
+ body = `
+ ${legend(shown)}
+ <div class="cv-chart-area">
+ <svg viewBox="0 0 ${CHART_W} ${CHART_H}" role="img"
+ aria-label="Circulating supply history for ${esc(name)}${days ? ` over ${days} days` : ' (all time)'}">
+ <defs>
+ <linearGradient id="sc-grad" x1="0" x2="0" y1="0" y2="1">
+ <stop offset="0%" stop-color="${METRICS.circulating.color}" stop-opacity="0.2"/>
+ <stop offset="100%" stop-color="${METRICS.circulating.color}" stop-opacity="0.02"/>
+ </linearGradient>
+ </defs>
+ ${yAxis(g)}
+ <path d="${g.area}" fill="url(#sc-grad)"/>
+ ${lines}
+ <g id="sc-crosshair" hidden>
+ <line id="sc-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="sc-cross-dot" r="4" fill="${METRICS.circulating.color}" stroke="var(--cv-surface)" stroke-width="2"/>
+ </g>
+ </svg>
+ <div class="cv-chart-tip" id="sc-tip" hidden>
+ <p class="p cv-mono" id="sc-tip-val"></p>
+ <p class="p cv-mono" id="sc-tip-extra"></p>
+ <p class="d" id="sc-tip-date"></p>
+ </div>
+ </div>`;
+ }
+
+ el.innerHTML = `
+ <div class="cv-chart-panel">
+ <div class="cv-chart-bar">
+ <div class="left"><span class="title">Circulating supply</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 raw = btn.dataset.days;
+ const dd = raw === 'all' ? null : Number(raw);
+ if (dd === chartState.days) return;
+ chartState.days = dd;
+ applyRange();
+ renderChart();
+ });
+ });
+
+ wireChartPointer();
+}
+
+function wireChartPointer() {
+ const svg = $('sc-chart').querySelector('svg');
+ const tip = $('sc-tip');
+ if (!svg || !tip || chartState.series.length < 2) return;
+ const g = chartGeometry(chartState.series, chartState.shown);
+ const cross = svg.querySelector('#sc-crosshair');
+ const crossLine = svg.querySelector('#sc-cross-line');
+ const crossDot = svg.querySelector('#sc-cross-dot');
+ const usableW = CHART_W - PAD.left - PAD.right;
+
+ 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 p = chartState.series[i];
+ const x = g.x(i);
+ cross.removeAttribute('hidden');
+ crossLine.setAttribute('x1', x);
+ crossLine.setAttribute('x2', x);
+ if (p.circulating != null) {
+ crossDot.removeAttribute('hidden');
+ crossDot.setAttribute('cx', x);
+ crossDot.setAttribute('cy', g.y(p.circulating));
+ } else {
+ crossDot.setAttribute('hidden', '');
+ }
+ tip.hidden = false;
+ tip.style.left = `${(x / CHART_W) * 100}%`;
+ $('sc-tip-val').textContent = formatUsd(p.circulating);
+ const extras = chartState.shown
+ .filter((k) => k !== 'circulating' && p[k] != null)
+ .map((k) => `${METRICS[k].label}: ${formatUsd(p[k])}`)
+ .join(' · ');
+ $('sc-tip-extra').textContent = extras;
+ $('sc-tip-extra').hidden = !extras;
+ $('sc-tip-date').textContent = formatChartTick(p.t, chartState.days || 400);
+ }
+ 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));
+}
+
+// ── Chain distribution ───────────────────────────────────────────────────────
+
+function renderChains(d) {
+ const el = $('sc-chains');
+ const chains = Array.isArray(d.chains) ? d.chains : [];
+ if (!chains.length) {
+ el.innerHTML = `
+ <h2 class="cv-h2">Circulation by chain</h2>
+ <div class="cv-empty">No per-chain circulation is reported for this stablecoin right now.</div>`;
+ return;
+ }
+ const rows = chains
+ .map((c) => {
+ const share = c.share_pct != null && Number.isFinite(c.share_pct) ? c.share_pct : null;
+ const bar = share != null ? Math.max(1, Math.min(100, share)) : 0;
+ return `
+ <tr>
+ <td class="left">
+ <a class="sc-chain-link" href="/chain/${encodeURIComponent(c.chain)}">${esc(c.chain)}</a>
+ </td>
+ <td class="cv-mono">${esc(formatUsd(c.circulating_usd))}</td>
+ <td class="sc-share-cell">
+ <span class="sc-share-bar" aria-hidden="true"><span style="width:${bar}%"></span></span>
+ <span class="cv-mono sc-share-pct">${share != null ? `${share.toFixed(share < 1 ? 2 : 1)}%` : '—'}</span>
+ </td>
+ </tr>`;
+ })
+ .join('');
+ el.innerHTML = `
+ <h2 class="cv-h2">Circulation by chain</h2>
+ <div class="cv-table-wrap">
+ <table class="cv-table sc-chain-table">
+ <thead>
+ <tr>
+ <th scope="col" class="left">Chain</th>
+ <th scope="col">Circulating</th>
+ <th scope="col">Dominance</th>
+ </tr>
+ </thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>`;
+}
+
+// ── Mint / redeem + audits ───────────────────────────────────────────────────
+
+function renderMint(d) {
+ const el = $('sc-mint');
+ if (!d.mint_redeem) {
+ el.innerHTML = '';
+ return;
+ }
+ el.innerHTML = `
+ <h2 class="cv-h2">Mint &amp; redeem</h2>
+ <div class="cv-prose sc-prose"><p>${esc(d.mint_redeem)}</p></div>`;
+}
+
+function renderAudits(d) {
+ const el = $('sc-audits');
+ const links = Array.isArray(d.audit_links) ? d.audit_links : [];
+ if (!links.length) {
+ el.innerHTML = '';
+ return;
+ }
+ const pills = links
+ .map((url, i) => {
+ const label = links.length > 1 ? `Audit ${i + 1}` : 'Audit report';
+ return `<a class="cv-pill" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${label} ↗</a>`;
+ })
+ .join('');
+ el.innerHTML = `
+ <h2 class="cv-h2">Audits</h2>
+ <div class="cv-pills sc-audit-pills">${pills}</div>`;
+}
+
+// ── Error / not-found states ─────────────────────────────────────────────────
+
+function clearSections() {
+ for (const id of ['sc-stats', 'sc-chart', 'sc-chains', 'sc-mint', 'sc-audits']) $(id).innerHTML = '';
+}
+
+function renderNotFound(id) {
+ $('sc-crumb-name').textContent = 'Not found';
+ $('sc-hero').innerHTML = `
+ <h1 class="cv-h1">Stablecoin not found</h1>
+ <div class="cv-empty" style="text-align:left">
+ <p style="margin:0 0 0.75rem">Could not find a stablecoin for id “${esc(id)}”. It may not be
+ tracked by DeFiLlama, or the id is wrong.</p>
+ <p style="margin:0">Browse the <a href="/stablecoins">stablecoins board</a> or head back to
+ <a href="/markets">Markets</a>.</p>
+ </div>`;
+ clearSections();
+}
+
+function renderError() {
+ $('sc-hero').innerHTML = `
+ <h1 class="cv-h1">Stablecoin 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="sc-retry" id="sc-retry">Retry</button>
+ <span style="margin-left:0.75rem">or return to the <a href="/stablecoins">stablecoins board</a>.</span>
+ </div>`;
+ clearSections();
+ $('sc-retry')?.addEventListener('click', () => main());
+}
+
+// ── SEO / document metadata ──────────────────────────────────────────────────
+
+function updateMeta(d, id) {
+ const title = `${d.name}${d.symbol ? ` (${d.symbol})` : ''} — Stablecoin · three.ws`;
+ document.title = title;
+ const url = `https://three.ws/stablecoin/${id}`;
+ const set = (sel, attr, val) => document.querySelector(sel)?.setAttribute(attr, val);
+ const mech = mechanismLabel(d.mechanism);
+ const desc = `${d.name}${d.symbol ? ` (${d.symbol})` : ''}${mech ? ` — ${mech.toLowerCase()} stablecoin` : ' stablecoin'}: peg health, per-chain circulation, supply history, and audits. Real DeFiLlama 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);
+ 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 = $('sc-main');
+ if (!id) {
+ location.replace('/stablecoins');
+ return;
+ }
+ renderSkeletons();
+
+ let d;
+ try {
+ d = await getJson(`/api/defi/stablecoin?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');
+ updateMeta(d, id);
+ renderHero(d);
+ renderStats(d);
+ renderChains(d);
+ renderMint(d);
+ renderAudits(d);
+
+ // Supply history.
+ const series = Array.isArray(d.supply_series) ? d.supply_series : [];
+ if (series.length < 2) {
+ $('sc-chart').innerHTML = '';
+ } else {
+ chartState.full = series;
+ chartState.name = d.name;
+ chartState.pegType = d.peg_type || '';
+ chartState.days = null; // default to the full history
+ applyRange();
+ renderChart();
+ }
+
+ const upd = $('sc-updated');
+ upd.hidden = false;
+ upd.textContent = `Updated ${new Date(d.updated_at || Date.now()).toLocaleTimeString('en-US')} · source: DeFiLlama`;
+}
+
+main();
diff --git a/src/stablecoins.js b/src/stablecoins.js
index 8785541f3..8b5e17bbf 100644
--- a/src/stablecoins.js
+++ b/src/stablecoins.js
@@ -179,8 +179,13 @@ function renderTable() {
const body = rows
.map((c) => {
const m = mechanism(c.peg_mechanism);
+ // Whole row opens the internal /stablecoin/:id detail page when we
+ // have DeFiLlama's numeric id; keyboard-accessible.
+ const nav = c.id
+ ? ` data-href="/stablecoin/${encodeURIComponent(c.id)}" tabindex="0" role="link" aria-label="Open ${esc(c.name)} detail page"`
+ : '';
return `
- <tr>
+ <tr${nav}>
<td class="rank hide-sm cv-mono">${c._rank ?? '—'}</td>
<td class="left name-cell"><span class="inner">
<span class="nm">${esc(c.name)}</span>
@@ -223,6 +228,18 @@ function renderTable() {
}
});
});
+
+ // Row → /stablecoin/:id navigation (a header click must never navigate).
+ el.querySelectorAll('tr[data-href]').forEach((tr) => {
+ const go = () => location.assign(tr.dataset.href);
+ tr.addEventListener('click', go);
+ tr.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ go();
+ }
+ });
+ });
}
// ── Filters ─────────────────────────────────────────────────────────────────────
diff --git a/src/yields.js b/src/yields.js
index b59bf4a2b..dbe615ecb 100644
--- a/src/yields.js
+++ b/src/yields.js
@@ -243,8 +243,8 @@ function rowHtml(p) {
${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="left hide-md yl-project">${p.project ? `<a class="yl-link" href="/protocol/${encodeURIComponent(p.project)}">${esc(p.project)}</a>` : '—'}</td>
+ <td class="left hide-sm yl-chain">${p.chain ? `<a class="yl-link" href="/chain/${encodeURIComponent(p.chain)}">${esc(p.chain)}</a>` : '—'}</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>
@@ -308,9 +308,14 @@ function renderTable() {
el.querySelectorAll('tr.yl-row').forEach((tr) => {
const toggle = () => toggleRow(tr.dataset.pool);
- tr.addEventListener('click', toggle);
+ tr.addEventListener('click', (e) => {
+ // A click on the project/chain cross-link navigates; it must not
+ // also toggle the pool's history drawer.
+ if (e.target.closest('a.yl-link')) return;
+ toggle();
+ });
tr.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' || e.key === ' ') {
+ if ((e.key === 'Enter' || e.key === ' ') && !e.target.closest('a.yl-link')) {
e.preventDefault();
toggle();
}
diff --git a/vercel.json b/vercel.json
index 4299ba2f4..0bf33260c 100644
--- a/vercel.json
+++ b/vercel.json
@@ -964,6 +964,10 @@
"src": "/markets/archive/?",
"dest": "/news-archive.html"
},
+ {
+ "src": "/markets/trending/?",
+ "dest": "/markets-trending.html"
+ },
{
"src": "/fear-greed/?",
"dest": "/fear-greed.html"
@@ -1016,6 +1020,18 @@
"src": "/yields/?",
"dest": "/yields.html"
},
+ {
+ "src": "/fees/?",
+ "dest": "/fees.html"
+ },
+ {
+ "src": "/dex-volumes/?",
+ "dest": "/dex-volumes.html"
+ },
+ {
+ "src": "/hacks/?",
+ "dest": "/hacks.html"
+ },
{
"src": "/exchange/([a-z0-9_-]{1,60})/?",
"dest": "/exchange.html"
@@ -1024,6 +1040,18 @@
"src": "/category/([a-z0-9-]{1,80})/?",
"dest": "/category.html"
},
+ {
+ "src": "/protocol/([a-z0-9.-]{1,80})/?",
+ "dest": "/protocol.html"
+ },
+ {
+ "src": "/chain/([A-Za-z0-9 ._%-]{1,40})/?",
+ "dest": "/chain.html"
+ },
+ {
+ "src": "/stablecoin/([0-9]{1,6})/?",
+ "dest": "/stablecoin.html"
+ },
{
"src": "/bnb/?",
"dest": "/bnb.html"
diff --git a/vite.config.js b/vite.config.js
index 36fa43c7d..5c93a30ec 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -485,6 +485,13 @@ const appConfig = {
exchange: resolve(__dirname, 'pages/exchange.html'),
category: resolve(__dirname, 'pages/category.html'),
yields: resolve(__dirname, 'pages/yields.html'),
+ protocol: resolve(__dirname, 'pages/protocol.html'),
+ chain: resolve(__dirname, 'pages/chain.html'),
+ stablecoin: resolve(__dirname, 'pages/stablecoin.html'),
+ 'markets-trending': resolve(__dirname, 'pages/markets-trending.html'),
+ fees: resolve(__dirname, 'pages/fees.html'),
+ 'dex-volumes': resolve(__dirname, 'pages/dex-volumes.html'),
+ hacks: resolve(__dirname, 'pages/hacks.html'),
bnb: resolve(__dirname, 'pages/bnb.html'),
'bnb-latency': resolve(__dirname, 'pages/bnb-latency.html'),
vault: resolve(__dirname, 'pages/vault.html'),
@@ -1077,6 +1084,14 @@ support: resolve(__dirname, 'pages/support.html'),
'/stablecoins/': resolve(root, 'pages/stablecoins.html'),
'/yields': resolve(root, 'pages/yields.html'),
'/yields/': resolve(root, 'pages/yields.html'),
+ '/fees': resolve(root, 'pages/fees.html'),
+ '/fees/': resolve(root, 'pages/fees.html'),
+ '/dex-volumes': resolve(root, 'pages/dex-volumes.html'),
+ '/dex-volumes/': resolve(root, 'pages/dex-volumes.html'),
+ '/hacks': resolve(root, 'pages/hacks.html'),
+ '/hacks/': resolve(root, 'pages/hacks.html'),
+ '/markets/trending': resolve(root, 'pages/markets-trending.html'),
+ '/markets/trending/': resolve(root, 'pages/markets-trending.html'),
'/bnb': resolve(root, 'pages/bnb.html'),
'/bnb/': resolve(root, 'pages/bnb.html'),
'/bnb-latency': resolve(root, 'pages/bnb-latency.html'),
@@ -1510,6 +1525,15 @@ support: resolve(__dirname, 'pages/support.html'),
// /category/:id → crypto category detail page
else if (!filePath && /^\/category\/[a-z0-9-]{1,80}\/?$/.test(path))
filePath = resolve(root, 'pages/category.html');
+ // /protocol/:slug → DeFi protocol detail page
+ else if (!filePath && /^\/protocol\/[a-z0-9.-]{1,80}\/?$/i.test(path))
+ filePath = resolve(root, 'pages/protocol.html');
+ // /chain/:name → chain TVL detail page
+ else if (!filePath && /^\/chain\/[A-Za-z0-9 ._%-]{1,40}\/?$/.test(path))
+ filePath = resolve(root, 'pages/chain.html');
+ // /stablecoin/:id → stablecoin detail page
+ else if (!filePath && /^\/stablecoin\/[0-9]{1,6}\/?$/.test(path))
+ filePath = resolve(root, 'pages/stablecoin.html');
// /@<handle> → public live profile page
else if (!filePath && /^\/@[a-z0-9_-]{3,30}\/?$/i.test(path))
filePath = resolve(root, 'pages/handle.html');