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: implement multi-source failover for market data and add DefiLlama support
fudjia9a325b7213f5
diff --git a/api/_lib/market-fallbacks.js b/api/_lib/market-fallbacks.jsnew file mode 100644index 000000000..9707949f1--- /dev/null+++ b/api/_lib/market-fallbacks.js@@ -0,0 +1,224 @@+// Free-API failover for the global coin datapoints that were single-source+// CoinGecko. CoinGecko's keyless tier rate-limits aggressively (a shared+// datacenter IP gets 429'd under load), so a CoinGecko blip used to blank the+// whole /coins stats bar and market table. This module fronts those reads with+// an ordered list of FREE, keyless public APIs — CoinGecko first (richest),+// then CoinPaprika and CoinLore — using the shared failover-fetch primitive so+// one dead upstream moves on to the next instead of surfacing an error.+//+// Every provider is normalized to the SAME shape the endpoints already emit, so+// the page renders identically no matter which source answered. Fallbacks that+// can't supply a field (CoinLore has no coin logos; neither fallback has 7d+// sparklines) leave it null/[] — the page already degrades gracefully on those.+//+// Sources (all keyless, verified live):+// CoinGecko api.coingecko.com — primary; full dominance map + sparklines+// CoinPaprika api.coinpaprika.com — global stats (BTC dominance only)+// CoinLore api.coinlore.com — global stats + ranked ticker table+//+// See api/_lib/market/token-market.js for the analogous Solana-mint failover+// and api/_lib/sol-price.js for the SOL-spot failover.++import { fetchFirst } from '../../src/shared/failover-fetch.js';+import { COINGECKO_BASE } from './coingecko.js';+import { downsample } from '../../src/shared/coin-format.js';++const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+};++// CoinGecko demo key (optional) lifts the public rate limit — same header the+// shared geckoFetch uses. Absent key just means the stricter keyless tier.+function geckoHeaders() {+ const h = { accept: 'application/json', 'user-agent': 'three.ws/1.0' };+ const key = (process.env.COINGECKO_API_KEY || '').trim();+ if (key) h['x-cg-demo-api-key'] = key;+ return h;+}++// ── Global market stats ──────────────────────────────────────────────────────+// Normalized shape: { market_cap_usd, volume_24h_usd, market_cap_change_pct_24h,+// active_coins, dominance: [{ symbol, pct }] }++/** CoinGecko /global → normalized global stats (full top-2 dominance). */+export function normalizeGeckoGlobal(raw) {+ const g = raw?.data;+ if (!g || typeof g !== 'object') return null;+ const mcap = num(g.total_market_cap?.usd);+ if (mcap == null) return null; // no headline number → treat as a miss, try next+ // Top-2 dominance entries from the runtime response, largest first — no asset+ // list is hardcoded.+ const dominance = Object.entries(g.market_cap_percentage || {})+ .filter(([, v]) => Number.isFinite(v))+ .sort((a, b) => b[1] - a[1])+ .slice(0, 2)+ .map(([sym, pct]) => ({ symbol: sym.toUpperCase(), pct }));+ return {+ market_cap_usd: mcap,+ volume_24h_usd: num(g.total_volume?.usd),+ market_cap_change_pct_24h: num(g.market_cap_change_percentage_24h_usd),+ active_coins: num(g.active_cryptocurrencies),+ dominance,+ };+}++/** CoinPaprika /v1/global → normalized global stats (BTC dominance only). */+export function normalizePaprikaGlobal(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const mcap = num(raw.market_cap_usd);+ if (mcap == null) return null;+ const btcDom = num(raw.bitcoin_dominance_percentage);+ return {+ market_cap_usd: mcap,+ volume_24h_usd: num(raw.volume_24h_usd),+ market_cap_change_pct_24h: num(raw.market_cap_change_24h),+ active_coins: num(raw.cryptocurrencies_number),+ dominance: btcDom != null ? [{ symbol: 'BTC', pct: btcDom }] : [],+ };+}++/** CoinLore /api/global/ (array with one object) → normalized global stats. */+export function normalizeLoreGlobal(raw) {+ const g = Array.isArray(raw) ? raw[0] : raw;+ if (!g || typeof g !== 'object') return null;+ const mcap = num(g.total_mcap);+ if (mcap == null) return null;+ const dominance = [];+ const btcDom = num(g.btc_d);+ const ethDom = num(g.eth_d);+ if (btcDom != null) dominance.push({ symbol: 'BTC', pct: btcDom });+ if (ethDom != null) dominance.push({ symbol: 'ETH', pct: ethDom });+ return {+ market_cap_usd: mcap,+ volume_24h_usd: num(g.total_volume),+ market_cap_change_pct_24h: num(g.mcap_change),+ active_coins: num(g.coins_count),+ dominance,+ };+}++/**+ * Global market stats with CoinGecko → CoinPaprika → CoinLore failover.+ * @returns {Promise<{market_cap_usd:number|null, volume_24h_usd:number|null,+ * market_cap_change_pct_24h:number|null, active_coins:number|null,+ * dominance:Array<{symbol:string,pct:number}>}>}+ * @throws when every free source is down.+ */+export async function fetchGlobalMarket() {+ const { value } = await fetchFirst(+ [+ {+ name: 'coingecko',+ url: `${COINGECKO_BASE}/global`,+ init: { headers: geckoHeaders() },+ parse: async (r) => normalizeGeckoGlobal(await r.json()),+ },+ {+ name: 'coinpaprika',+ url: 'https://api.coinpaprika.com/v1/global',+ parse: async (r) => normalizePaprikaGlobal(await r.json()),+ },+ {+ name: 'coinlore',+ url: 'https://api.coinlore.com/api/global/',+ parse: async (r) => normalizeLoreGlobal(await r.json()),+ },+ ],+ { timeoutMs: 6000, label: 'global-market' },+ );+ return value;+}++// ── Ranked market table ──────────────────────────────────────────────────────+// Normalized row shape (matches src/shared/market-table.js coinRow):+// { id, symbol, name, image, rank, price, change_24h, change_7d,+// market_cap, volume_24h, sparkline: number[] }++/** CoinGecko /coins/markets row → normalized table row (with 7d sparkline). */+export function normalizeGeckoRow(c) {+ return {+ id: c.id,+ symbol: (c.symbol || '').toUpperCase(),+ name: c.name || c.id,+ image: c.image || null,+ rank: num(c.market_cap_rank),+ price: num(c.current_price),+ change_24h: num(c.price_change_percentage_24h_in_currency ?? c.price_change_percentage_24h),+ change_7d: num(c.price_change_percentage_7d_in_currency),+ market_cap: num(c.market_cap),+ volume_24h: num(c.total_volume),+ sparkline: downsample((c.sparkline_in_7d?.price || []).filter((v) => Number.isFinite(v)), 32),+ };+}++// CoinLore ticker row → normalized table row. `nameid` is a CoinGecko-compatible+// slug (e.g. "bitcoin") for the top coins, so the /coin/:id detail links keep+// working through a CoinGecko outage; long-tail slugs can diverge, but the table+// only falls back to CoinLore when CoinGecko itself is down — at which point the+// detail page is degraded regardless. No logos or 7d series in this feed → image+// null, sparkline empty (the page renders both gracefully).+function normalizeLoreRow(c) {+ const id = (c.nameid || '').trim();+ if (!id) return null;+ return {+ id,+ symbol: (c.symbol || '').toUpperCase(),+ name: c.name || id,+ image: null,+ rank: num(c.rank),+ price: num(c.price_usd),+ change_24h: num(c.percent_change_24h),+ change_7d: num(c.percent_change_7d),+ market_cap: num(c.market_cap_usd),+ volume_24h: num(c.volume24),+ sparkline: [],+ };+}++/**+ * Ranked market table with CoinGecko → CoinLore failover.+ *+ * CoinGecko is the only source with 7d sparklines and category scoping, so when+ * a `category` is requested the fallback is skipped (it can't honor the filter —+ * serving an unfiltered table would be wrong data). Without a category, CoinLore+ * backs up the plain top-N list. CoinLore caps a page at 100 rows.+ *+ * @param {{ page:number, perPage:number, category?:string }} opts+ * @returns {Promise<{ rows: object[], source: string }>}+ * @throws when every eligible source is down.+ */+export async function fetchMarketsTable({ page, perPage, category }) {+ const providers = [+ {+ name: 'coingecko',+ url:+ `${COINGECKO_BASE}/coins/markets?vs_currency=usd&order=market_cap_desc` ++ `&per_page=${perPage}&page=${page}&sparkline=true&price_change_percentage=24h,7d` ++ (category ? `&category=${encodeURIComponent(category)}` : ''),+ init: { headers: geckoHeaders() },+ parse: async (r) => {+ const raw = await r.json();+ if (!Array.isArray(raw)) return null;+ return raw.map(normalizeGeckoRow);+ },+ },+ ];+ if (!category) {+ const start = (page - 1) * perPage;+ const limit = Math.min(perPage, 100); // CoinLore hard-caps a page at 100+ providers.push({+ name: 'coinlore',+ url: `https://api.coinlore.com/api/tickers/?start=${start}&limit=${limit}`,+ parse: async (r) => {+ const raw = await r.json();+ const data = Array.isArray(raw?.data) ? raw.data : null;+ if (!data) return null;+ const rows = data.map(normalizeLoreRow).filter(Boolean);+ return rows.length ? rows : null;+ },+ });+ }+ const { value, source } = await fetchFirst(providers, { timeoutMs: 10_000, label: 'markets-table' });+ return { rows: value, source };+}diff --git a/api/_lib/market/token-market.js b/api/_lib/market/token-market.jsindex 4b878e2af..583135d40 100644--- a/api/_lib/market/token-market.js+++ b/api/_lib/market/token-market.js@@ -230,7 +230,21 @@ async function fromGeckoTerminal(mint) {);}-const SOURCES = [fromBirdeye, fromDexScreener, fromGeckoTerminal];+// DefiLlama coins oracle (keyless) — price-only, but a fully independent+// aggregator (its own multi-DEX sourcing), so it survives when Birdeye,+// DexScreener AND GeckoTerminal are simultaneously down/rate-limited. It carries+// no market cap / volume / liquidity / holders, so those stay null when it's the+// answering source — a price-only panel beats a blank one.+async function fromLlamaCoins(mint) {+ const key = `solana:${mint}`;+ const data = await fetchJson(`https://coins.llama.fi/prices/current/${key}`);+ const c = data?.coins?.[key];+ const price = num(c?.price);+ if (!(price > 0)) return null;+ return shape({ price_usd: price, decimals: num(c?.decimals) ?? 6 }, 'llama');+}++const SOURCES = [fromBirdeye, fromDexScreener, fromGeckoTerminal, fromLlamaCoins];// Store a value in the per-instance L1 cache (with the bounded-size eviction the// fetch path uses) and return it. Shared by the live, L2-hit, and lock-loserdiff --git a/api/_lib/sol-price.js b/api/_lib/sol-price.jsindex 4b414c6a7..07c188b29 100644--- a/api/_lib/sol-price.js+++ b/api/_lib/sol-price.js@@ -7,9 +7,12 @@// one shared implementation — see api/_lib/pump-alert-runner.js / pump-launch-feed.js// for the older inline copies this consolidates.//-// Four independent free sources, tried in order (failover-fetch cools a failing+// Seven independent free sources, tried in order (failover-fetch cools a failing// source for 60s so a CoinGecko rate-limit doesn't tax every valuation with a-// timeout). All four quote the same asset; any disagreement is sub-1% noise.+// timeout). They all quote the same asset; any disagreement is sub-1% noise.+// Exchange tickers (Kraken/Coinbase/Bitfinex), aggregators (CoinGecko/Jupiter/+// DefiLlama) and an on-chain oracle (DIA) fail independently, so it takes a+// near-total outage to exhaust the chain.import { fetchFirst } from '../../src/shared/failover-fetch.js';@@ -48,6 +51,30 @@ const PROVIDERS = [url: 'https://api.coinbase.com/v2/prices/SOL-USD/spot',parse: async (r) => asPrice((await r.json())?.data?.amount),},+ {+ // DefiLlama coins oracle — keyless, independent multi-DEX aggregation.+ name: 'llama',+ url: `https://coins.llama.fi/prices/current/solana:${WSOL}`,+ parse: async (r) => asPrice((await r.json())?.coins?.[`solana:${WSOL}`]?.price),+ },+ {+ // DIA on-chain oracle — keyless, a fully separate methodology from the+ // exchange tickers above, so it survives a broad CEX-API outage.+ name: 'dia',+ url: 'https://api.diadata.org/v1/assetQuotation/Solana/0x0000000000000000000000000000000000000000',+ parse: async (r) => asPrice((await r.json())?.Price),+ },+ {+ // Bitfinex public ticker. Bitfinex (unlike Binance) does NOT geo-block US+ // datacenter IPs, so it works from Cloud Run us-central1. Ticker array:+ // index 6 is LAST_PRICE.+ name: 'bitfinex',+ url: 'https://api-pub.bitfinex.com/v2/ticker/tSOLUSD',+ parse: async (r) => {+ const t = await r.json();+ return asPrice(Array.isArray(t) ? t[6] : null);+ },+ },];let _price = 0;diff --git a/api/coin/global.js b/api/coin/global.jsindex cde77254d..d749cfed1 100644--- a/api/coin/global.js+++ b/api/coin/global.js@@ -1,15 +1,16 @@// GET /api/coin/global// ---------------------------------------------------------------------------// Global market stats bar for the /coins page: total market cap, 24h volume,-// top-2 dominance shares, active coin count (CoinGecko /global) plus the-// Fear & Greed index (alternative.me — the standard free source). Each half is-// independent: if one upstream fails the other still renders. Cached 120s.+// top-2 dominance shares, active coin count plus the Fear & Greed index+// (alternative.me — the standard free source). The market stats read failover+// across three free sources (CoinGecko → CoinPaprika → CoinLore, see+// api/_lib/market-fallbacks.js) so a single-provider rate-limit no longer+// blanks the bar. Each half is independent: if one upstream fails the other+// still renders. Cached 120s.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { geckoFetch } from '../_lib/coingecko.js';--const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);+import { fetchGlobalMarket } from '../_lib/market-fallbacks.js';let _fng = null; // { value, expiresAt }const FNG_TTL_MS = 300_000;@@ -38,28 +39,11 @@ export default wrap(async (req, res) => {if (!rl.success) return rateLimited(res, rl);const [globalResult, fngResult] = await Promise.allSettled([- geckoFetch('/global', { ttlMs: 120_000 }),+ fetchGlobalMarket(),fetchFearGreed(),]);- let market = null;- if (globalResult.status === 'fulfilled') {- const g = globalResult.value?.data || {};- // Top-2 dominance entries come from the runtime response, largest first —- // no asset list is hardcoded here.- const dominance = Object.entries(g.market_cap_percentage || {})- .filter(([, v]) => Number.isFinite(v))- .sort((a, b) => b[1] - a[1])- .slice(0, 2)- .map(([sym, pct]) => ({ symbol: sym.toUpperCase(), pct }));- market = {- market_cap_usd: num(g.total_market_cap?.usd),- volume_24h_usd: num(g.total_volume?.usd),- market_cap_change_pct_24h: num(g.market_cap_change_percentage_24h_usd),- active_coins: num(g.active_cryptocurrencies),- dominance,- };- }+ const market = globalResult.status === 'fulfilled' ? globalResult.value : null;const fear_greed = fngResult.status === 'fulfilled' ? fngResult.value : null;if (!market && !fear_greed) {diff --git a/api/coin/markets.js b/api/coin/markets.jsindex 6b70b72a0..664263ee4 100644--- a/api/coin/markets.js+++ b/api/coin/markets.js@@ -11,29 +11,10 @@import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { geckoFetch } from '../_lib/coingecko.js';-import { downsample } from '../../src/shared/coin-format.js';+import { fetchMarketsTable } from '../_lib/market-fallbacks.js';const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);-function shapeRow(c) {- return {- id: c.id,- symbol: (c.symbol || '').toUpperCase(),- name: c.name || c.id,- image: c.image || null,- rank: num(c.market_cap_rank),- price: num(c.current_price),- change_24h: num(c.price_change_percentage_24h_in_currency ?? c.price_change_percentage_24h),- change_7d: num(c.price_change_percentage_7d_in_currency),- market_cap: num(c.market_cap),- volume_24h: num(c.total_volume),- sparkline: downsample(- (c.sparkline_in_7d?.price || []).filter((v) => Number.isFinite(v)),- 32,- ),- };-}-export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -68,14 +49,12 @@ export default wrap(async (req, res) => {if (category && !/^[a-z0-9-]{1,80}$/.test(category)) {return error(res, 400, 'bad_category', 'category must be a CoinGecko category id');}- const raw = await geckoFetch(- `/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=${perPage}&page=${page}` +- `&sparkline=true&price_change_percentage=24h,7d` +- (category ? `&category=${encodeURIComponent(category)}` : ''),- { ttlMs: 60_000, timeoutMs: 10_000 },- );- if (!Array.isArray(raw)) throw new Error('unexpected upstream payload');- return json(res, 200, { coins: raw.map(shapeRow), page, per_page: perPage, category: category || null }, {+ // CoinGecko primary → CoinLore fallback (see api/_lib/market-fallbacks.js).+ // A CoinGecko rate-limit no longer blanks the /coins table; CoinLore backs+ // it up (top-N only — category scoping and 7d sparklines are CoinGecko-only+ // and degrade gracefully).+ const { rows } = await fetchMarketsTable({ page, perPage, category });+ return json(res, 200, { coins: rows, page, per_page: perPage, category: category || null }, {'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300',});} catch {