Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(derivatives): give every perpetual contract its own page at /derivative/:venue/:symbol
ni3aa492c55d56d2
diff --git a/api/_lib/derivative-slug.js b/api/_lib/derivative-slug.jsnew file mode 100644index 000000000..694a80db9--- /dev/null+++ b/api/_lib/derivative-slug.js@@ -0,0 +1,71 @@+// Perpetual-contract URL slugs, shared by every surface that links to+// /derivative/:venue/:symbol.+//+// A contract is addressed by its venue id plus the venue's own symbol, and+// those symbols are not path-safe: a handful arrive as "ETH/USDT". A+// percent-encoded %2F is decoded by proxies before routing, which splits the+// path into an extra segment and 404s the route, so the slash is swapped for+// "~" instead. "~" is an unreserved URL character (no encoding needed, no+// double-encoding trap) and appears in no venue symbol the derivatives feed+// carries.+//+// A symbol that falls outside the accepted charset returns null rather than a+// mangled slug: the caller renders plain text instead of a link that would+// 404.+//+// This module exists twice and the two copies must stay byte-identical:+// src/shared/derivative-slug.js (browser) and api/_lib/derivative-slug.js+// (server). The server build context excludes src/, so it cannot import the+// browser copy; tests/api/derivative-slug.test.js compares the two files and+// fails the moment they drift.++// Venue ids come from CoinGecko's derivatives-exchange namespace.+export const VENUE_ID_RE = /^[a-z0-9_-]{1,60}$/i;+// Exchange symbols in the feed use letters, digits, "_", "-", "/", "." and ":".+export const SYMBOL_RE = /^[A-Za-z0-9._:/-]{1,48}$/;+// What a symbol looks like once the slash is folded into "~".+export const SYMBOL_SLUG_RE = /^[A-Za-z0-9._:~-]{1,48}$/;++/**+ * Fold a venue symbol into a path-safe slug.+ * @param {string} symbol e.g. "ETH/USDT"+ * @returns {string|null} e.g. "ETH~USDT", or null when the symbol is unusable+ */+export function contractSlug(symbol) {+ const s = String(symbol ?? '').trim();+ if (!s || !SYMBOL_RE.test(s) || s.includes('~')) return null;+ return s.replace(/\//g, '~');+}++/**+ * Recover the venue symbol from a path slug.+ * @param {string} slug e.g. "ETH~USDT"+ * @returns {string|null} e.g. "ETH/USDT", or null when the slug is unusable+ */+export function symbolFromSlug(slug) {+ let s = String(slug ?? '').trim();+ // Tolerate a still-encoded segment: some clients hand back "%7E" or "%2F".+ if (s.includes('%')) {+ try {+ s = decodeURIComponent(s);+ } catch {+ return null;+ }+ }+ if (!s) return null;+ const symbol = s.replace(/~/g, '/');+ return SYMBOL_RE.test(symbol) ? symbol : null;+}++/**+ * The canonical detail path for one contract.+ * @param {string} venueId CoinGecko derivatives-exchange id+ * @param {string} symbol venue symbol+ * @returns {string|null} "/derivative/<venue>/<slug>", or null when unusable+ */+export function derivativePath(venueId, symbol) {+ const id = String(venueId ?? '').trim();+ const slug = contractSlug(symbol);+ if (!id || !VENUE_ID_RE.test(id) || !slug) return null;+ return `/derivative/${id.toLowerCase()}/${slug}`;+}diff --git a/api/_lib/derivative-venues.js b/api/_lib/derivative-venues.jsnew file mode 100644index 000000000..fdcc9c748--- /dev/null+++ b/api/_lib/derivative-venues.js@@ -0,0 +1,89 @@+// The derivatives-venue directory, shared by /api/coin/derivatives and+// /api/coin/derivative.+//+// CoinGecko's `/derivatives` ticker feed names a venue only by its display+// name ("WhiteBIT Futures"), while every venue-scoped endpoint and every+// internal route addresses it by id ("whitebit_futures"). Without that bridge+// a perp row cannot link anywhere: it knows the market it trades on but not+// how to name it. `/derivatives/exchanges` carries both, so this module keeps+// one cached copy of the full directory and exposes the name to id map built+// from it.+//+// The page-ranked table on /derivatives fetches its own 50-row slice; this+// directory is deliberately the FULL list (per_page=250 covers every venue+// CoinGecko tracks, roughly 110 today), because a ticker from a venue outside+// the top 50 by open interest still needs a working link.++import { geckoFetch } from './coingecko.js';++const TTL_MS = 300_000;+const PATH = '/derivatives/exchanges?order=open_interest_btc_desc&per_page=250';++let _cache = null; // { venues, byName, expiresAt }++const num = (v) => {+ if (v == null || v === '') return null;+ const n = typeof v === 'number' ? v : Number(v);+ return Number.isFinite(n) ? n : null;+};++/** Venue display names are compared case- and whitespace-insensitively. */+export function venueNameKey(name) {+ return String(name ?? '')+ .trim()+ .replace(/\s+/g, ' ')+ .toLowerCase();+}++/**+ * The full derivatives-venue directory plus a display-name lookup.+ * Throws when the upstream is unreachable and nothing is cached; callers that+ * only want richer links should catch and degrade.+ * @returns {Promise<{ venues: object[], byName: Map<string, object> }>}+ */+export async function fetchDerivativeVenues() {+ const now = Date.now();+ if (_cache && _cache.expiresAt > now) return { venues: _cache.venues, byName: _cache.byName };++ const raw = await geckoFetch(PATH, { ttlMs: TTL_MS });+ const rows = Array.isArray(raw) ? raw : [];+ const venues = rows+ .filter((e) => e && e.id)+ .map((e) => ({+ id: String(e.id),+ name: (e.name || e.id).trim(),+ image: e.image || null,+ open_interest_btc: num(e.open_interest_btc),+ trade_volume_24h_btc: num(e.trade_volume_24h_btc),+ perpetual_pairs: num(e.number_of_perpetual_pairs),+ futures_pairs: num(e.number_of_futures_pairs),+ year_established: num(e.year_established),+ country: e.country || null,+ }));++ if (!venues.length) throw new Error('empty derivatives exchange directory');++ const byName = new Map();+ for (const v of venues) {+ const key = venueNameKey(v.name);+ if (key && !byName.has(key)) byName.set(key, v);+ }++ _cache = { venues, byName, expiresAt: now + TTL_MS };+ return { venues, byName };+}++/**+ * Resolve a ticker's `market` display name to its venue id.+ * Returns null instead of throwing: a missing id costs a link, not a page.+ * @param {string} name+ * @returns {Promise<string|null>}+ */+export async function venueIdForName(name) {+ try {+ const { byName } = await fetchDerivativeVenues();+ return byName.get(venueNameKey(name))?.id ?? null;+ } catch {+ return null;+ }+}diff --git a/api/coin/derivative.js b/api/coin/derivative.jsnew file mode 100644index 000000000..c139dba37--- /dev/null+++ b/api/coin/derivative.js@@ -0,0 +1,393 @@+// GET /api/coin/derivative?venue=<exchange-id>&symbol=<venue-symbol>+// ---------------------------------------------------------------------------+// One perpetual contract in full, powering the /derivative/:venue/:symbol+// detail page that the /derivatives table now links into. The table row is a+// summary (price, funding, open interest, volume); this endpoint answers the+// questions the row raises: is this contract trading above or below its own+// index, what does its funding cost annualized, how big is it next to the rest+// of the venue, and where does the same underlying fund cheaper somewhere+// else.+//+// Four upstream reads, all shared with pages that already ran them, so a warm+// instance usually serves this from cache:+// 1. /derivatives/exchanges/{venue}?include_tickers=unexpired+// The contract itself plus every other contract on the venue, and the+// venue profile (country, year, description, open interest).+// 2. /derivatives?include_tickers=unexpired+// Same feed /derivatives renders, reused here to price the SAME index on+// every other venue: the cross-venue funding table.+// 3. The venue directory (api/_lib/derivative-venues.js) for display-name to+// id resolution, so each peer row links to its own detail page.+// 4. /coins/markets for the underlying asset (spot price, market cap, rank),+// which links the contract back to /coin/:id.+//+// Only read 1 is load-bearing. Reads 2 to 4 fail soft to null/empty: a+// cross-venue outage must not take down the contract page.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { geckoFetch, htmlToText } from '../_lib/coingecko.js';+import { fetchDerivativeVenues, venueNameKey } from '../_lib/derivative-venues.js';+import { VENUE_ID_RE, SYMBOL_RE, contractSlug } from '../_lib/derivative-slug.js';++const VENUE_TTL_MS = 120_000;+const FEED_TTL_MS = 60_000;+const ASSET_TTL_MS = 120_000;++// Most venues settle funding three times a day (every 8h). CoinGecko does not+// publish the interval, so the annualized figure is an 8h-interval estimate and+// every surface that shows it says so.+const FUNDING_PERIODS_PER_YEAR = 3 * 365;++// How many rows each secondary table carries. Both are ranked by 24h volume,+// so the cut keeps the liquid end.+const MAX_PEERS = 40;+const MAX_VENUE_CONTRACTS = 12;++const num = (v) => {+ if (v == null || v === '') return null;+ const n = typeof v === 'number' ? v : Number(v);+ return Number.isFinite(n) ? n : null;+};+const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);+const httpUrl = (v) => (typeof v === 'string' && /^https?:\/\//.test(v) ? v : null);++// CoinGecko funding_rate is a percentage for one funding interval (0.01 means+// 0.01%, not 1%). Annualizing assumes the 8h schedule above.+function fundingApr(rate) {+ return rate == null ? null : rate * FUNDING_PERIODS_PER_YEAR;+}++// bid_ask_spread on the derivatives namespace is a ratio, not a percentage.+function spreadPct(v) {+ const n = num(v);+ return n == null ? null : n * 100;+}++// CoinGecko reports `index_basis_percentage` as the INDEX's premium over the+// contract ((index - last) / last). Traders read basis the other way round: a+// contract trading above the thing it settles against is a positive basis, and+// that is the sign that agrees with funding. So the value is derived straight+// from the two prices when both are present, and the upstream field is negated+// as the fallback.+function contractBasisPct(t) {+ const last = num(t.last);+ const index = num(t.index);+ if (last != null && index != null && index !== 0) return ((last - index) / index) * 100;+ const upstream = num(t.index_basis_percentage);+ return upstream == null ? null : -upstream;+}++function shapeContract(t, venueId) {+ const symbol = str(t.symbol);+ const base = str(t.base);+ const target = str(t.target);+ const funding = num(t.funding_rate);+ return {+ symbol,+ slug: symbol ? contractSlug(symbol) : null,+ base,+ target,+ pair: base && target ? `${base}/${target}` : symbol,+ venue_id: venueId,+ contract_type: str(t.contract_type) || 'perpetual',+ coin_id: str(t.coin_id),+ price: num(t.last),+ index: num(t.index),+ basis_pct: contractBasisPct(t),+ change_24h: num(t.h24_percentage_change),+ funding_rate: funding,+ funding_apr: fundingApr(funding),+ open_interest_usd: num(t.open_interest_usd),+ volume_24h_usd: num(t.converted_volume?.usd),+ volume_24h_base: num(t.h24_volume),+ spread_pct: spreadPct(t.bid_ask_spread),+ last_traded_at: num(t.last_traded),+ expired_at: t.expired_at ?? null,+ trade_url: httpUrl(t.trade_url),+ };+}++// A row from the cross-venue /derivatives feed. Thinner than shapeContract:+// that feed carries no base/target, spread or index.+function shapePeer(t, venue) {+ const symbol = str(t.symbol);+ const funding = num(t.funding_rate);+ return {+ venue_id: venue?.id ?? null,+ venue_name: str(t.market) || venue?.name || 'Unknown',+ image: venue?.image ?? null,+ symbol,+ slug: symbol ? contractSlug(symbol) : null,+ price: num(t.price ?? t.last),+ change_24h: num(t.price_percentage_change_24h ?? t.h24_percentage_change),+ funding_rate: funding,+ funding_apr: fundingApr(funding),+ open_interest_usd: num(t.open_interest),+ volume_24h_usd: num(t.volume_24h),+ current: false,+ };+}++function median(values) {+ if (!values.length) return null;+ const s = [...values].sort((a, b) => a - b);+ const mid = s.length >> 1;+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;+}++// A popular index lists on well over a hundred venues, most of them thin. The+// extremes of that full set are noise: a DEX doing four figures a day sets the+// widest funding and the widest price every single time. Anything presented as+// somewhere a trader could actually act (best venue to hold a long, best venue+// to hold a short, how far quotes disagree) is drawn from venues clearing at+// least this much in 24h volume; the aggregate totals and shares still count+// every venue.+const LIQUID_VOLUME_FLOOR_USD = 1_000_000;++function pick(peer) {+ return peer+ ? {+ venue_id: peer.venue_id,+ venue_name: peer.venue_name,+ symbol: peer.symbol,+ slug: peer.slug,+ funding_rate: peer.funding_rate,+ funding_apr: peer.funding_apr,+ }+ : null;+}++// Everything the cross-venue table needs to be an answer rather than a list:+// where this contract's funding sits against the field, how much of the+// underlying's open interest and volume it holds, and how far the venues+// disagree on price.+function summarizePeers(peers, current) {+ if (!peers.length) return null;+ const liquid = peers.filter((p) => (p.volume_24h_usd ?? 0) >= LIQUID_VOLUME_FLOOR_USD);+ const fundings = liquid.map((p) => p.funding_rate).filter((v) => v != null);+ const prices = liquid.map((p) => p.price).filter((v) => v != null && v > 0);+ const totalOi = peers.reduce((s, p) => s + (p.open_interest_usd ?? 0), 0);+ const totalVol = peers.reduce((s, p) => s + (p.volume_24h_usd ?? 0), 0);++ const byFunding = liquid.filter((p) => p.funding_rate != null);+ const cheapestLong = byFunding.length+ ? byFunding.reduce((a, b) => (b.funding_rate < a.funding_rate ? b : a))+ : null;+ const richestShort = byFunding.length+ ? byFunding.reduce((a, b) => (b.funding_rate > a.funding_rate ? b : a))+ : null;++ const priceMin = prices.length ? Math.min(...prices) : null;+ const priceMax = prices.length ? Math.max(...prices) : null;++ const rankBy = (key) => {+ const value = current?.[key];+ if (value == null) return null;+ return peers.filter((p) => (p[key] ?? -Infinity) > value).length + 1;+ };++ return {+ venues: peers.length,+ liquid_venues: liquid.length,+ liquid_floor_usd: LIQUID_VOLUME_FLOOR_USD,+ funding_min: fundings.length ? Math.min(...fundings) : null,+ funding_max: fundings.length ? Math.max(...fundings) : null,+ funding_median: median(fundings),+ funding_spread: fundings.length ? Math.max(...fundings) - Math.min(...fundings) : null,+ cheapest_long: pick(cheapestLong),+ richest_short: pick(richestShort),+ price_min: priceMin,+ price_max: priceMax,+ price_dispersion_pct: priceMin && priceMax ? ((priceMax - priceMin) / priceMin) * 100 : null,+ total_open_interest_usd: totalOi || null,+ total_volume_24h_usd: totalVol || null,+ oi_share_pct: totalOi && current?.open_interest_usd != null ? (current.open_interest_usd / totalOi) * 100 : null,+ vol_share_pct: totalVol && current?.volume_24h_usd != null ? (current.volume_24h_usd / totalVol) * 100 : null,+ oi_rank: rankBy('open_interest_usd'),+ vol_rank: rankBy('volume_24h_usd'),+ };+}++// The same underlying on every other venue, ranked by 24h volume. The feed+// keys venues by display name, so each row is resolved back to an id through+// the venue directory in order to link to its own detail page.+async function buildPeers(indexId, contract, venueName) {+ if (!indexId) return { peers: [], stats: null };++ let rows = [];+ try {+ const raw = await geckoFetch('/derivatives?include_tickers=unexpired', { ttlMs: FEED_TTL_MS });+ rows = Array.isArray(raw) ? raw : [];+ } catch {+ return { peers: [], stats: null };+ }++ let byName = new Map();+ try {+ ({ byName } = await fetchDerivativeVenues());+ } catch {+ // Names without ids still render; they just do not link anywhere.+ }++ const wantedVenue = venueNameKey(venueName);+ const peers = rows+ .filter((t) => t && t.contract_type === 'perpetual' && t.index_id === indexId)+ .map((t) => shapePeer(t, byName.get(venueNameKey(t.market))))+ .sort((a, b) => (b.volume_24h_usd ?? 0) - (a.volume_24h_usd ?? 0));++ for (const p of peers) {+ if (venueNameKey(p.venue_name) === wantedVenue && p.symbol === contract.symbol) {+ p.current = true;+ // The venue-scoped read is the fresher of the two feeds for this one+ // contract, so the row the visitor is standing on shows those numbers.+ p.price = contract.price ?? p.price;+ p.funding_rate = contract.funding_rate ?? p.funding_rate;+ p.funding_apr = fundingApr(p.funding_rate);+ p.open_interest_usd = contract.open_interest_usd ?? p.open_interest_usd;+ p.volume_24h_usd = contract.volume_24h_usd ?? p.volume_24h_usd;+ }+ }++ const stats = summarizePeers(peers, contract);+ return { peers: peers.slice(0, MAX_PEERS), stats };+}++// Spot market data for the contract's underlying, so the page can put the mark+// price next to the asset it tracks and link through to /coin/:id.+async function buildIndexAsset(coinId) {+ if (!coinId) return null;+ try {+ const raw = await geckoFetch(+ `/coins/markets?vs_currency=usd&ids=${encodeURIComponent(coinId)}&price_change_percentage=24h&sparkline=false`,+ { ttlMs: ASSET_TTL_MS },+ );+ const row = Array.isArray(raw) ? raw[0] : null;+ if (!row) return null;+ return {+ coin_id: str(row.id),+ name: str(row.name),+ symbol: str(row.symbol)?.toUpperCase() ?? null,+ image: httpUrl(row.image),+ price_usd: num(row.current_price),+ change_24h: num(row.price_change_percentage_24h),+ market_cap: num(row.market_cap),+ market_cap_rank: num(row.market_cap_rank),+ volume_24h: num(row.total_volume),+ high_24h: num(row.high_24h),+ low_24h: num(row.low_24h),+ ath: num(row.ath),+ ath_change_pct: num(row.ath_change_percentage),+ };+ } catch {+ return null;+ }+}++/**+ * Assemble the full contract payload.+ * Throws with `status` 404 when the venue or the symbol is unknown upstream.+ */+export async function buildDerivativeContract(venueId, symbol) {+ const detail = await geckoFetch(+ `/derivatives/exchanges/${encodeURIComponent(venueId)}?include_tickers=unexpired`,+ { ttlMs: VENUE_TTL_MS },+ );++ const tickers = Array.isArray(detail?.tickers) ? detail.tickers : [];+ const wanted = symbol.toLowerCase();+ const raw = tickers.find((t) => String(t?.symbol ?? '').toLowerCase() === wanted);+ if (!raw) {+ const err = new Error(`no contract ${symbol} on ${venueId}`);+ err.status = 404;+ throw err;+ }++ const contract = shapeContract(raw, venueId);+ const venueName = (detail.name || venueId).trim();+ const venue = {+ id: venueId,+ name: venueName,+ image: httpUrl(detail.image),+ url: httpUrl(detail.url),+ description: detail.description ? htmlToText(detail.description) : null,+ country: str(detail.country),+ year_established: num(detail.year_established),+ open_interest_btc: num(detail.open_interest_btc),+ trade_volume_24h_btc: num(detail.trade_volume_24h_btc),+ perpetual_pairs: num(detail.number_of_perpetual_pairs),+ futures_pairs: num(detail.number_of_futures_pairs),+ contracts_listed: tickers.length,+ };++ // Everything else the venue lists, ranked by volume, minus this contract.+ const venueContracts = tickers+ .filter((t) => t && String(t.symbol ?? '').toLowerCase() !== wanted)+ .map((t) => shapeContract(t, venueId))+ .sort((a, b) => (b.volume_24h_usd ?? 0) - (a.volume_24h_usd ?? 0))+ .slice(0, MAX_VENUE_CONTRACTS);++ const venueOi = tickers.reduce((s, t) => s + (num(t.open_interest_usd) ?? 0), 0);+ const venueVol = tickers.reduce((s, t) => s + (num(t.converted_volume?.usd) ?? 0), 0);+ contract.venue_oi_share_pct =+ venueOi && contract.open_interest_usd != null ? (contract.open_interest_usd / venueOi) * 100 : null;+ contract.venue_vol_share_pct =+ venueVol && contract.volume_24h_usd != null ? (contract.volume_24h_usd / venueVol) * 100 : null;++ const [{ peers, stats }, indexAsset] = await Promise.all([+ buildPeers(contract.base, contract, venueName),+ buildIndexAsset(contract.coin_id),+ ]);++ return {+ venue,+ contract,+ index: indexAsset,+ peers,+ peer_stats: stats,+ venue_contracts: venueContracts,+ funding_periods_per_year: FUNDING_PERIODS_PER_YEAR,+ updated_at: Date.now(),+ };+}++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 venue = (params.get('venue') || '').trim().toLowerCase();+ const symbol = (params.get('symbol') || '').trim();++ if (!VENUE_ID_RE.test(venue)) {+ return error(res, 400, 'bad_request', 'venue must be a derivatives exchange id');+ }+ if (!SYMBOL_RE.test(symbol)) {+ return error(res, 400, 'bad_request', 'symbol must be a venue contract symbol');+ }++ try {+ const payload = await buildDerivativeContract(venue, symbol);+ return json(res, 200, payload, {+ 'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300',+ });+ } catch (err) {+ if (err?.status === 404) {+ return error(+ res,+ 404,+ 'not_found',+ `no active contract "${symbol}" on "${venue}"`,+ );+ }+ return error(+ res,+ 502,+ 'upstream_error',+ 'contract data is unavailable right now, please retry shortly',+ );+ }+});diff --git a/api/coin/derivatives.js b/api/coin/derivatives.jsindex 842a33720..f45e16964 100644--- a/api/coin/derivatives.js+++ b/api/coin/derivatives.js@@ -23,6 +23,8 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { geckoFetch } from '../_lib/coingecko.js';import { fetchHyperliquidPerps } from '../_lib/hyperliquid.js';import { fetchDeribitSummary } from '../_lib/deribit.js';+import { fetchDerivativeVenues, venueNameKey } from '../_lib/derivative-venues.js';+import { contractSlug } from '../_lib/derivative-slug.js';let _cache = null; // { value, expiresAt }let _exCache = null; // { value, expiresAt }@@ -35,6 +37,25 @@ const num = (v) => {return Number.isFinite(n) ? n : null;};+// Each row's `market` is a display name; the /derivative/:venue/:symbol detail+// page is addressed by venue id plus a path-safe symbol slug. Resolving both+// here is what makes a perp row clickable: the client links the row only when+// the pair came back, so an unresolved venue costs a link, never a row. The+// backup Hyperliquid path deliberately skips this, since its symbols are its+// own and are not guaranteed to match the ones CoinGecko lists for that venue.+async function attachVenueLinks(tickers) {+ let byName = new Map();+ try {+ ({ byName } = await fetchDerivativeVenues());+ } catch {+ return; // rows render unlinked rather than not at all+ }+ for (const t of tickers) {+ t.venue_id = byName.get(venueNameKey(t.market))?.id ?? null;+ t.slug = t.symbol ? contractSlug(t.symbol) : null;+ }+}+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402// market-derivatives endpoint sells the same perp table this page renders.//@@ -70,6 +91,7 @@ export async function buildDerivativeTickers() {})).sort((a, b) => (b.volume_24h ?? 0) - (a.volume_24h ?? 0)).slice(0, 100);+ await attachVenueLinks(tickers);} catch {// fall through to the Hyperliquid backup below}diff --git a/pages/derivative.html b/pages/derivative.htmlnew file mode 100644index 000000000..b54456a28--- /dev/null+++ b/pages/derivative.html@@ -0,0 +1,114 @@+<!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>Perpetual Futures Contract · three.ws</title>+ <meta+ name="description"+ content="One perpetual futures contract in full: mark price against its index, funding rate and what it costs on a real position, open interest, spread, and the same underlying priced on every other venue. Real CoinGecko data, no API key."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/derivatives" />+ <meta property="og:title" content="Perpetual Futures Contract · three.ws" />+ <meta+ property="og:description"+ content="Mark price, basis, funding cost, open interest and cross-venue comparison for a single perpetual futures contract."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Perpetual+Futures+Contract&d=Mark+price%2C+basis%2C+funding+cost%2C+open+interest+and+a+cross-venue+funding+comparison+for+one+perpetual+contract&p=%2Fderivatives"+ />+ <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="Perpetual Futures Contract · three.ws" />+ <meta+ name="twitter:description"+ content="Mark price, basis, funding cost, open interest and cross-venue comparison for a single perpetual futures contract."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Perpetual+Futures+Contract&d=Mark+price%2C+basis%2C+funding+cost%2C+open+interest+and+a+cross-venue+funding+comparison+for+one+perpetual+contract&p=%2Fderivatives"+ />+ <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/derivative-page.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/derivatives" />+ <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="Perpetual futures contract detail - three.ws" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container" id="dc-main" aria-busy="true">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/markets">Markets</a>+ <span class="sep" aria-hidden="true">/</span>+ <a href="/derivatives">Derivatives</a>+ <span class="sep" aria-hidden="true">/</span>+ <a href="/derivatives" id="dc-crumb-venue">…</a>+ <span class="sep" aria-hidden="true">/</span>+ <span class="here" id="dc-crumb-symbol">…</span>+ </nav>++ <!-- Venue logo, symbol, mark price, 24h move, trade link. -->+ <section id="dc-hero" aria-label="Contract overview"></section>++ <!-- Mark, index, basis, funding, open interest, volume, spread. -->+ <section id="dc-stats" aria-label="Contract statistics"></section>++ <!-- Funding rate turned into the cost of holding a real position. -->+ <section id="dc-funding" aria-label="Funding cost"></section>++ <!-- Spot price history for the underlying this contract tracks. -->+ <section id="dc-chart" aria-label="Underlying price chart"></section>++ <!-- The same underlying on every other venue, with the funding spread. -->+ <section id="dc-peers" class="cv-section" aria-label="Cross-venue comparison"></section>++ <!-- Share of the venue, plus the venue's other contracts. -->+ <section id="dc-venue" class="cv-section" aria-label="Venue context"></section>++ <!-- The underlying asset's spot market. -->+ <section id="dc-asset" class="cv-section" aria-label="Underlying asset"></section>++ <section id="dc-related" aria-label="Related pages"></section>++ <p class="cv-updated" id="dc-updated" hidden></p>+ </main>++ <script type="module" src="/src/derivative-page.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/pages/derivatives.html b/pages/derivatives.htmlindex 5ee844cec..554afef2d 100644--- a/pages/derivatives.html+++ b/pages/derivatives.html@@ -98,6 +98,11 @@interest, and 24h volume for every contract. Positive funding means longs payshorts; negative means shorts pay longs.</p>+ <p class="cv-sub" style="margin-top:-1.25rem" data-i18n="derivatives.open_any_contract_for_its_full_detail_page">+ Open any contract for its full detail page: basis against its own index, what+ the funding rate costs on a position you size yourself, and the same underlying+ priced on every other venue.+ </p><!-- Header stat cards. Hydrated by src/derivatives.js. --><sectiondiff --git a/src/derivative-page.css b/src/derivative-page.cssnew file mode 100644index 000000000..b34dd7c14--- /dev/null+++ b/src/derivative-page.css@@ -0,0 +1,565 @@+/*+ * /derivative/:venue/:symbol - one perpetual futures contract in full.+ * Builds on the shared coin-pages design system (src/coin-pages.css): same+ * tokens, same surfaces, same mono numerals. Everything here is the structure+ * that page needs and the others do not: the contract hero, the funding-cost+ * calculator, the cross-venue comparison callouts, and the share meters.+ */++/* ── Hero ───────────────────────────────────────────────────────────────── */++.dc-hero {+ display: grid;+ gap: 1.5rem;+ grid-template-columns: 1fr;+ align-items: start;+ margin-bottom: 2rem;+}+@media (min-width: 900px) {+ .dc-hero {+ grid-template-columns: minmax(0, 1fr) auto;+ }+}++.dc-hero-id {+ display: flex;+ gap: 1rem;+ align-items: flex-start;+ min-width: 0;+}++.dc-logo {+ width: 56px;+ height: 56px;+ border-radius: var(--cv-radius-lg);+ object-fit: cover;+ background: var(--cv-surface-3);+ flex-shrink: 0;+}+.dc-logo-fallback {+ display: block;+}++.dc-title-row {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ flex-wrap: wrap;+}+.dc-symbol {+ font-family: var(--cv-font-mono);+ font-size: 1.625rem;+ line-height: 1.15;+ font-weight: 700;+ letter-spacing: -0.01em;+ margin: 0;+ color: var(--cv-text);+ word-break: break-word;+}+@media (min-width: 768px) {+ .dc-symbol {+ font-size: 2rem;+ }+}++.dc-venue-line {+ margin: 0.375rem 0 0;+ font-size: 0.9375rem;+ color: var(--cv-text-2);+}+.dc-venue-line a {+ color: var(--cv-text);+ font-weight: 600;+ text-decoration: none;+ border-bottom: 1px solid var(--cv-border-hover);+ transition: color var(--duration-fast, 120ms);+}+.dc-venue-line a:hover,+.dc-venue-line a:focus-visible {+ color: var(--cv-accent);+}++.dc-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+ margin-top: 0.75rem;+}+.dc-chip {+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ font-size: 0.6875rem;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ padding: 0.25rem 0.5rem;+ border-radius: 999px;+ border: 1px solid var(--cv-border);+ background: var(--cv-surface-2);+ color: var(--cv-text-2);+}+.dc-chip-perp {+ border-color: color-mix(in srgb, var(--cv-accent) 40%, var(--cv-border));+ color: var(--cv-accent);+ background: color-mix(in srgb, var(--cv-accent) 10%, transparent);+}++/* Price block, right of the identity on wide screens. */+.dc-price-box {+ min-width: 0;+}+.dc-price {+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+ font-size: 2rem;+ font-weight: 700;+ line-height: 1.1;+ margin: 0;+ color: var(--cv-text);+}+@media (min-width: 900px) {+ .dc-price-box {+ text-align: right;+ }+ .dc-price {+ font-size: 2.5rem;+ }+}+.dc-price-delta {+ margin: 0.25rem 0 0;+ font-size: 1rem;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+}+.dc-price-note {+ margin: 0.375rem 0 0;+ font-size: 0.75rem;+ color: var(--cv-text-3);+}++.dc-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ margin-top: 0.875rem;+}+@media (min-width: 900px) {+ .dc-actions {+ justify-content: flex-end;+ }+}+.dc-trade {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ padding: 0.5rem 0.875rem;+ border-radius: var(--cv-radius-md);+ background: var(--cv-accent-solid);+ color: var(--cv-on-accent);+ font-size: 0.875rem;+ font-weight: 600;+ text-decoration: none;+ transition:+ transform var(--duration-fast, 120ms),+ filter var(--duration-fast, 120ms);+}+.dc-trade:hover {+ filter: brightness(1.08);+}+.dc-trade:active {+ transform: translateY(1px);+}++/* ── Stat grid ──────────────────────────────────────────────────────────── */++/* Eight cards read as two rows of four, not seven and a widow. auto-fit does+ whatever the viewport allows and stranded a single card on its own line at+ desktop width, so the column count is set explicitly per breakpoint. */+.dc-stats {+ display: grid;+ gap: 0.75rem;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ margin-bottom: 2.5rem;+}+@media (min-width: 680px) {+ .dc-stats {+ grid-template-columns: repeat(3, minmax(0, 1fr));+ }+}+@media (min-width: 960px) {+ .dc-stats {+ grid-template-columns: repeat(4, minmax(0, 1fr));+ }+}+.dc-stat .label {+ display: flex;+ align-items: center;+ gap: 0.25rem;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ font-size: 0.6875rem;+ font-weight: 600;+}+.dc-stat .value {+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+}++/* An inline "why this matters" affordance on a stat label. */+.dc-info {+ cursor: help;+ color: var(--cv-text-3);+ font-size: 0.75rem;+ border-radius: 50%;+}+.dc-info:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++/* ── Funding panel ──────────────────────────────────────────────────────── */++.dc-panel {+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-xl);+ padding: 1.25rem;+ margin-bottom: 2.5rem;+}+@media (min-width: 768px) {+ .dc-panel {+ padding: 1.5rem;+ }+}+.dc-panel-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 0.75rem;+ flex-wrap: wrap;+ margin-bottom: 0.75rem;+}+.dc-panel-head h2 {+ margin: 0;+}+.dc-panel-note {+ margin: 0;+ font-size: 0.8125rem;+ color: var(--cv-text-3);+}++.dc-fund-verdict {+ font-size: 1rem;+ line-height: 1.55;+ color: var(--cv-text);+ margin: 0 0 1rem;+}+.dc-fund-verdict strong {+ font-weight: 700;+}++.dc-calc {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ gap: 0.75rem 1rem;+}+.dc-calc label {+ display: block;+ font-size: 0.75rem;+ color: var(--cv-text-3);+ margin-bottom: 0.25rem;+}+.dc-calc-field {+ position: relative;+ display: flex;+ align-items: center;+}+.dc-calc-field .prefix {+ position: absolute;+ left: 0.625rem;+ color: var(--cv-text-3);+ font-family: var(--cv-font-mono);+ pointer-events: none;+}+.dc-calc input {+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+ font-size: 0.9375rem;+ padding: 0.5rem 0.75rem 0.5rem 1.5rem;+ width: 11rem;+ max-width: 100%;+ border-radius: var(--cv-radius-md);+ border: 1px solid var(--cv-border);+ background: var(--cv-surface);+ color: var(--cv-text);+ transition:+ border-color var(--duration-fast, 120ms),+ box-shadow var(--duration-fast, 120ms);+}+.dc-calc input:hover {+ border-color: var(--cv-border-hover);+}+.dc-calc input:focus-visible {+ outline: none;+ border-color: var(--cv-accent);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 25%, transparent);+}+.dc-calc-out {+ display: flex;+ flex-wrap: wrap;+ gap: 1.5rem;+}+.dc-calc-out .k {+ font-size: 0.75rem;+ color: var(--cv-text-3);+ margin: 0 0 0.125rem;+}+.dc-calc-out .v {+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+ font-size: 1.125rem;+ font-weight: 700;+ margin: 0;+}++/* ── Cross-venue callouts ───────────────────────────────────────────────── */++.dc-callouts {+ display: grid;+ gap: 0.75rem;+ grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));+ margin-bottom: 1.25rem;+}+.dc-callout {+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ padding: 1rem;+}+.dc-callout .k {+ font-size: 0.6875rem;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ font-weight: 600;+ color: var(--cv-text-3);+ margin: 0 0 0.375rem;+}+.dc-callout .v {+ font-size: 1rem;+ font-weight: 700;+ margin: 0;+ color: var(--cv-text);+}+.dc-callout .v a {+ color: inherit;+ text-decoration: none;+ border-bottom: 1px solid var(--cv-border-hover);+}+.dc-callout .v a:hover,+.dc-callout .v a:focus-visible {+ color: var(--cv-accent);+}+.dc-callout .s {+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+ font-size: 0.8125rem;+ margin: 0.25rem 0 0;+ color: var(--cv-text-2);+}++/* ── Share meters ───────────────────────────────────────────────────────── */++.dc-shares {+ display: grid;+ gap: 1rem;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+}+.dc-share .top {+ display: flex;+ justify-content: space-between;+ gap: 0.5rem;+ font-size: 0.8125rem;+ margin-bottom: 0.375rem;+}+.dc-share .top .k {+ color: var(--cv-text-2);+}+.dc-share .top .v {+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+ font-weight: 700;+ color: var(--cv-text);+}+.dc-share-track {+ height: 8px;+ border-radius: 999px;+ background: var(--cv-surface-3);+ overflow: hidden;+}+.dc-share-fill {+ height: 100%;+ border-radius: 999px;+ background: var(--cv-accent);+ transition: width var(--duration-slow, 400ms) ease;+}+.dc-share .cap {+ margin: 0.375rem 0 0;+ font-size: 0.75rem;+ color: var(--cv-text-3);+}++/* ── Tables ─────────────────────────────────────────────────────────────── */++.dc-table th,+.dc-table td {+ white-space: nowrap;+}+.dc-table td.left,+.dc-table th.left {+ text-align: left;+}+.dc-venue-cell {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ min-width: 0;+}+.dc-venue-cell img {+ width: 20px;+ height: 20px;+ border-radius: 4px;+ flex-shrink: 0;+}+.dc-table a {+ color: var(--cv-text);+ text-decoration: none;+}+.dc-table a:hover,+.dc-table a:focus-visible {+ color: var(--cv-accent);+ text-decoration: underline;+}+.dc-table tr.dc-current {+ background: color-mix(in srgb, var(--cv-accent) 10%, transparent);+}+.dc-table tr.dc-current td {+ font-weight: 600;+}+.dc-here {+ display: inline-block;+ margin-left: 0.375rem;+ font-size: 0.625rem;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ padding: 0.0625rem 0.3125rem;+ border-radius: 999px;+ background: var(--cv-accent-solid);+ color: var(--cv-on-accent);+ vertical-align: middle;+}++.dc-table-note {+ margin: 0.625rem 0 0;+ font-size: 0.8125rem;+ color: var(--cv-text-3);+}++/* ── Underlying asset card ──────────────────────────────────────────────── */++.dc-asset {+ display: flex;+ gap: 1rem;+ align-items: center;+ flex-wrap: wrap;+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ padding: 1rem 1.25rem;+ text-decoration: none;+ color: inherit;+ transition:+ border-color var(--duration-base, 200ms),+ box-shadow var(--duration-base, 200ms);+ margin-bottom: 1rem;+}+.dc-asset:hover,+.dc-asset:focus-visible {+ border-color: var(--cv-border-hover);+ box-shadow: var(--cv-shadow-card-hover);+}+.dc-asset img {+ width: 40px;+ height: 40px;+ border-radius: 50%;+ flex-shrink: 0;+}+.dc-asset .nm {+ font-weight: 700;+ font-size: 1rem;+ margin: 0;+}+.dc-asset .sub {+ margin: 0.125rem 0 0;+ font-size: 0.8125rem;+ color: var(--cv-text-3);+}+.dc-asset .spot {+ margin-left: auto;+ text-align: right;+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+}+.dc-asset .spot .p {+ margin: 0;+ font-size: 1.125rem;+ font-weight: 700;+}+.dc-asset .spot .d {+ margin: 0;+ font-size: 0.8125rem;+ font-weight: 600;+}++/* ── Related links ──────────────────────────────────────────────────────── */++.dc-related {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ margin: 0 0 1.5rem;+}++/* ── Error / retry ──────────────────────────────────────────────────────── */++.dc-retry {+ font: inherit;+ font-weight: 600;+ padding: 0.5rem 0.875rem;+ border-radius: var(--cv-radius-md);+ border: 1px solid var(--cv-border);+ background: var(--cv-surface-2);+ color: var(--cv-text);+ cursor: pointer;+ transition:+ border-color var(--duration-fast, 120ms),+ background var(--duration-fast, 120ms);+}+.dc-retry:hover {+ border-color: var(--cv-border-hover);+ background: var(--cv-surface-3);+}+.dc-retry:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++@media (prefers-reduced-motion: reduce) {+ .dc-share-fill,+ .dc-trade,+ .dc-asset {+ transition: none;+ }+}diff --git a/src/derivative-page.js b/src/derivative-page.jsnew file mode 100644index 000000000..4c31608c9--- /dev/null+++ b/src/derivative-page.js@@ -0,0 +1,901 @@+// /derivative/:venue/:symbol - the detail page behind every row of+// /derivatives, part of the three.ws Markets surface.+//+// The perps table answers "what is this contract worth right now". This page+// answers the questions that row raises and a table cannot: what the funding+// rate actually costs on a position of a given size, whether the contract+// trades above or below its own index, how much of the venue and of the+// underlying's whole perp market it represents, and where the same underlying+// funds cheaper somewhere else. Data comes from /api/coin/derivative (venue+// contract feed, cross-venue perp feed, spot market data) plus /api/coin/ohlc+// for the underlying price chart. Never mocked.+//+// Mirrors the /exchange/:id detail-page pattern (src/exchange-page.js).++import {+ formatUsd,+ formatPrice,+ formatPercent,+ formatSupply,+ formatChartTick,+ escapeHtml as esc,+} from './shared/coin-format.js';+import { upstreamLogoURL, swapFailedLogos } from './shared/upstream-logo.js';+import { VENUE_ID_RE, SYMBOL_SLUG_RE, symbolFromSlug, derivativePath } from './shared/derivative-slug.js';++const $ = (id) => document.getElementById(id);+const DASH = '—';++// Venue funding is settled every 8h on almost every venue, and CoinGecko does+// not publish the schedule. Every annualized figure on this page says so.+const FUNDING_PERIODS_PER_YEAR = 3 * 365;+const DEFAULT_POSITION_USD = 10_000;++/** { venue, symbol } from the path, falling back to ?venue=&symbol= queries. */+function targetFromLocation() {+ const m = location.pathname.match(/^\/derivative\/([^/]+)\/([^/]+)\/?$/);+ if (m && VENUE_ID_RE.test(m[1]) && SYMBOL_SLUG_RE.test(decodeURIComponent(m[2]))) {+ const symbol = symbolFromSlug(m[2]);+ if (symbol) return { venue: m[1].toLowerCase(), symbol };+ }+ const q = new URLSearchParams(location.search);+ const venue = (q.get('venue') || '').trim().toLowerCase();+ const symbol = (q.get('symbol') || '').trim();+ if (VENUE_ID_RE.test(venue) && symbol) return { venue, symbol };+ return 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();+}++// ── Number formatting local to contracts ────────────────────────────────────++/** Funding is a percentage per interval and lives four decimals deep. */+function formatFunding(v) {+ if (v == null || !Number.isFinite(v)) return DASH;+ return `${v >= 0 ? '+' : ''}${v.toFixed(4)}%`;+}++/** Annualized funding, which is a whole-percent scale. */+function formatApr(v) {+ if (v == null || !Number.isFinite(v)) return DASH;+ return `${v >= 0 ? '+' : ''}${v.toFixed(2)}%`;+}++function formatBasis(v) {+ if (v == null || !Number.isFinite(v)) return DASH;+ return `${v >= 0 ? '+' : ''}${v.toFixed(3)}%`;+}++/** Exact USD with cents, for calculator output where compact units would lie. */+function formatUsdExact(n) {+ if (n == null || !Number.isFinite(n)) return DASH;+ const sign = n < 0 ? '-' : '';+ return `${sign}$${Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;+}++function formatCount(n) {+ return n == null || !Number.isFinite(n) ? DASH : n.toLocaleString('en-US');+}++function signClass(v) {+ if (v == null || !Number.isFinite(v)) return '';+ return v >= 0 ? 'cv-up' : 'cv-down';+}++/** "3 minutes ago" for a unix-seconds last-trade stamp. */+function agoFromSeconds(sec) {+ if (sec == null || !Number.isFinite(sec)) return DASH;+ const diff = Math.max(0, Date.now() - sec * 1000);+ const mins = Math.round(diff / 60_000);+ if (mins < 1) return 'just now';+ if (mins < 60) return `${mins} min ago`;+ const hrs = Math.round(mins / 60);+ if (hrs < 48) return `${hrs} hr ago`;+ return `${Math.round(hrs / 24)} d ago`;+}++// ── State ───────────────────────────────────────────────────────────────────++const state = {+ venue: null,+ symbol: null,+ payload: null,+ positionUsd: DEFAULT_POSITION_USD,+};++// ── Skeletons ───────────────────────────────────────────────────────────────++function renderSkeletons() {+ $('dc-hero').innerHTML = `+ <div class="dc-hero">+ <div class="dc-hero-id">+ <div class="cv-skel dc-logo" style="border-radius:10px"></div>+ <div style="flex:1;min-width:0">+ <div class="cv-skel" style="width:12rem;height:2rem"></div>+ <div class="cv-skel" style="width:16rem;max-width:100%;height:1.1rem;margin-top:0.6rem"></div>+ <div class="cv-skel" style="width:20rem;max-width:100%;height:1.5rem;margin-top:0.75rem"></div>+ </div>+ </div>+ <div class="cv-skel" style="width:12rem;height:4rem"></div>+ </div>`;+ $('dc-stats').innerHTML =+ '<div class="dc-stats">' ++ Array.from({ length: 8 }, () => '<div class="cv-skel" style="height:5rem"></div>').join('') ++ '</div>';+ $('dc-funding').innerHTML = '<div class="cv-skel" style="height:11rem;border-radius:12px"></div>';+ $('dc-chart').innerHTML =+ '<div class="cv-chart-panel"><div class="cv-skel" style="height:300px;border-radius:8px"></div></div>';+ $('dc-peers').innerHTML =+ '<h2 class="cv-h2">Same contract, every venue</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>';+ $('dc-venue').innerHTML = '';+ $('dc-asset').innerHTML = '';+}++// ── Hero ────────────────────────────────────────────────────────────────────++const EXT_ICON =+ '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';++function heroChips(c, v) {+ const chips = [];+ const kind = c.contract_type === 'perpetual' ? 'Perpetual' : c.contract_type;+ chips.push(`<span class="dc-chip dc-chip-perp">${esc(kind)}</span>`);+ if (c.base && c.target) chips.push(`<span class="dc-chip">${esc(c.base)} / ${esc(c.target)}</span>`);+ if (v.country) chips.push(`<span class="dc-chip">${esc(v.country)}</span>`);+ if (v.year_established != null) chips.push(`<span class="dc-chip">Est. ${esc(String(v.year_established))}</span>`);+ if (c.last_traded_at != null) chips.push(`<span class="dc-chip">Last trade ${esc(agoFromSeconds(c.last_traded_at))}</span>`);+ return `<div class="dc-chips">${chips.join('')}</div>`;+}++function renderHero(p) {+ const c = p.contract;+ const v = p.venue;+ $('dc-crumb-venue').textContent = v.name;+ $('dc-crumb-venue').href = `/exchange/${encodeURIComponent(v.id)}`;+ $('dc-crumb-symbol').textContent = c.symbol;++ const logo = v.image ? upstreamLogoURL(v.image, 56) : '';+ const basisNote =+ c.basis_pct != null+ ? `${c.basis_pct >= 0 ? 'Trading above' : 'Trading below'} its index by ${Math.abs(c.basis_pct).toFixed(3)}%`+ : 'Mark price reported by the venue';++ $('dc-hero').innerHTML = `+ <div class="dc-hero">+ <div class="dc-hero-id">+ ${+ logo+ ? `<img class="dc-logo" src="${esc(logo)}" alt="${esc(v.name)} logo" width="56" height="56" loading="eager" data-no-dark-filter />`+ : '<div class="dc-logo dc-logo-fallback" aria-hidden="true"></div>'+ }+ <div style="min-width:0">+ <div class="dc-title-row">+ <h1 class="dc-symbol">${esc(c.symbol)}</h1>+ </div>+ <p class="dc-venue-line">on <a href="/exchange/${encodeURIComponent(v.id)}">${esc(v.name)}</a></p>+ ${heroChips(c, v)}+ </div>+ </div>+ <div class="dc-price-box">+ <p class="dc-price">${esc(formatPrice(c.price))}</p>+ <p class="dc-price-delta ${signClass(c.change_24h)}">${+ c.change_24h != null ? `${c.change_24h >= 0 ? '▲' : '▼'} ${esc(formatPercent(c.change_24h))} 24h` : DASH+ }</p>+ <p class="dc-price-note">${esc(basisNote)}</p>+ <div class="dc-actions">+ ${+ c.trade_url+ ? `<a class="dc-trade" href="${esc(c.trade_url)}" target="_blank" rel="noopener noreferrer nofollow">Trade on ${esc(v.name)} ${EXT_ICON}</a>`+ : ''+ }+ </div>+ </div>+ </div>`;++ swapFailedLogos($('dc-hero'), '.dc-logo', 'dc-logo dc-logo-fallback', 'div');+}++// ── Stat cards ──────────────────────────────────────────────────────────────++function statCard({ label, value, sub, cls, tip }) {+ const info = tip+ ? ` <span class="dc-info" tabindex="0" role="img" aria-label="${esc(tip)}" title="${esc(tip)}">ⓘ</span>`+ : '';+ return `+ <div class="cv-mini-stat dc-stat">+ <p class="label">${esc(label)}${info}</p>+ <p class="value ${cls || ''}">${esc(value)}</p>+ ${sub ? `<p class="sub">${esc(sub)}</p>` : ''}+ </div>`;+}++function renderStats(p) {+ const c = p.contract;+ const s = p.peer_stats;+ const cards = [+ statCard({+ label: 'Mark price',+ value: formatPrice(c.price),+ sub: c.index != null ? `Index ${formatPrice(c.index)}` : undefined,+ tip: 'The venue’s last traded price for this contract, next to the index it settles against.',+ }),+ statCard({+ label: 'Basis',+ value: formatBasis(c.basis_pct),+ sub: c.basis_pct == null ? undefined : c.basis_pct >= 0 ? 'Contract over index' : 'Contract under index',+ cls: signClass(c.basis_pct),+ tip: 'How far the contract trades from its own index. A persistent positive basis is the market paying up to be long.',+ }),+ statCard({+ label: 'Funding rate',+ value: formatFunding(c.funding_rate),+ sub: c.funding_rate == null ? undefined : c.funding_rate >= 0 ? 'Longs pay shorts' : 'Shorts pay longs',+ cls: signClass(c.funding_rate),+ tip: 'Paid each funding interval, typically every 8 hours.',+ }),+ statCard({+ label: 'Funding, annualized',+ value: formatApr(c.funding_apr),+ sub: 'Assumes 8h intervals',+ cls: signClass(c.funding_apr),+ tip: 'The interval rate compounded out over a year at three settlements a day. An estimate: venues publish schedules, CoinGecko does not.',+ }),+ statCard({+ label: 'Open interest',+ value: formatUsd(c.open_interest_usd),+ sub: s?.oi_rank ? `#${s.oi_rank} of ${formatCount(s.venues)} venues` : undefined,+ tip: 'Notional value of every position currently open on this contract.',+ }),+ statCard({+ label: '24h volume',+ value: formatUsd(c.volume_24h_usd),+ sub: s?.vol_rank ? `#${s.vol_rank} of ${formatCount(s.venues)} venues` : undefined,+ }),+ statCard({+ label: 'Bid/ask spread',+ value: c.spread_pct != null ? `${c.spread_pct.toFixed(4)}%` : DASH,+ sub: 'Round-trip cost of crossing',+ }),+ statCard({+ label: c.base ? `24h volume in ${c.base}` : '24h volume in the underlying',+ value: c.volume_24h_base != null ? `${formatSupply(c.volume_24h_base)} ${c.base || ''}`.trim() : DASH,+ sub: 'The same tape, denominated in the asset',+ }),+ ];+ $('dc-stats').innerHTML = `<div class="dc-stats">${cards.join('')}</div>`;+}++// ── Funding cost panel ──────────────────────────────────────────────────────+// The rate on its own is abstract. This turns it into the number a trader+// actually cares about: what holding a position of a given size costs per day+// and per year at the rate quoted right now.++function fundingCost(rate, positionUsd) {+ if (rate == null || !Number.isFinite(rate) || !Number.isFinite(positionUsd)) return null;+ const perInterval = (rate / 100) * positionUsd;+ return {+ perInterval,+ perDay: perInterval * 3,+ perYear: perInterval * FUNDING_PERIODS_PER_YEAR,+ };+}++function renderFunding(p) {+ const c = p.contract;+ const el = $('dc-funding');+ if (c.funding_rate == null) {+ el.innerHTML = `+ <section class="dc-panel" aria-label="Funding">+ <div class="dc-panel-head"><h2 class="cv-h2">Funding</h2></div>+ <p class="dc-panel-note">This venue does not publish a funding rate for ${esc(c.symbol)}, so there is nothing to price here. Every other figure on this page is live.</p>+ </section>`;+ return;+ }++ const longsPay = c.funding_rate >= 0;+ const payer = longsPay ? 'Longs pay shorts' : 'Shorts pay longs';+ const cost = fundingCost(c.funding_rate, state.positionUsd);++ el.innerHTML = `+ <section class="dc-panel" aria-label="Funding cost">+ <div class="dc-panel-head">+ <h2 class="cv-h2">What funding costs</h2>+ <p class="dc-panel-note">Rate is per funding interval; daily and annual figures assume the 8h schedule most venues run.</p>+ </div>+ <p class="dc-fund-verdict">+ <strong class="${signClass(c.funding_rate)}">${esc(payer)}</strong> ${esc(formatFunding(c.funding_rate))} per interval+ on ${esc(c.symbol)}, which annualizes to <strong class="${signClass(c.funding_apr)}">${esc(formatApr(c.funding_apr))}</strong>.+ ${+ longsPay+ ? 'Holding this contract long costs you that; holding it short is paid it.'+ : 'Holding this contract short costs you that; holding it long is paid it.'+ }+ </p>+ <div class="dc-calc">+ <div>+ <label for="dc-size">Position size</label>+ <div class="dc-calc-field">+ <span class="prefix" aria-hidden="true">$</span>+ <input id="dc-size" type="number" inputmode="decimal" min="0" step="100"+ value="${state.positionUsd}" aria-label="Position size in US dollars" />+ </div>+ </div>+ <div class="dc-calc-out" id="dc-calc-out">${fundingOutput(cost, longsPay)}</div>+ </div>+ </section>`;++ const input = $('dc-size');+ input.addEventListener('input', () => {+ const raw = Number(input.value);+ state.positionUsd = Number.isFinite(raw) && raw >= 0 ? raw : 0;+ $('dc-calc-out').innerHTML = fundingOutput(+ fundingCost(c.funding_rate, state.positionUsd),+ longsPay,+ );+ });+}++function fundingOutput(cost, longsPay) {+ if (!cost) return '';+ const side = longsPay ? 'long' : 'short';+ const cell = (k, v) =>+ `<div><p class="k">${esc(k)}</p><p class="v cv-down">${esc(formatUsdExact(v))}</p></div>`;+ return [+ `<div><p class="k">Paid by the ${esc(side)}</p><p class="v">${esc(formatUsdExact(cost.perInterval))}</p></div>`,+ cell('Per day', cost.perDay),+ cell('Per year', cost.perYear),+ ].join('');+}++// ── Underlying price chart ──────────────────────────────────────────────────++const TIME_RANGES = [+ { label: '1D', days: 1 },+ { label: '7D', days: 7 },+ { label: '30D', days: 30 },+ { label: '90D', days: 90 },+ { label: '1Y', days: 365 },+];++const CHART_W = 800;+const CHART_H = 300;+const PAD = { top: 20, right: 76, bottom: 30, left: 10 };++const chartState = { days: 30, series: [], loading: false, error: false, coinId: null, name: '' };++function chartGeometry(series) {+ const vals = series.map((p) => p[1]);+ const min = Math.min(...vals);+ const max = Math.max(...vals);+ const range = max - min || Math.abs(max) || 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 = $('dc-chart');+ const { days, series, loading, error, name } = chartState;+ if (!chartState.coinId) {+ el.innerHTML = '';+ return;+ }++ const rangeBtns = TIME_RANGES.map(+ (r) =>+ `<button type="button" class="cv-range-btn" data-days="${r.days}" aria-pressed="${r.days === days}">${r.label}</button>`,+ ).join('');++ let body;+ if (loading) {+ body = '<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading chart</div>';+ } else if (error) {+ body = '<div class="cv-chart-state">Price history is temporarily unavailable. The contract figures above are live.</div>';+ } else if (series.length < 2) {+ body = '<div class="cv-chart-state">No price history available for this range.</div>';+ } else {+ const g = chartGeometry(series);+ const up = series[series.length - 1][1] >= series[0][1];+ const color = up ? 'var(--cv-chart-green)' : 'var(--cv-chart-red)';+ 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(formatPrice(v))}</text></g>`;+ }).join('');+ body = `+ <div class="cv-chart-area">+ <svg viewBox="0 0 ${CHART_W} ${CHART_H}" role="img"+ aria-label="${esc(name)} spot price over ${days} day${days > 1 ? 's' : ''}">+ <defs>+ <linearGradient id="dc-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(#dc-grad)"/>+ <path d="${g.line}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>+ <g id="dc-crosshair" hidden>+ <line id="dc-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="dc-cross-dot" r="4" fill="${color}" stroke="var(--cv-surface)" stroke-width="2"/>+ </g>+ </svg>+ <div class="cv-chart-tip" id="dc-tip" hidden>+ <p class="p cv-mono" id="dc-tip-val"></p>+ <p class="d" id="dc-tip-date"></p>+ </div>+ </div>`;+ }++ el.innerHTML = `+ <div class="cv-chart-panel">+ <div class="cv-chart-bar">+ <div class="left"><span class="title">${esc(name)} spot price, the index this contract tracks</span></div>+ <div class="cv-ranges" role="group" aria-label="Chart time range">${rangeBtns}</div>+ </div>+ ${body}+ </div>`;++ el.querySelectorAll('.cv-range-btn').forEach((btn) => {+ btn.addEventListener('click', () => {+ const dd = Number(btn.dataset.days);+ if (dd === chartState.days) return;+ chartState.days = dd;+ loadChart();+ });+ });++ wireChartPointer();+}++function wireChartPointer() {+ const svg = $('dc-chart').querySelector('svg');+ const tip = $('dc-tip');+ if (!svg || !tip || chartState.series.length < 2) return;+ const g = chartGeometry(chartState.series);+ const cross = svg.querySelector('#dc-crosshair');+ const crossLine = svg.querySelector('#dc-cross-line');+ const crossDot = svg.querySelector('#dc-cross-dot');+ const usableW = CHART_W - PAD.left - PAD.right;+ const usableH = CHART_H - PAD.top - PAD.bottom;++ function show(clientX) {+ const rect = svg.getBoundingClientRect();+ const mouseX = ((clientX - rect.left) / rect.width) * CHART_W;+ const n = chartState.series.length;+ const i = Math.max(0, Math.min(n - 1, Math.round(((mouseX - PAD.left) / usableW) * (n - 1))));+ const [ts, price] = chartState.series[i];+ const x = PAD.left + (i / (n - 1)) * usableW;+ const y = PAD.top + usableH - ((price - 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}%`;+ $('dc-tip-val').textContent = formatPrice(price);+ $('dc-tip-date').textContent = formatChartTick(ts, chartState.days);+ }+ function hide() {+ cross.setAttribute('hidden', '');+ tip.hidden = true;+ }+ svg.addEventListener('pointermove', (e) => show(e.clientX));+ svg.addEventListener('pointerleave', hide);+ svg.addEventListener('pointerdown', (e) => show(e.clientX));+}++async function loadChart() {+ if (!chartState.coinId) return;+ chartState.loading = true;+ chartState.error = false;+ renderChart();+ try {+ const data = await getJson(+ `/api/coin/ohlc?id=${encodeURIComponent(chartState.coinId)}&days=${chartState.days}`,+ );+ chartState.series = Array.isArray(data.data) ? data.data : [];+ chartState.loading = false;+ } catch {+ chartState.loading = false;+ chartState.error = true;+ chartState.series = [];+ }+ renderChart();+}++// ── Cross-venue comparison ──────────────────────────────────────────────────++function peerLink(row, label) {+ const href = row.venue_id && row.symbol ? derivativePath(row.venue_id, row.symbol) : null;+ return href ? `<a href="${esc(href)}">${esc(label)}</a>` : esc(label);+}++function renderCallouts(p) {+ const s = p.peer_stats;+ if (!s) return '';+ const cards = [];+ if (s.cheapest_long) {+ cards.push(`+ <div class="dc-callout">+ <p class="k">Cheapest venue to hold a long</p>+ <p class="v">${peerLink(s.cheapest_long, s.cheapest_long.venue_name)}</p>+ <p class="s ${signClass(s.cheapest_long.funding_rate)}">${esc(formatFunding(s.cheapest_long.funding_rate))} per interval · ${esc(s.cheapest_long.symbol || '')}</p>+ </div>`);+ }+ if (s.richest_short) {+ cards.push(`+ <div class="dc-callout">+ <p class="k">Best paid venue to hold a short</p>+ <p class="v">${peerLink(s.richest_short, s.richest_short.venue_name)}</p>+ <p class="s ${signClass(s.richest_short.funding_rate)}">${esc(formatFunding(s.richest_short.funding_rate))} per interval · ${esc(s.richest_short.symbol || '')}</p>+ </div>`);+ }+ if (s.funding_spread != null) {+ cards.push(`+ <div class="dc-callout">+ <p class="k">Funding spread across venues</p>+ <p class="v">${esc(s.funding_spread.toFixed(4))} pp</p>+ <p class="s">Median ${esc(formatFunding(s.funding_median))} · ${esc(formatCount(s.liquid_venues))} liquid venues</p>+ </div>`);+ }+ if (s.price_dispersion_pct != null) {+ cards.push(`+ <div class="dc-callout">+ <p class="k">Price dispersion</p>+ <p class="v">${esc(s.price_dispersion_pct.toFixed(2))}%</p>+ <p class="s">${esc(formatPrice(s.price_min))} to ${esc(formatPrice(s.price_max))}</p>+ </div>`);+ }+ return cards.length ? `<div class="dc-callouts">${cards.join('')}</div>` : '';+}++function peerRow(row) {+ const label = row.symbol || DASH;+ const venueHref = row.venue_id ? `/exchange/${encodeURIComponent(row.venue_id)}` : null;+ const venueCell = `<span class="dc-venue-cell">${+ row.image+ ? `<img src="${esc(upstreamLogoURL(row.image, 20))}" alt="" loading="lazy" width="20" height="20" data-no-dark-filter />`+ : ''+ }${venueHref ? `<a href="${esc(venueHref)}">${esc(row.venue_name)}</a>` : esc(row.venue_name)}</span>`;+ return `+ <tr class="${row.current ? 'dc-current' : ''}">+ <td class="left">${venueCell}</td>+ <td class="left cv-mono">${peerLink(row, label)}${row.current ? '<span class="dc-here">You are here</span>' : ''}</td>+ <td class="cv-mono">${esc(formatPrice(row.price))}</td>+ <td class="cv-mono ${signClass(row.change_24h)}">${esc(formatPercent(row.change_24h))}</td>+ <td class="cv-mono ${signClass(row.funding_rate)}">${esc(formatFunding(row.funding_rate))}</td>+ <td class="cv-mono ${signClass(row.funding_apr)}">${esc(formatApr(row.funding_apr))}</td>+ <td class="cv-mono">${esc(formatUsd(row.open_interest_usd))}</td>+ <td class="cv-mono">${esc(formatUsd(row.volume_24h_usd))}</td>+ </tr>`;+}++function renderPeers(p) {+ const el = $('dc-peers');+ const base = p.contract.base || p.contract.symbol;+ const peers = Array.isArray(p.peers) ? p.peers : [];+ const heading = `<h2 class="cv-h2">${esc(base)} perpetuals, every venue</h2>`;++ if (!peers.length) {+ el.innerHTML = `${heading}<div class="cv-empty">No other venue in the feed lists a ${esc(base)} perpetual right now. <a href="/derivatives">Browse all perpetual markets</a>.</div>`;+ return;+ }++ const s = p.peer_stats;+ const note = s+ ? `<p class="dc-table-note">Showing the ${formatCount(Math.min(peers.length, s.venues))} most active of ${formatCount(s.venues)} venues listing a ${esc(base)} perpetual. Cheapest, best-paid and dispersion figures count only venues clearing ${formatUsd(s.liquid_floor_usd)} or more in 24h volume, so a dormant book cannot set them.</p>`+ : '';++ el.innerHTML = `+ ${heading}+ ${renderCallouts(p)}+ <div class="cv-table-wrap">+ <table class="cv-table dc-table">+ <caption class="cv-sr-only">${esc(base)} perpetual contracts across venues, ranked by 24h volume</caption>+ <thead>+ <tr>+ <th scope="col" class="left">Venue</th>+ <th scope="col" class="left">Contract</th>+ <th scope="col">Price</th>+ <th scope="col">24h</th>+ <th scope="col">Funding</th>+ <th scope="col">Annualized</th>+ <th scope="col">Open interest</th>+ <th scope="col">24h volume</th>+ </tr>+ </thead>+ <tbody>${peers.map(peerRow).join('')}</tbody>+ </table>+ </div>+ ${note}`;+}++// ── Venue context: share meters and the venue's other contracts ─────────────++function shareMeter({ label, pct, caption }) {+ if (pct == null || !Number.isFinite(pct)) return '';+ const width = Math.max(1, Math.min(100, pct));+ return `+ <div class="dc-share">+ <div class="top"><span class="k">${esc(label)}</span><span class="v">${esc(pct.toFixed(2))}%</span></div>+ <div class="dc-share-track"><div class="dc-share-fill" style="width:${width.toFixed(2)}%"></div></div>+ <p class="cap">${esc(caption)}</p>+ </div>`;+}++function venueContractRow(t) {+ const href = derivativePath(t.venue_id, t.symbol);+ const label = t.symbol || DASH;+ return `+ <tr>+ <td class="left cv-mono">${href ? `<a href="${esc(href)}">${esc(label)}</a>` : esc(label)}</td>+ <td class="cv-mono">${esc(formatPrice(t.price))}</td>+ <td class="cv-mono ${signClass(t.change_24h)}">${esc(formatPercent(t.change_24h))}</td>+ <td class="cv-mono ${signClass(t.funding_rate)}">${esc(formatFunding(t.funding_rate))}</td>+ <td class="cv-mono">${esc(formatUsd(t.open_interest_usd))}</td>+ <td class="cv-mono">${esc(formatUsd(t.volume_24h_usd))}</td>+ </tr>`;+}++function renderVenue(p) {+ const v = p.venue;+ const c = p.contract;+ const s = p.peer_stats;+ const others = Array.isArray(p.venue_contracts) ? p.venue_contracts : [];++ const meters = [+ shareMeter({+ label: `Share of ${v.name} open interest`,+ pct: c.venue_oi_share_pct,+ caption: `${formatUsd(c.open_interest_usd)} of this venue's ${formatCount(v.contracts_listed)} listed contracts`,+ }),+ shareMeter({+ label: `Share of ${v.name} 24h volume`,+ pct: c.venue_vol_share_pct,+ caption: `${formatUsd(c.volume_24h_usd)} traded here in the last 24 hours`,+ }),+ s+ ? shareMeter({+ label: c.base+ ? `Share of all ${c.base} perpetual open interest`+ : 'Share of all open interest in this underlying',+ pct: s.oi_share_pct,+ caption: `${formatUsd(s.total_open_interest_usd)} open across ${formatCount(s.venues)} venues`,+ })+ : '',+ ]+ .filter(Boolean)+ .join('');++ const table = others.length+ ? `+ <h3 class="cv-h2" style="font-size:1rem;margin-top:1.75rem">Other contracts on ${esc(v.name)}</h3>+ <div class="cv-table-wrap">+ <table class="cv-table dc-table">+ <caption class="cv-sr-only">The most traded other contracts listed on ${esc(v.name)}</caption>+ <thead>+ <tr>+ <th scope="col" class="left">Contract</th>+ <th scope="col">Price</th>+ <th scope="col">24h</th>+ <th scope="col">Funding</th>+ <th scope="col">Open interest</th>+ <th scope="col">24h volume</th>+ </tr>+ </thead>+ <tbody>${others.map(venueContractRow).join('')}</tbody>+ </table>+ </div>+ <p class="dc-table-note"><a href="/exchange/${encodeURIComponent(v.id)}">See the full ${esc(v.name)} profile</a> for every contract, open interest and venue history.</p>`+ : `<p class="dc-table-note"><a href="/exchange/${encodeURIComponent(v.id)}">See the full ${esc(v.name)} profile</a>.</p>`;++ const about = v.description+ ? `<div class="cv-prose" style="margin-top:1rem"><p>${esc(v.description)}</p></div>`+ : '';++ $('dc-venue').innerHTML = `+ <h2 class="cv-h2">How big this contract is</h2>+ ${meters ? `<div class="dc-shares">${meters}</div>` : '<p class="dc-table-note">This venue does not report the shares needed to size the contract against its book.</p>'}+ ${about}+ ${table}`;+}++// ── Underlying asset card ───────────────────────────────────────────────────++function renderAsset(p) {+ const a = p.index;+ const el = $('dc-asset');+ if (!a || !a.coin_id) {+ el.innerHTML = '';+ return;+ }+ const stats = [+ ['Market cap', formatUsd(a.market_cap)],+ ['Spot 24h volume', formatUsd(a.volume_24h)],+ ['24h range', `${formatPrice(a.low_24h)} to ${formatPrice(a.high_24h)}`],+ ['All-time high', `${formatPrice(a.ath)}${a.ath_change_pct != null ? ` (${formatPercent(a.ath_change_pct)})` : ''}`],+ ];+ el.innerHTML = `+ <h2 class="cv-h2">The underlying</h2>+ <a class="dc-asset" href="/coin/${encodeURIComponent(a.coin_id)}">+ ${a.image ? `<img src="${esc(upstreamLogoURL(a.image, 40))}" alt="" width="40" height="40" loading="lazy" data-no-dark-filter />` : ''}+ <span>+ <p class="nm">${esc(a.name || a.symbol || '')} ${a.market_cap_rank != null ? `<span class="dc-chip">#${esc(String(a.market_cap_rank))}</span>` : ''}</p>+ <p class="sub">Spot market on three.ws</p>+ </span>+ <span class="spot">+ <p class="p">${esc(formatPrice(a.price_usd))}</p>+ <p class="d ${signClass(a.change_24h)}">${esc(formatPercent(a.change_24h))} 24h</p>+ </span>+ </a>+ <div class="dc-stats">${stats.map(([k, v]) => statCard({ label: k, value: v })).join('')}</div>`;+}++// ── Related links ───────────────────────────────────────────────────────────++function renderRelated(p) {+ const v = p.venue;+ const c = p.contract;+ const pills = [+ `<a class="cv-pill" href="/derivatives">All perpetual markets</a>`,+ `<a class="cv-pill" href="/exchange/${encodeURIComponent(v.id)}">${esc(v.name)} profile</a>`,+ ];+ if (c.coin_id) pills.push(`<a class="cv-pill" href="/coin/${encodeURIComponent(c.coin_id)}">${esc(c.base || c.coin_id)} spot</a>`);+ pills.push('<a class="cv-pill" href="/exchanges">Exchange rankings</a>');+ $('dc-related').innerHTML = `<div class="dc-related">${pills.join('')}</div>`;+}++// ── SEO metadata ────────────────────────────────────────────────────────────++function updateMeta(p) {+ const c = p.contract;+ const v = p.venue;+ const title = `${c.symbol} on ${v.name} - Perpetual Futures · three.ws`;+ document.title = title;+ const url = `https://three.ws${derivativePath(v.id, c.symbol) || '/derivatives'}`;+ const desc = `${c.symbol} perpetual futures on ${v.name}: ${formatPrice(c.price)} mark price, ${formatFunding(c.funding_rate)} funding (${formatApr(c.funding_apr)} annualized), ${formatUsd(c.open_interest_usd)} open interest and ${formatUsd(c.volume_24h_usd)} 24h volume, compared against every other venue listing ${c.base || 'the same'} perpetuals.`;++ const set = (sel, attr, val) => document.querySelector(sel)?.setAttribute(attr, val);+ 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 (v.image) {+ set('meta[property="og:image"]', 'content', v.image);+ set('meta[name="twitter:image"]', 'content', v.image);+ }+ let canon = document.querySelector('link[rel="canonical"]');+ if (!canon) {+ canon = document.createElement('link');+ canon.rel = 'canonical';+ document.head.appendChild(canon);+ }+ canon.href = url;++ const ld = {+ '@context': 'https://schema.org',+ '@type': 'FinancialProduct',+ name: `${c.symbol} perpetual futures`,+ description: desc,+ url,+ category: 'Perpetual futures contract',+ provider: { '@type': 'Organization', name: v.name, url: v.url || undefined },+ };+ let script = document.getElementById('dc-ld');+ if (!script) {+ script = document.createElement('script');+ script.type = 'application/ld+json';+ script.id = 'dc-ld';+ document.head.appendChild(script);+ }+ script.textContent = JSON.stringify(ld);+}++// ── Error states ────────────────────────────────────────────────────────────++function clearSections() {+ for (const id of ['dc-stats', 'dc-funding', 'dc-chart', 'dc-peers', 'dc-venue', 'dc-asset', 'dc-related']) {+ $(id).innerHTML = '';+ }+}++function renderNotFound(target) {+ document.title = 'Contract not found · three.ws';+ $('dc-crumb-symbol').textContent = 'Not found';+ $('dc-hero').innerHTML = `+ <h1 class="cv-h1">Contract not found</h1>+ <div class="cv-empty" style="text-align:left">+ <p style="margin:0 0 0.75rem">No active perpetual called <strong>${esc(target.symbol)}</strong> is listed on <strong>${esc(target.venue)}</strong> right now. Contracts get delisted and symbols get renamed, and expired contracts drop out of the feed.</p>+ <p style="margin:0">Browse <a href="/derivatives">every live perpetual market</a>, or open the <a href="/exchange/${encodeURIComponent(target.venue)}">${esc(target.venue)} profile</a> to see what it does list.</p>+ </div>`;+ clearSections();+}++function renderError() {+ $('dc-hero').innerHTML = `+ <h1 class="cv-h1">Contract 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="dc-retry" id="dc-retry">Retry</button>+ <span style="margin-left:0.75rem">or go back to <a href="/derivatives">all perpetual markets</a>.</span>+ </div>`;+ clearSections();+ $('dc-retry')?.addEventListener('click', main);+}++// ── Boot ────────────────────────────────────────────────────────────────────++async function main() {+ const target = targetFromLocation();+ const root = $('dc-main');+ if (!target) {+ location.replace('/derivatives');+ return;+ }+ state.venue = target.venue;+ state.symbol = target.symbol;+ root.setAttribute('aria-busy', 'true');+ renderSkeletons();++ let payload;+ try {+ payload = await getJson(+ `/api/coin/derivative?venue=${encodeURIComponent(target.venue)}&symbol=${encodeURIComponent(target.symbol)}`,+ );+ } catch (err) {+ root.removeAttribute('aria-busy');+ if (err.status === 404 || err.status === 400) renderNotFound(target);+ else renderError();+ return;+ }++ state.payload = payload;+ root.removeAttribute('aria-busy');++ updateMeta(payload);+ renderHero(payload);+ renderStats(payload);+ renderFunding(payload);+ renderPeers(payload);+ renderVenue(payload);+ renderAsset(payload);+ renderRelated(payload);++ const upd = $('dc-updated');+ upd.hidden = false;+ upd.textContent = `Updated ${new Date(payload.updated_at || Date.now()).toLocaleTimeString('en-US')} · source: CoinGecko`;++ // The underlying's price history streams in after the contract itself.+ chartState.coinId = payload.contract.coin_id;+ chartState.name = payload.index?.name || payload.contract.base || 'Index';+ chartState.days = 30;+ if (chartState.coinId) loadChart();+ else $('dc-chart').innerHTML = '';+}++main();diff --git a/src/derivatives.css b/src/derivatives.cssindex d8c3fb6ae..b05f01d39 100644--- a/src/derivatives.css+++ b/src/derivatives.css@@ -31,14 +31,45 @@display: none;}-/* Derivatives rows are informational, not links — no pointer cursor. */+/* Every perp row that resolved to a contract page opens it; rows the feed+ could not address stay inert, so the cursor has to follow the data. */.dv-table tbody tr {cursor: default;}-.dv-table .name-cell .nm {+.dv-table tbody tr[data-href] {+ cursor: pointer;+ transition: background var(--duration-fast, 120ms);+}+.dv-table tbody tr[data-href]:hover,+.dv-table tbody tr[data-href]:focus-within {+ background: var(--cv-surface-2);+}+.dv-table .name-cell .nm,+.dv-table .name-cell .dv-link {max-width: 200px;overflow: hidden;text-overflow: ellipsis;display: inline-block;vertical-align: middle;}++/* The cell links carry the row's affordance: readable at rest, obviously+ interactive on hover, and focusable on their own for keyboard users. */+.dv-link {+ color: inherit;+ text-decoration: none;+ border-bottom: 1px solid transparent;+ transition:+ color var(--duration-fast, 120ms),+ border-color var(--duration-fast, 120ms);+}+.dv-link:hover,+.dv-link:focus-visible {+ color: var(--cv-accent);+ border-bottom-color: currentColor;+}+.dv-link:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+ border-radius: 2px;+}diff --git a/src/derivatives.js b/src/derivatives.jsindex 7a559f436..ae29abfb0 100644--- a/src/derivatives.js+++ b/src/derivatives.js@@ -5,6 +5,7 @@// the /coins market-table pattern (src/coins-index.js).import { formatUsd, formatPrice, formatPercent, escapeHtml as esc } from './shared/coin-format.js';+import { derivativePath } from './shared/derivative-slug.js';const $ = (id) => document.getElementById(id);@@ -164,6 +165,47 @@ function sortedTickers() {return out;}+// A row links to /derivative/:venue/:symbol when the feed resolved both halves+// of that address. When it did not (an unmapped venue, or a symbol outside the+// slug charset), the row renders as plain text rather than as a link that would+// land on a 404.+function contractHref(t) {+ return t.venue_id && t.symbol ? derivativePath(t.venue_id, t.symbol) : null;+}++function marketRow(t) {+ const href = contractHref(t);+ const label = esc(t.market);+ const nameCell = href+ ? `<a class="dv-link" href="${esc(href)}">${label}</a>`+ : `<span class="nm">${label}</span>`;+ const symbol = esc(t.symbol || '—');+ const symbolCell = href ? `<a class="dv-link" href="${esc(href)}">${symbol}</a>` : symbol;+ return `+ <tr${href ? ` data-href="${esc(href)}"` : ''}>+ <td class="left name-cell">${nameCell}</td>+ <td class="left dim hide-sm cv-mono">${symbolCell}</td>+ <td class="left">${t.index_id ? `<span class="dv-index">${esc(t.index_id)}</span>` : '<span class="dim">—</span>'}</td>+ <td class="price">${esc(formatPrice(t.price))}</td>+ ${pctCell(t.change_24h)}+ ${fundingCell(t.funding_rate)}+ <td class="dim hide-md">${esc(formatUsd(t.open_interest))}</td>+ <td class="dim">${esc(formatUsd(t.volume_24h))}</td>+ </tr>`;+}++// The name and symbol cells are real links, so keyboard and middle-click work+// without help. This only adds the convenience of clicking anywhere else in+// the row, and never hijacks a click that landed on the link itself.+function wireRowLinks(scope) {+ scope.querySelectorAll('tr[data-href]').forEach((tr) => {+ tr.addEventListener('click', (e) => {+ if (e.target.closest('a')) return;+ window.location.assign(tr.dataset.href);+ });+ });+}+function renderTable() {const el = $('dv-market');if (!state.tickers.length) {@@ -189,21 +231,7 @@ function renderTable() {return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;}).join('');- const body = rows- .map(- (t) => `- <tr>- <td class="left name-cell"><span class="nm">${esc(t.market)}</span></td>- <td class="left dim hide-sm cv-mono">${esc(t.symbol || '—')}</td>- <td class="left">${t.index_id ? `<span class="dv-index">${esc(t.index_id)}</span>` : '<span class="dim">—</span>'}</td>- <td class="price">${esc(formatPrice(t.price))}</td>- ${pctCell(t.change_24h)}- ${fundingCell(t.funding_rate)}- <td class="dim hide-md">${esc(formatUsd(t.open_interest))}</td>- <td class="dim">${esc(formatUsd(t.volume_24h))}</td>- </tr>`,- )- .join('');+ const body = rows.map(marketRow).join('');el.innerHTML = `<div class="cv-table-wrap">@@ -213,6 +241,8 @@ function renderTable() {</table></div>`;+ wireRowLinks(el);+el.querySelectorAll('th[data-key]').forEach((th) => {const activate = () => {const key = th.dataset.key;diff --git a/src/exchange-page.js b/src/exchange-page.jsindex 2d3100905..843c4f28a 100644--- a/src/exchange-page.js+++ b/src/exchange-page.js@@ -15,9 +15,14 @@ import {escapeHtml as esc,} from './shared/coin-format.js';import { upstreamLogoURL, swapFailedLogos } from './shared/upstream-logo.js';+import { derivativePath } from './shared/derivative-slug.js';const $ = (id) => document.getElementById(id);+// The exchange id for the profile currently on screen. Contract rows need it+// to address their own /derivative/:venue/:symbol page.+let pageId = null;+// Matches the /exchange/:id route; falls back to the ?id= query for direct// links and dev proxies that don't rewrite the path.function idFromLocation() {@@ -426,18 +431,29 @@ function spotRow(t) {</tr>`;}+// A contract symbol leads to its own three.ws detail page (funding cost, basis,+// cross-venue comparison); the venue's own trade screen stays reachable from+// the icon beside it, so the row offers both without either shadowing the+// other.function derivRow(t) {const sym = esc(t.symbol || '—');- const symCell = t.trade_url- ? `<a class="ex-pair-link" href="${esc(t.trade_url)}" target="_blank" rel="noopener noreferrer">${sym} <span class="ex-trade-inline" aria-hidden="true">↗</span></a>`- : `<span>${sym}</span>`;+ const detail = pageId && t.symbol ? derivativePath(pageId, t.symbol) : null;+ const symCell = detail+ ? `<a class="ex-pair-link" href="${esc(detail)}">${sym}</a>`+ : t.trade_url+ ? `<a class="ex-pair-link" href="${esc(t.trade_url)}" target="_blank" rel="noopener noreferrer">${sym} <span class="ex-trade-inline" aria-hidden="true">↗</span></a>`+ : `<span>${sym}</span>`;+ const trade =+ detail && t.trade_url+ ? `<a class="ex-trade" href="${esc(t.trade_url)}" target="_blank" rel="noopener noreferrer" aria-label="Trade ${sym} on this venue (opens in a new tab)">${TRADE_ICON}</a>`+ : '';const funding =t.funding_rate != null? `<span class="${t.funding_rate >= 0 ? 'cv-up' : 'cv-down'}">${t.funding_rate >= 0 ? '+' : ''}${t.funding_rate.toFixed(4)}%</span>`: '—';return `<tr>- <td class="left"><span class="ex-pair">${symCell}</span></td>+ <td class="left"><span class="ex-pair">${symCell}${trade}</span></td><td class="cv-mono">${esc(formatPrice(t.price))}</td><td class="cv-mono">${esc(formatPrice(t.index))}</td><td class="cv-mono">${funding}</td>@@ -562,6 +578,7 @@ async function main() {location.replace('/exchanges');return;}+ pageId = id;renderSkeletons();let payload;diff --git a/src/shared/derivative-slug.js b/src/shared/derivative-slug.jsnew file mode 100644index 000000000..694a80db9--- /dev/null+++ b/src/shared/derivative-slug.js@@ -0,0 +1,71 @@+// Perpetual-contract URL slugs, shared by every surface that links to+// /derivative/:venue/:symbol.+//+// A contract is addressed by its venue id plus the venue's own symbol, and+// those symbols are not path-safe: a handful arrive as "ETH/USDT". A+// percent-encoded %2F is decoded by proxies before routing, which splits the+// path into an extra segment and 404s the route, so the slash is swapped for+// "~" instead. "~" is an unreserved URL character (no encoding needed, no+// double-encoding trap) and appears in no venue symbol the derivatives feed+// carries.+//+// A symbol that falls outside the accepted charset returns null rather than a+// mangled slug: the caller renders plain text instead of a link that would+// 404.+//+// This module exists twice and the two copies must stay byte-identical:+// src/shared/derivative-slug.js (browser) and api/_lib/derivative-slug.js+// (server). The server build context excludes src/, so it cannot import the+// browser copy; tests/api/derivative-slug.test.js compares the two files and+// fails the moment they drift.++// Venue ids come from CoinGecko's derivatives-exchange namespace.+export const VENUE_ID_RE = /^[a-z0-9_-]{1,60}$/i;+// Exchange symbols in the feed use letters, digits, "_", "-", "/", "." and ":".+export const SYMBOL_RE = /^[A-Za-z0-9._:/-]{1,48}$/;+// What a symbol looks like once the slash is folded into "~".+export const SYMBOL_SLUG_RE = /^[A-Za-z0-9._:~-]{1,48}$/;++/**+ * Fold a venue symbol into a path-safe slug.+ * @param {string} symbol e.g. "ETH/USDT"+ * @returns {string|null} e.g. "ETH~USDT", or null when the symbol is unusable+ */+export function contractSlug(symbol) {+ const s = String(symbol ?? '').trim();+ if (!s || !SYMBOL_RE.test(s) || s.includes('~')) return null;+ return s.replace(/\//g, '~');+}++/**+ * Recover the venue symbol from a path slug.+ * @param {string} slug e.g. "ETH~USDT"+ * @returns {string|null} e.g. "ETH/USDT", or null when the slug is unusable+ */+export function symbolFromSlug(slug) {+ let s = String(slug ?? '').trim();+ // Tolerate a still-encoded segment: some clients hand back "%7E" or "%2F".+ if (s.includes('%')) {+ try {+ s = decodeURIComponent(s);+ } catch {+ return null;+ }+ }+ if (!s) return null;+ const symbol = s.replace(/~/g, '/');+ return SYMBOL_RE.test(symbol) ? symbol : null;+}++/**+ * The canonical detail path for one contract.+ * @param {string} venueId CoinGecko derivatives-exchange id+ * @param {string} symbol venue symbol+ * @returns {string|null} "/derivative/<venue>/<slug>", or null when unusable+ */+export function derivativePath(venueId, symbol) {+ const id = String(venueId ?? '').trim();+ const slug = contractSlug(symbol);+ if (!id || !VENUE_ID_RE.test(id) || !slug) return null;+ return `/derivative/${id.toLowerCase()}/${slug}`;+}