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(market): add seven keyless CEX ticker and kline rungs behind the US-safe exchanges
nirholase3fd861ef908
diff --git a/api/_lib/cex-public.js b/api/_lib/cex-public.jsnew file mode 100644index 000000000..43b606c2d--- /dev/null+++ b/api/_lib/cex-public.js@@ -0,0 +1,364 @@+// Free, KEYLESS public spot market-data clients for seven centralized+// exchanges: Binance, OKX, Bybit V5, KuCoin, Gate.io v4, MEXC, Bitget. Public+// market endpoints only (spot ticker / 24h stats and klines); no API key, no+// auth header, no account is involved anywhere in this module.+//+// These exist as DEEP fallback rungs for api/_lib/market-fallbacks.js: they+// are consulted only after the aggregators (CoinGecko, DefiLlama) and the+// US-datacenter-safe exchanges (Kraken, Coinbase, Bitfinex) have all failed.+// Two properties follow from that depth:+//+// - Quotes are USDT pairs (BTCUSDT / BTC-USDT / BTC_USDT), the only quote+// all seven venues share with real depth. The last price is used as a USD+// proxy; USDT peg drift is basis points under normal conditions, well+// inside the tolerance of a last-resort rung.+// - Binance and Bybit geo-block US datacenter IPs (verified 2026-08-05:+// api.binance.com answers HTTP 451 and api.bybit.com HTTP 403 from an+// Azure US egress; OKX can be blocked from some clouds too, per the note+// in api/_lib/sol-price.js). They are wired anyway: a block is an instant+// non-2xx, so the shared failover primitive pays one fast round-trip,+// benches the rung for its cooldown window, and moves on. From+// non-blocked egress the rungs simply work.+//+// Every endpoint, symbol format, response shape and per-request candle cap in+// this file was verified against the live APIs with curl on 2026-08-05 before+// being written down. Verified quirks, so nobody "fixes" them back:+// - MEXC /ticker/24hr `priceChangePercent` is a RATIO (0.0076 means 0.76%),+// unlike Binance's same-named field, which is a percent. KuCoin+// `changeRate`, Bybit `price24hPcnt` and Bitget `change24h` are ratios+// too; Gate `change_percentage` is a percent; OKX has no change field at+// all (derived here from `open24h`).+// - OKX /market/candles and Bitget /market/candles cap one request at 300+// rows, so neither can serve the 365d chart window in one call and both+// omit that rung. KuCoin /market/candles returns only 100 rows without an+// explicit startAt/endAt range, so its candle URLs always carry one.++import { fetchFirst } from '../../src/shared/failover-fetch.js';++const asPrice = (v) => {+ const n = Number(v);+ return Number.isFinite(n) && n > 0 ? n : null;+};++const asNum = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+};++// ── Symbol mapping ───────────────────────────────────────────────────────────++/** CoinGecko coin id → base asset symbol, for the ids the platform prices. */+export const CEX_BASE_BY_ID = {+ bitcoin: 'BTC',+ ethereum: 'ETH',+ solana: 'SOL',+};++/** The seven venues, deepest spot liquidity first. Keys into the tables below. */+export const CEX_VENUES = ['binance', 'okx', 'bybit', 'kucoin', 'gate', 'mexc', 'bitget'];++/**+ * Venue-native USDT pair for a base asset symbol.+ * BTC → BTCUSDT (Binance/Bybit/MEXC/Bitget), BTC-USDT (OKX/KuCoin),+ * BTC_USDT (Gate.io). Returns null for an unknown venue or a malformed base.+ * @param {string} venue one of CEX_VENUES+ * @param {string} base base asset symbol, e.g. "BTC"+ */+export function cexPair(venue, base) {+ const b = String(base || '').trim().toUpperCase();+ if (!/^[A-Z0-9]{1,20}$/.test(b)) return null;+ switch (venue) {+ case 'binance':+ case 'bybit':+ case 'mexc':+ case 'bitget':+ return `${b}USDT`;+ case 'okx':+ case 'kucoin':+ return `${b}-USDT`;+ case 'gate':+ return `${b}_USDT`;+ default:+ return null;+ }+}++// ── Ticker parsers ───────────────────────────────────────────────────────────+// Each takes the venue's raw JSON body and returns { price, change_24h } with+// price a positive number and change_24h a percent (or null when the venue+// omitted it), or null when the body is not a healthy ticker. All exported so+// the tests can pin them to captured live bodies.++/** Binance /api/v3/ticker/24hr: `lastPrice`; `priceChangePercent` is a percent. */+export function parseBinanceTicker(raw) {+ const price = asPrice(raw?.lastPrice);+ return price ? { price, change_24h: asNum(raw?.priceChangePercent) } : null;+}++/** OKX /api/v5/market/ticker: data[0].last; 24h change derived from open24h. */+export function parseOkxTicker(raw) {+ if (raw?.code !== '0') return null;+ const d = Array.isArray(raw.data) ? raw.data[0] : null;+ const price = asPrice(d?.last);+ if (!price) return null;+ const open = asPrice(d?.open24h);+ return { price, change_24h: open ? ((price - open) / open) * 100 : null };+}++/** Bybit /v5/market/tickers (spot): result.list[0]; `price24hPcnt` is a ratio. */+export function parseBybitTicker(raw) {+ if (raw?.retCode !== 0) return null;+ const d = Array.isArray(raw?.result?.list) ? raw.result.list[0] : null;+ const price = asPrice(d?.lastPrice);+ if (!price) return null;+ const ratio = asNum(d?.price24hPcnt);+ return { price, change_24h: ratio == null ? null : ratio * 100 };+}++/** KuCoin /api/v1/market/stats: data.last; `changeRate` is a ratio. */+export function parseKucoinTicker(raw) {+ if (raw?.code !== '200000') return null;+ const d = raw.data;+ const price = asPrice(d?.last);+ if (!price) return null;+ const ratio = asNum(d?.changeRate);+ return { price, change_24h: ratio == null ? null : ratio * 100 };+}++/** Gate /api/v4/spot/tickers: [0].last; `change_percentage` is a percent. */+export function parseGateTicker(raw) {+ const d = Array.isArray(raw) ? raw[0] : null;+ const price = asPrice(d?.last);+ return price ? { price, change_24h: asNum(d?.change_percentage) } : null;+}++/** MEXC /api/v3/ticker/24hr: `lastPrice`; `priceChangePercent` is a RATIO. */+export function parseMexcTicker(raw) {+ const price = asPrice(raw?.lastPrice);+ if (!price) return null;+ const ratio = asNum(raw?.priceChangePercent);+ return { price, change_24h: ratio == null ? null : ratio * 100 };+}++/** Bitget /api/v2/spot/market/tickers: data[0].lastPr; `change24h` is a ratio. */+export function parseBitgetTicker(raw) {+ if (raw?.code !== '00000') return null;+ const d = Array.isArray(raw.data) ? raw.data[0] : null;+ const price = asPrice(d?.lastPr);+ if (!price) return null;+ const ratio = asNum(d?.change24h);+ return { price, change_24h: ratio == null ? null : ratio * 100 };+}++const TICKERS = {+ binance: {+ url: (pair) => `https://api.binance.com/api/v3/ticker/24hr?symbol=${pair}`,+ parse: parseBinanceTicker,+ },+ okx: {+ url: (pair) => `https://www.okx.com/api/v5/market/ticker?instId=${pair}`,+ parse: parseOkxTicker,+ },+ bybit: {+ url: (pair) => `https://api.bybit.com/v5/market/tickers?category=spot&symbol=${pair}`,+ parse: parseBybitTicker,+ },+ kucoin: {+ url: (pair) => `https://api.kucoin.com/api/v1/market/stats?symbol=${pair}`,+ parse: parseKucoinTicker,+ },+ gate: {+ url: (pair) => `https://api.gateio.ws/api/v4/spot/tickers?currency_pair=${pair}`,+ parse: parseGateTicker,+ },+ mexc: {+ url: (pair) => `https://api.mexc.com/api/v3/ticker/24hr?symbol=${pair}`,+ parse: parseMexcTicker,+ },+ bitget: {+ url: (pair) => `https://api.bitget.com/api/v2/spot/market/tickers?symbol=${pair}`,+ parse: parseBitgetTicker,+ },+};++/**+ * fetchFirst providers yielding { price, change_24h } for a base asset symbol,+ * one rung per venue, deepest liquidity first.+ * @param {string} base base asset symbol, e.g. "BTC"+ */+export function cexTickerProviders(base) {+ const out = [];+ for (const venue of CEX_VENUES) {+ const pair = cexPair(venue, base);+ if (!pair) continue;+ const t = TICKERS[venue];+ out.push({+ name: venue,+ url: t.url(pair),+ parse: async (r) => t.parse(await r.json()),+ });+ }+ return out;+}++/**+ * The same rungs narrowed to the spot price alone, for splicing into a+ * price-failover chain (market-fallbacks.js fetchCoinPriceUsd).+ * @param {string} base base asset symbol, e.g. "BTC"+ */+export function cexPriceProviders(base) {+ return cexTickerProviders(base).map((p) => ({+ ...p,+ parse: async (r) => (await p.parse(r))?.price ?? null,+ }));+}++/**+ * Spot ticker for a base asset across the seven venues: the first healthy+ * venue answers. Resolves { price, change_24h, source } or null when every+ * venue is down or blocked; never throws, because these are last-resort rungs+ * and callers want the primary chain's error, not this one's.+ * @param {string} base base asset symbol, e.g. "BTC"+ */+export async function fetchCexTicker(base) {+ const providers = cexTickerProviders(base);+ if (!providers.length) return null;+ try {+ const { value, source } = await fetchFirst(providers, { timeoutMs: 6000, label: `cex-ticker:${base}` });+ return { ...value, source };+ } catch {+ return null;+ }+}++// ── Candles (klines) ─────────────────────────────────────────────────────────+// Normalized to the [[timestamp_ms, close], ...] oldest-first series the coin+// chart renders (see fetchExchangeChart in market-fallbacks.js). Interval per+// chart window mirrors the Kraken rung: 5m for 1d, 1h for 7d, 4h for 30d, 1d+// for 90d/365d. A venue that cannot cover a window in ONE request omits that+// window rather than serving a silently truncated chart.++// Candles needed to span each window at the chosen interval.+const CANDLE_LIMIT = { 1: 288, 7: 168, 30: 180, 90: 90, 365: 365 };++// Verified row layouts (index of the close price, timestamp unit, sort order):+// binance [openTime_ms, o, h, l, c, vol, closeTime_ms, quoteVol] oldest first+// okx [ts_ms, o, h, l, c, vol, volCcy, volCcyQuote, confirm] newest first+// bybit [start_ms, o, h, l, c, vol, turnover] newest first+// kucoin [t_s, open, close, high, low, vol, turnover] newest first+// gate [t_s, quoteVol, close, high, low, open, baseVol, done] oldest first+// mexc [openTime_ms, o, h, l, c, vol, closeTime_ms, quoteVol] oldest first+// bitget [ts_ms, o, h, l, c, baseVol, usdtVol, quoteVol] oldest first+// The normalizer sorts ascending regardless, so sort order never matters.+const CANDLES = {+ binance: {+ interval: { 1: '5m', 7: '1h', 30: '4h', 90: '1d', 365: '1d' },+ url: (pair, interval, days) =>+ `https://api.binance.com/api/v3/klines?symbol=${pair}&interval=${interval}&limit=${CANDLE_LIMIT[days]}`,+ rows: (raw) => (Array.isArray(raw) ? raw : null),+ closeIndex: 4,+ tsMs: true,+ },+ okx: {+ // No 365: /market/candles caps a request at 300 rows (verified).+ interval: { 1: '5m', 7: '1H', 30: '4H', 90: '1D' },+ url: (pair, interval, days) =>+ `https://www.okx.com/api/v5/market/candles?instId=${pair}&bar=${interval}&limit=${Math.min(CANDLE_LIMIT[days], 300)}`,+ rows: (raw) => (raw?.code === '0' && Array.isArray(raw.data) ? raw.data : null),+ closeIndex: 4,+ tsMs: true,+ },+ bybit: {+ interval: { 1: '5', 7: '60', 30: '240', 90: 'D', 365: 'D' },+ url: (pair, interval, days) =>+ `https://api.bybit.com/v5/market/kline?category=spot&symbol=${pair}&interval=${interval}&limit=${CANDLE_LIMIT[days]}`,+ rows: (raw) => (raw?.retCode === 0 && Array.isArray(raw?.result?.list) ? raw.result.list : null),+ closeIndex: 4,+ tsMs: true,+ },+ kucoin: {+ interval: { 1: '5min', 7: '1hour', 30: '4hour', 90: '1day', 365: '1day' },+ // Without startAt/endAt KuCoin returns only the latest 100 rows+ // (verified), which silently truncates every window except 90d; with a+ // range it returns up to 1500, covering all of ours.+ url: (pair, interval, days, now) => {+ const endAt = Math.floor(now / 1000);+ const startAt = endAt - days * 86_400;+ return `https://api.kucoin.com/api/v1/market/candles?type=${interval}&symbol=${pair}&startAt=${startAt}&endAt=${endAt}`;+ },+ rows: (raw) => (raw?.code === '200000' && Array.isArray(raw.data) ? raw.data : null),+ closeIndex: 2,+ tsMs: false,+ },+ gate: {+ interval: { 1: '5m', 7: '1h', 30: '4h', 90: '1d', 365: '1d' },+ url: (pair, interval, days) =>+ `https://api.gateio.ws/api/v4/spot/candlesticks?currency_pair=${pair}&interval=${interval}&limit=${CANDLE_LIMIT[days]}`,+ rows: (raw) => (Array.isArray(raw) ? raw : null),+ closeIndex: 2,+ tsMs: false,+ },+ mexc: {+ // MEXC's hour interval is named 60m, not 1h (verified; 1h is rejected).+ interval: { 1: '5m', 7: '60m', 30: '4h', 90: '1d', 365: '1d' },+ url: (pair, interval, days) =>+ `https://api.mexc.com/api/v3/klines?symbol=${pair}&interval=${interval}&limit=${CANDLE_LIMIT[days]}`,+ rows: (raw) => (Array.isArray(raw) ? raw : null),+ closeIndex: 4,+ tsMs: true,+ },+ bitget: {+ // No 365: /market/candles caps a request at 300 rows (verified).+ interval: { 1: '5min', 7: '1h', 30: '4h', 90: '1day' },+ url: (pair, interval, days) =>+ `https://api.bitget.com/api/v2/spot/market/candles?symbol=${pair}&granularity=${interval}&limit=${Math.min(CANDLE_LIMIT[days], 300)}`,+ rows: (raw) => (raw?.code === '00000' && Array.isArray(raw.data) ? raw.data : null),+ closeIndex: 4,+ tsMs: true,+ },+};++/**+ * Venue candle rows → [[timestamp_ms, close], ...] ascending, clipped to the+ * window; null when no row lands inside it. Exported for tests.+ * @param {any[]} rows the venue's row array (any sort order)+ * @param {{closeIndex:number, tsMs:boolean}} layout+ * @param {number} days chart window in days+ * @param {number} [now] epoch ms, injectable for tests+ */+export function normalizeCexCandles(rows, { closeIndex, tsMs }, days, now = Date.now()) {+ if (!Array.isArray(rows)) return null;+ const cutoff = now - days * 86_400_000;+ const out = rows+ .map((r) => [Number(r?.[0]) * (tsMs ? 1 : 1000), Number(r?.[closeIndex])])+ .filter(([t, c]) => Number.isFinite(t) && t >= cutoff && Number.isFinite(c) && c > 0)+ .sort((a, b) => a[0] - b[0]);+ return out.length ? out : null;+}++/**+ * fetchFirst providers yielding the chart series for a window, one rung per+ * venue that can cover it in a single request, deepest liquidity first.+ * Rung names are `<venue>-klines`, keeping their failover cooldowns separate+ * from the same venue's ticker rung (the Kraken rungs follow this pattern).+ * @param {string} base base asset symbol, e.g. "BTC"+ * @param {number} days chart window: 1 | 7 | 30 | 90 | 365+ * @param {number} [now] epoch ms, injectable for tests+ */+export function cexCandleProviders(base, days, now = Date.now()) {+ if (!CANDLE_LIMIT[days]) return [];+ const out = [];+ for (const venue of CEX_VENUES) {+ const pair = cexPair(venue, base);+ if (!pair) continue;+ const c = CANDLES[venue];+ const interval = c.interval[days];+ if (!interval) continue;+ out.push({+ name: `${venue}-klines`,+ url: c.url(pair, interval, days, now),+ parse: async (r) => normalizeCexCandles(c.rows(await r.json()), c, days, now),+ });+ }+ return out;+}diff --git a/api/_lib/market-fallbacks.js b/api/_lib/market-fallbacks.jsindex 27cb08771..c8ffbd7b1 100644--- a/api/_lib/market-fallbacks.js+++ b/api/_lib/market-fallbacks.js@@ -22,6 +22,7 @@import { fetchFirst } from '../../src/shared/failover-fetch.js';import { COINGECKO_BASE, geckoHeaders } from './coingecko.js';import { PAPRIKA_BASE, paprikaGet } from './coinpaprika.js';+import { CEX_BASE_BY_ID, cexPriceProviders, cexCandleProviders } from './cex-public.js';import { downsample } from '../../src/shared/coin-format.js';import { cacheGet, cacheSet } from './cache.js';@@ -40,12 +41,16 @@ const asPrice = (v) => {};// ── Exchange tickers for the headline assets ─────────────────────────────────-// US-datacenter-safe exchange APIs only: Binance, Bybit and OKX geo-block US-// datacenter IPs (Cloud Run us-central1 gets a "restricted location" error-// body, see the note in api/_lib/sol-price.js), which would make them-// permanently dead rungs. Kraken, Coinbase Exchange and Bitfinex all serve-// datacenter traffic. Only the CoinGecko ids the platform actually prices by-// id are mapped; an unmapped id just skips the exchange rungs.+// Two tiers. The US-datacenter-safe exchanges lead: Kraken, Coinbase Exchange+// and Bitfinex all serve datacenter traffic and quote real USD. Behind them+// sit the seven keyless CEX rungs from api/_lib/cex-public.js (Binance, OKX,+// Bybit, KuCoin, Gate.io, MEXC, Bitget), USDT-quoted, deepest liquidity first.+// Binance and Bybit geo-block US datacenter IPs (and OKX can from some clouds,+// see the note in api/_lib/sol-price.js), but a block is an instant non-2xx:+// the failover primitive pays one fast attempt, benches the rung for its+// cooldown, and moves on to a venue that answers, so they are no longer+// excluded as "permanently dead". Only the CoinGecko ids the platform actually+// prices by id are mapped; an unmapped id just skips the exchange rungs.export const EXCHANGE_PAIRS = {bitcoin: { kraken: 'XBTUSD', coinbase: 'BTC-USD', bitfinex: 'tBTCUSD' },@@ -74,6 +79,7 @@ export function parseBitfinexTicker(raw) {function exchangePriceProviders(id) {const pairs = EXCHANGE_PAIRS[id];if (!pairs) return [];+ const base = CEX_BASE_BY_ID[id];return [{name: 'kraken',@@ -90,6 +96,8 @@ function exchangePriceProviders(id) {url: `https://api-pub.bitfinex.com/v2/ticker/${pairs.bitfinex}`,parse: async (r) => parseBitfinexTicker(await r.json()),},+ // Keyless CEX tail: Binance → OKX → Bybit → KuCoin → Gate → MEXC → Bitget.+ ...(base ? cexPriceProviders(base) : []),];}@@ -369,10 +377,11 @@ export async function fetchMarketsTable({ page, perPage, category }) {// ── Price-series (chart) failover ────────────────────────────────────────────// Backs up CoinGecko /market_chart for the /coin/:id line chart, which renders// close prices as [[timestamp_ms, price], ...]. Exchange candle endpoints-// (Kraken OHLC, Coinbase Exchange candles) cover the EXCHANGE_PAIRS majors:-// when CoinGecko is rate-limited, the BTC/ETH/SOL charts stay live instead of-// blanking. Long-tail coins have no exchange mapping and keep CoinGecko as-// their only source, exactly as before.+// (Kraken OHLC, Coinbase Exchange candles, then the keyless CEX kline rungs+// from api/_lib/cex-public.js) cover the EXCHANGE_PAIRS majors: when CoinGecko+// is rate-limited, the BTC/ETH/SOL charts stay live instead of blanking.+// Long-tail coins have no exchange mapping and keep CoinGecko as their only+// source, exactly as before.// Kraken OHLC interval (minutes) per chart window. Kraken returns up to 720// candles per interval, so every window fits in one request: 5m covers 2.5d,@@ -440,6 +449,10 @@ export async function fetchExchangeChart(id, days) {parse: async (r) => normalizeCoinbaseChart(await r.json(), days),});}+ // Keyless CEX kline tail (Binance → OKX → Bybit → KuCoin → Gate → MEXC →+ // Bitget): venues that cannot cover this window in one request self-omit.+ const base = CEX_BASE_BY_ID[id];+ if (base) providers.push(...cexCandleProviders(base, days));try {const { value } = await fetchFirst(providers, { timeoutMs: 8000, label: `chart:${id}` });return value;diff --git a/tests/api/cex-public-fallbacks.test.js b/tests/api/cex-public-fallbacks.test.jsnew file mode 100644index 000000000..aa622dd59--- /dev/null+++ b/tests/api/cex-public-fallbacks.test.js@@ -0,0 +1,431 @@+// The seven keyless CEX rungs (Binance, OKX, Bybit, KuCoin, Gate.io, MEXC,+// Bitget) behind the market-data fallback chain: every rung must be REACHABLE,+// proven by failing the rungs above it at the transport level, and every+// parser must be pinned to the venue's real wire shape.+//+// Why transport level: a chain tested only with parse errors looks healthy+// while the real failure mode (dead socket, DNS failure, abort, geo-block)+// walks straight past it (see tests/api/llm-free-chain-reachability.test.js+// for the incident that made this the house pattern). Each reachability case+// kills the rungs above the target the way a provider actually dies and+// asserts the target answers.+//+// The ticker fixtures are captured LIVE bodies (curl, 2026-08-05), so the+// parsers are pinned to what the venues really send, including the quirk this+// suite exists to protect: MEXC/KuCoin/Bybit/Bitget report 24h change as a+// RATIO while Binance/Gate report a percent and OKX reports nothing at all.+// Binance and Bybit geo-block the capture host (HTTP 451/403), so their+// fixtures follow their documented shapes instead; both shapes are also in+// the family a sibling venue verifies live (MEXC mirrors Binance's schema).++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++import {+ CEX_BASE_BY_ID,+ CEX_VENUES,+ cexPair,+ parseBinanceTicker,+ parseOkxTicker,+ parseBybitTicker,+ parseKucoinTicker,+ parseGateTicker,+ parseMexcTicker,+ parseBitgetTicker,+ cexTickerProviders,+ cexPriceProviders,+ cexCandleProviders,+ normalizeCexCandles,+} from '../../api/_lib/cex-public.js';++// ── Captured live ticker bodies (curl, 2026-08-05) ───────────────────────────++const OKX_TICKER = {+ code: '0',+ msg: '',+ data: [+ {+ instType: 'SPOT',+ instId: 'BTC-USDT',+ last: '64639',+ open24h: '64101.3',+ high24h: '65026.6',+ low24h: '63880.7',+ vol24h: '7026.55757809',+ ts: '1785974196267',+ },+ ],+};++const KUCOIN_STATS = {+ code: '200000',+ data: {+ time: 1785974195546,+ symbol: 'BTC-USDT',+ changeRate: '0.0079',+ changePrice: '512.5',+ high: '65026.5',+ low: '63879',+ last: '64636.3',+ averagePrice: '64235.82318744',+ },+};++const GATE_TICKER = [+ {+ currency_pair: 'BTC_USDT',+ last: '64637.3',+ lowest_ask: '64637.3',+ highest_bid: '64637.2',+ change_percentage: '0.84',+ base_volume: '5766.149367',+ high_24h: '65019.8',+ low_24h: '63880',+ },+];++const MEXC_TICKER = {+ symbol: 'BTCUSDT',+ priceChange: '491.31',+ priceChangePercent: '0.0076', // a RATIO: 0.76%, not 0.0076%+ lastPrice: '64631.33',+ openPrice: '64140.02',+ highPrice: '65000',+ lowPrice: '63900',+ volume: '6395.70584489',+};++const BITGET_TICKER = {+ code: '00000',+ msg: 'success',+ requestTime: 1785974198119,+ data: [+ {+ symbol: 'BTCUSDT',+ lastPr: '64635.01',+ high24h: '65025',+ low24h: '63880.77',+ change24h: '0.00841', // a ratio+ open: '64096.26',+ },+ ],+};++// Documented shapes (capture host is geo-blocked by these two venues).+const BINANCE_TICKER = { symbol: 'BTCUSDT', lastPrice: '64640.1', priceChangePercent: '0.84', openPrice: '64101.3' };+const BYBIT_TICKER = {+ retCode: 0,+ retMsg: 'OK',+ result: { category: 'spot', list: [{ symbol: 'BTCUSDT', lastPrice: '64638.5', price24hPcnt: '0.0079' }] },+};++// The live geo-block bodies (Binance answers this with HTTP 451, Bybit's 403+// carries an HTML-ish CloudFront page that is not even JSON).+const BINANCE_GEOBLOCK = { code: 0, msg: "Service unavailable from a restricted location according to 'b. Eligibility' in https://www.binance.com/en/terms." };++describe('cexPair symbol mapping', () => {+ it('maps a base symbol to each venue-native USDT pair', () => {+ expect(cexPair('binance', 'btc')).toBe('BTCUSDT');+ expect(cexPair('bybit', 'BTC')).toBe('BTCUSDT');+ expect(cexPair('mexc', 'BTC')).toBe('BTCUSDT');+ expect(cexPair('bitget', 'BTC')).toBe('BTCUSDT');+ expect(cexPair('okx', 'BTC')).toBe('BTC-USDT');+ expect(cexPair('kucoin', 'BTC')).toBe('BTC-USDT');+ expect(cexPair('gate', 'BTC')).toBe('BTC_USDT');+ });++ it('rejects unknown venues and malformed bases', () => {+ expect(cexPair('nasdaq', 'BTC')).toBeNull();+ expect(cexPair('binance', '')).toBeNull();+ expect(cexPair('binance', 'B T C')).toBeNull();+ expect(cexPair('gate', '../etc')).toBeNull();+ });+});++describe('ticker parsers pinned to live wire shapes', () => {+ it('Binance: percent field stays a percent', () => {+ expect(parseBinanceTicker(BINANCE_TICKER)).toEqual({ price: 64640.1, change_24h: 0.84 });+ });++ it('OKX: derives 24h change from open24h', () => {+ const t = parseOkxTicker(OKX_TICKER);+ expect(t.price).toBe(64639);+ expect(t.change_24h).toBeCloseTo(((64639 - 64101.3) / 64101.3) * 100, 6);+ });++ it('Bybit: price24hPcnt ratio is scaled to a percent', () => {+ expect(parseBybitTicker(BYBIT_TICKER)).toEqual({ price: 64638.5, change_24h: 0.79 });+ });++ it('KuCoin: changeRate ratio is scaled to a percent', () => {+ const t = parseKucoinTicker(KUCOIN_STATS);+ expect(t.price).toBe(64636.3);+ expect(t.change_24h).toBeCloseTo(0.79, 6);+ });++ it('Gate: change_percentage stays a percent', () => {+ expect(parseGateTicker(GATE_TICKER)).toEqual({ price: 64637.3, change_24h: 0.84 });+ });++ it('MEXC: priceChangePercent is a RATIO and must be scaled, unlike Binance', () => {+ const t = parseMexcTicker(MEXC_TICKER);+ expect(t.price).toBe(64631.33);+ expect(t.change_24h).toBeCloseTo(0.76, 6);+ expect(t.change_24h).not.toBeCloseTo(0.0076, 6);+ });++ it('Bitget: change24h ratio is scaled to a percent', () => {+ const t = parseBitgetTicker(BITGET_TICKER);+ expect(t.price).toBe(64635.01);+ expect(t.change_24h).toBeCloseTo(0.841, 6);+ });++ it('rejects error and geo-block bodies as misses, not prices', () => {+ expect(parseBinanceTicker(BINANCE_GEOBLOCK)).toBeNull();+ expect(parseOkxTicker({ code: '51001', msg: 'Instrument ID does not exist', data: [] })).toBeNull();+ expect(parseBybitTicker({ retCode: 10001, retMsg: 'params error', result: {} })).toBeNull();+ expect(parseKucoinTicker({ code: '400100', msg: 'symbol not exists' })).toBeNull();+ expect(parseGateTicker({ label: 'INVALID_CURRENCY_PAIR' })).toBeNull();+ expect(parseMexcTicker({ msg: 'Invalid symbol.', code: -1121 })).toBeNull();+ expect(parseBitgetTicker({ code: '40034', msg: 'Parameter does not exist', data: null })).toBeNull();+ });+});++describe('candle normalization pinned to live row layouts', () => {+ // Explicit `now` beside the captured timestamps so the fixtures never age+ // out of the window as the suite gets older.+ const NOW = 1_785_974_400_000;++ it('OKX rows (ms, close at index 4, newest first) sort ascending', () => {+ const rows = [+ ['1785970800000', '64638.3', '64751.8', '64581.6', '64638.9', '74.78', '4835416', '4835416', '0'],+ ['1785967200000', '64730.6', '64792.6', '64633.8', '64638.4', '45.05', '2914820', '2914820', '1'],+ ];+ expect(normalizeCexCandles(rows, { closeIndex: 4, tsMs: true }, 7, NOW)).toEqual([+ [1785967200000, 64638.4],+ [1785970800000, 64638.9],+ ]);+ });++ it('KuCoin rows (seconds, close at index 2, newest first) convert to ms', () => {+ const rows = [+ ['1785970800', '64626.9', '64636.3', '64750.1', '64571.6', '21.08', '1362973'],+ ['1785967200', '64731.8', '64634.9', '64785.4', '64625.5', '16.58', '1073089'],+ ];+ expect(normalizeCexCandles(rows, { closeIndex: 2, tsMs: false }, 7, NOW)).toEqual([+ [1785967200000, 64634.9],+ [1785970800000, 64636.3],+ ]);+ });++ it('Gate rows (seconds, close at index 2, oldest first) convert to ms', () => {+ const rows = [+ ['1785963600', '8785034.29', '64732.3', '64831.1', '64666.6', '64831.1', '135.70', 'true'],+ ['1785967200', '4848473.09', '64635.1', '64782.3', '64633.4', '64732.3', '74.93', 'true'],+ ];+ expect(normalizeCexCandles(rows, { closeIndex: 2, tsMs: false }, 7, NOW)).toEqual([+ [1785963600000, 64732.3],+ [1785967200000, 64635.1],+ ]);+ });++ it('MEXC/Binance-family rows (ms, close at index 4, oldest first) pass through', () => {+ const rows = [+ [1785963600000, '64840.38', '64840.38', '64669.12', '64742.09', '239.42', 1785967200000, '15497514.5'],+ [1785967200000, '64742.09', '64773.04', '64628.25', '64633.83', '139.56', 1785970800000, '9029060.18'],+ ];+ expect(normalizeCexCandles(rows, { closeIndex: 4, tsMs: true }, 7, NOW)).toEqual([+ [1785963600000, 64742.09],+ [1785967200000, 64633.83],+ ]);+ });++ it('clips rows outside the window and returns null when nothing survives', () => {+ const stale = [['1685963600000', '1', '1', '1', '30000', '1']];+ expect(normalizeCexCandles(stale, { closeIndex: 4, tsMs: true }, 7, NOW)).toBeNull();+ expect(normalizeCexCandles('not-rows', { closeIndex: 4, tsMs: true }, 7, NOW)).toBeNull();+ });+});++describe('provider construction stays keyless and liquidity-ordered', () => {+ it('ticker rungs cover all seven venues in order, with no credential anywhere', () => {+ const providers = cexTickerProviders('BTC');+ expect(providers.map((p) => p.name)).toEqual(CEX_VENUES);+ for (const p of providers) {+ expect(p.url).toMatch(/^https:\/\//);+ // Keyless is the whole point: no key/secret/signature/passphrase param+ // and no custom headers may ever creep into these URLs.+ expect(p.url).not.toMatch(/key|secret|sign|passphrase|token/i);+ expect(p.init).toBeUndefined();+ }+ });++ it('price rungs mirror the ticker rungs one-to-one', () => {+ expect(cexPriceProviders('SOL').map((p) => p.name)).toEqual(CEX_VENUES);+ });++ it('candle rungs use venue-native pair and interval names for the 7d window', () => {+ const NOW = 1_785_974_400_000;+ const byName = Object.fromEntries(cexCandleProviders('BTC', 7, NOW).map((p) => [p.name, p.url]));+ expect(Object.keys(byName)).toEqual(CEX_VENUES.map((v) => `${v}-klines`));+ expect(byName['binance-klines']).toContain('symbol=BTCUSDT&interval=1h&limit=168');+ expect(byName['okx-klines']).toContain('instId=BTC-USDT&bar=1H');+ expect(byName['bybit-klines']).toContain('category=spot&symbol=BTCUSDT&interval=60');+ expect(byName['mexc-klines']).toContain('interval=60m'); // MEXC rejects "1h" (verified 400 -1121)+ expect(byName['gate-klines']).toContain('currency_pair=BTC_USDT&interval=1h');+ expect(byName['bitget-klines']).toContain('granularity=1h');+ // KuCoin truncates to 100 rows without an explicit range (verified), so+ // the URL must always carry one.+ expect(byName['kucoin-klines']).toContain(`startAt=${Math.floor(NOW / 1000) - 7 * 86_400}`);+ expect(byName['kucoin-klines']).toContain(`endAt=${Math.floor(NOW / 1000)}`);+ });++ it('venues that cannot cover 365d in one request omit that rung', () => {+ const names = cexCandleProviders('BTC', 365).map((p) => p.name);+ expect(names).toEqual(['binance-klines', 'bybit-klines', 'kucoin-klines', 'gate-klines', 'mexc-klines']);+ });++ it('an unknown window or malformed base yields no rungs', () => {+ expect(cexCandleProviders('BTC', 14)).toEqual([]);+ expect(cexCandleProviders('B T C', 7)).toEqual([]);+ });+});++// ── Reachability through the market-fallbacks chain ──────────────────────────+// The chain in exchange-rung order for fetchCoinPriceUsd('bitcoin'). Every+// host is distinct, so a rung is identified by host alone.++const PRICE_CHAIN = [+ { name: 'coingecko', host: 'api.coingecko.com', body: { bitcoin: { usd: 64650.5 } }, price: 64650.5 },+ {+ name: 'llama',+ host: 'coins.llama.fi',+ body: { coins: { 'coingecko:bitcoin': { price: 64649.4 } } },+ price: 64649.4,+ },+ { name: 'kraken', host: 'api.kraken.com', body: { result: { XXBTZUSD: { c: ['64648.3', '1.0'] } } }, price: 64648.3 },+ { name: 'coinbase', host: 'api.coinbase.com', body: { data: { amount: '64647.2' } }, price: 64647.2 },+ {+ name: 'bitfinex',+ host: 'api-pub.bitfinex.com',+ body: [64646, 5.1, 64647, 3.2, 540, 0.008, 64646.1, 900, 65000, 63800],+ price: 64646.1,+ },+ { name: 'binance', host: 'api.binance.com', body: BINANCE_TICKER, price: 64640.1 },+ { name: 'okx', host: 'www.okx.com', body: OKX_TICKER, price: 64639 },+ { name: 'bybit', host: 'api.bybit.com', body: BYBIT_TICKER, price: 64638.5 },+ { name: 'kucoin', host: 'api.kucoin.com', body: KUCOIN_STATS, price: 64636.3 },+ { name: 'gate', host: 'api.gateio.ws', body: GATE_TICKER, price: 64637.3 },+ { name: 'mexc', host: 'api.mexc.com', body: MEXC_TICKER, price: 64631.33 },+ { name: 'bitget', host: 'api.bitget.com', body: BITGET_TICKER, price: 64635.01 },+];++const FIRST_CEX_RUNG = 5; // index of binance in PRICE_CHAIN++const okJson = (body) => ({ ok: true, status: 200, json: async () => body });+const httpBlock = (status, body) => ({ ok: false, status, json: async () => body });++// How a provider actually dies: the socket drops, or the attempt is aborted.+function transportFailure(kind) {+ if (kind === 'abort') return Object.assign(new Error('The operation was aborted'), { name: 'AbortError' });+ return Object.assign(new Error('fetch failed: ECONNRESET'), { cause: { code: 'ECONNRESET' } });+}++describe('market-fallbacks chain: every CEX rung is reachable', () => {+ const savedFetch = globalThis.fetch;+ let mf;++ beforeEach(async () => {+ // Fresh module graph per test: the failover primitive's cooldown map is+ // process-wide, and a rung benched by one test must not skew the next.+ vi.resetModules();+ mf = await import('../../api/_lib/market-fallbacks.js');+ });++ afterEach(() => {+ globalThis.fetch = savedFetch;+ vi.restoreAllMocks();+ });++ for (let i = FIRST_CEX_RUNG; i < PRICE_CHAIN.length; i++) {+ const rung = PRICE_CHAIN[i];+ it(`reaches ${rung.name} when the ${i} rung(s) above it die at the transport level`, async () => {+ const tried = [];+ globalThis.fetch = vi.fn(async (url) => {+ const u = String(url);+ const idx = PRICE_CHAIN.findIndex((r) => u.includes(r.host));+ expect(idx, `unexpected fetch: ${u}`).toBeGreaterThanOrEqual(0);+ tried.push(PRICE_CHAIN[idx].name);+ if (idx < i) throw transportFailure(idx % 2 === 0 ? 'reset' : 'abort');+ return okJson(PRICE_CHAIN[idx].body);+ });++ const price = await mf.fetchCoinPriceUsd('bitcoin');+ expect(price).toBe(rung.price);+ // Every rung above was actually attempted, in the documented order.+ expect(tried).toEqual(PRICE_CHAIN.slice(0, i + 1).map((r) => r.name));+ });+ }++ it('walks past the real Binance 451 and Bybit 403 geo-blocks to a venue that answers', async () => {+ globalThis.fetch = vi.fn(async (url) => {+ const u = String(url);+ if (u.includes('api.binance.com')) return httpBlock(451, BINANCE_GEOBLOCK);+ if (u.includes('api.bybit.com')) return httpBlock(403, {});+ if (u.includes('www.okx.com')) throw transportFailure('reset');+ if (u.includes('api.kucoin.com')) return okJson(KUCOIN_STATS);+ throw transportFailure('abort'); // aggregators and USD exchanges are down+ });+ const price = await mf.fetchCoinPriceUsd('bitcoin');+ expect(price).toBe(64636.3);+ });++ it('serves the 7d chart from a CEX kline rung when Kraken, Coinbase and Binance die', async () => {+ const h1 = 3_600_000;+ const t0 = Date.now() - 2 * h1;+ // OKX layout: [ts_ms, o, h, l, c, ...], newest first.+ const okxRows = [+ [String(t0 + h1), '101', '106', '100', '105', '1', '1', '1', '1'],+ [String(t0), '100', '104', '99', '103', '1', '1', '1', '1'],+ ];+ globalThis.fetch = vi.fn(async (url) => {+ const u = String(url);+ if (u.includes('www.okx.com')) return okJson({ code: '0', msg: '', data: okxRows });+ throw transportFailure('reset');+ });+ const series = await mf.fetchExchangeChart('bitcoin', 7);+ expect(series).toEqual([+ [t0, 103],+ [t0 + h1, 105],+ ]);+ });++ it('never asks OKX or Bitget for the 365d window and serves it from Gate', async () => {+ const day = 86_400_000;+ const t0 = Date.now() - 2 * day;+ // Gate layout: [t_s, quoteVol, close, high, low, open, baseVol, done].+ const gateRows = [+ [String(Math.floor(t0 / 1000)), '900000', '64000', '64500', '63500', '63800', '14', 'true'],+ [String(Math.floor((t0 + day) / 1000)), '910000', '64100', '64600', '63600', '64000', '14', 'true'],+ ];+ const asked = new Set();+ globalThis.fetch = vi.fn(async (url) => {+ const u = String(url);+ asked.add(new URL(u).host);+ if (u.includes('api.gateio.ws')) return okJson(gateRows);+ throw transportFailure('abort');+ });+ const series = await mf.fetchExchangeChart('bitcoin', 365);+ expect(series).toEqual([+ [Math.floor(t0 / 1000) * 1000, 64000],+ [Math.floor((t0 + day) / 1000) * 1000, 64100],+ ]);+ expect(asked.has('www.okx.com')).toBe(false);+ expect(asked.has('api.bitget.com')).toBe(false);+ });++ it('maps every EXCHANGE_PAIRS id to a CEX base symbol', () => {+ for (const id of Object.keys(mf.EXCHANGE_PAIRS)) {+ expect(CEX_BASE_BY_ID[id], `missing CEX base for ${id}`).toBeTruthy();+ }+ });+});