Skip to content

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

feat: implement CoinGecko to DefiLlama failover for price fetching and add unit tests for market fallback normalizers

fudjia62e423dcfbcd
diff --git a/api/_lib/market-fallbacks.js b/api/_lib/market-fallbacks.js
index 9707949f1..095e1b389 100644
--- a/api/_lib/market-fallbacks.js
+++ b/api/_lib/market-fallbacks.js
@@ -37,6 +37,55 @@ function geckoHeaders() {
return h;
}
+const asPrice = (v) => {
+ const n = Number(v);
+ return Number.isFinite(n) && n > 0 ? n : null;
+};
+
+// ── Spot USD price by CoinGecko id ───────────────────────────────────────────
+// For the endpoints that price a headline asset (ETH for /gas, BTC for
+// /exchanges) via CoinGecko /simple/price. Both those reads were single-source;
+// DefiLlama's coins oracle is keyed by the SAME CoinGecko id (`coingecko:<id>`),
+// so it's a drop-in second source with no id-mapping. Returns a positive number
+// or throws when both are down; callers price best-effort and tolerate a throw.
+
+/**
+ * Live USD spot price for a CoinGecko coin id, CoinGecko → DefiLlama failover.
+ * @param {string} coingeckoId e.g. "ethereum", "bitcoin", "solana"
+ * @returns {Promise<number>} positive USD price
+ * @throws when every free source is down.
+ */
+export async function fetchCoinPriceUsd(coingeckoId) {
+ const id = String(coingeckoId || '').trim().toLowerCase();
+ if (!/^[a-z0-9][a-z0-9_-]{0,99}$/.test(id)) throw new Error(`bad coin id: ${coingeckoId}`);
+ const { value } = await fetchFirst(
+ [
+ {
+ name: 'coingecko',
+ url: `${COINGECKO_BASE}/simple/price?ids=${id}&vs_currencies=usd`,
+ init: { headers: geckoHeaders() },
+ parse: async (r) => asPrice((await r.json())?.[id]?.usd),
+ },
+ {
+ name: 'llama',
+ url: `https://coins.llama.fi/prices/current/coingecko:${id}`,
+ parse: async (r) => asPrice((await r.json())?.coins?.[`coingecko:${id}`]?.price),
+ },
+ ],
+ { timeoutMs: 6000, label: `price:${id}` },
+ );
+ return value;
+}
+
+/** Like fetchCoinPriceUsd but resolves to null instead of throwing. */
+export async function fetchCoinPriceUsdOrNull(coingeckoId) {
+ try {
+ return await fetchCoinPriceUsd(coingeckoId);
+ } catch {
+ return null;
+ }
+}
+
// ── Global market stats ──────────────────────────────────────────────────────
// Normalized shape: { market_cap_usd, volume_24h_usd, market_cap_change_pct_24h,
// active_coins, dominance: [{ symbol, pct }] }
diff --git a/api/coin/exchange.js b/api/coin/exchange.js
index 3527ff6f6..b87ed8178 100644
--- a/api/coin/exchange.js
+++ b/api/coin/exchange.js
@@ -15,6 +15,7 @@
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 { fetchCoinPriceUsdOrNull } from '../_lib/market-fallbacks.js';
const ID_RE = /^[a-z0-9_-]{1,60}$/i;
const DAYS = new Set([1, 7, 14, 30, 90, 180, 365]);
@@ -140,15 +141,9 @@ function shapeVolumeChart(raw) {
.filter(([ts, v]) => Number.isFinite(ts) && Number.isFinite(v));
}
-async function fetchBtcUsd() {
- try {
- const p = await geckoFetch('/simple/price?ids=bitcoin&vs_currencies=usd', { ttlMs: 60_000 });
- const v = num(p?.bitcoin?.usd);
- return v != null && v > 0 ? v : null;
- } catch {
- return null; // best-effort — the client falls back to BTC-only figures
- }
-}
+// CoinGecko → DefiLlama failover (see api/_lib/market-fallbacks.js); best-effort
+// — the client falls back to BTC-only figures if every source is down.
+const fetchBtcUsd = () => fetchCoinPriceUsdOrNull('bitcoin');
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
diff --git a/api/coin/exchanges.js b/api/coin/exchanges.js
index 8ae15a411..33c5eca4d 100644
--- a/api/coin/exchanges.js
+++ b/api/coin/exchanges.js
@@ -10,6 +10,7 @@
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 { fetchCoinPriceUsd } from '../_lib/market-fallbacks.js';
let _cache = null; // { value, expiresAt }
const TTL_MS = 300_000;
@@ -25,15 +26,14 @@ async function build() {
const [exResult, priceResult] = await Promise.allSettled([
geckoFetch('/exchanges?per_page=100&page=1', { ttlMs: TTL_MS }),
- geckoFetch('/simple/price?ids=bitcoin&vs_currencies=usd', { ttlMs: 60_000 }),
+ fetchCoinPriceUsd('bitcoin'),
]);
if (exResult.status !== 'fulfilled') throw exResult.reason || new Error('no exchange data');
const rows = Array.isArray(exResult.value) ? exResult.value : [];
if (!rows.length) throw new Error('empty exchange payload');
- const btcUsdRaw =
- priceResult.status === 'fulfilled' ? num(priceResult.value?.bitcoin?.usd) : null;
+ const btcUsdRaw = priceResult.status === 'fulfilled' ? num(priceResult.value) : null;
const btcUsd = btcUsdRaw != null && btcUsdRaw > 0 ? btcUsdRaw : null;
const exchanges = rows.map((e) => {
diff --git a/api/coin/gas.js b/api/coin/gas.js
index b1acd971f..6df35f862 100644
--- a/api/coin/gas.js
+++ b/api/coin/gas.js
@@ -5,11 +5,12 @@
// no key. It reads eth_feeHistory over the last ~20 blocks from a public RPC
// (with failover) and derives each tier as base fee + a priority-fee
// percentile (25th / 50th / 90th). Adds USD cost estimates for common actions
-// using the live ETH price from CoinGecko. Cached 15s in-memory + CDN.
+// using the live ETH price (CoinGecko → DefiLlama failover, see
+// api/_lib/market-fallbacks.js). Cached 15s in-memory + CDN.
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 { fetchCoinPriceUsd } from '../_lib/market-fallbacks.js';
// Keyless public JSON-RPC endpoints, tried in order until one answers.
const RPCS = [
@@ -105,14 +106,13 @@ async function build() {
const [fhResult, priceResult] = await Promise.allSettled([
feeHistory(),
- geckoFetch('/simple/price?ids=ethereum&vs_currencies=usd', { ttlMs: 60_000 }),
+ fetchCoinPriceUsd('ethereum'),
]);
if (fhResult.status !== 'fulfilled') throw fhResult.reason || new Error('no fee history');
const { baseFeeGwei, tiers } = computeTiers(fhResult.value);
- const ethUsd =
- priceResult.status === 'fulfilled' ? Number(priceResult.value?.ethereum?.usd) : null;
- const ethPrice = Number.isFinite(ethUsd) ? ethUsd : null;
+ const ethUsd = priceResult.status === 'fulfilled' ? Number(priceResult.value) : null;
+ const ethPrice = Number.isFinite(ethUsd) && ethUsd > 0 ? ethUsd : null;
// Cost per action = gasPrice(gwei) × 1e-9 ETH/gwei × gasUnits × ETH price.
const withCosts = tiers.map((t) => ({
diff --git a/public/changelog.json b/public/changelog.json
index fc3914012..3d6ccc311 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-11T07:01:31.915Z",
+ "generated_at": "2026-07-11T21:07:02.781Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index 15c614542..d8464820d 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-11T07:01:31.902Z",
+ "generated_at": "2026-07-11T21:07:02.765Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/shared/usd-price.js b/src/shared/usd-price.js
index 4d85bd8bd..490629734 100644
--- a/src/shared/usd-price.js
+++ b/src/shared/usd-price.js
@@ -2,45 +2,68 @@
* Client-side SOL/USD price helper — single source of truth for USD equivalents.
*
* USDC: treated as exactly $1 (it's a dollar-pegged stablecoin).
- * SOL: fetched from Jupiter Lite API (CoinGecko fallback), cached 60 s.
+ * SOL: four free, CORS-enabled feeds tried in order via the shared failover-
+ * fetch (Jupiter → CoinGecko → Coinbase → DefiLlama), cached 60 s. No
+ * single feed is a point of failure — mirrors the server-side
+ * api/_lib/sol-price.js chain, limited here to browser-CORS-safe hosts.
*
* Never hardcodes a SOL rate; degrades silently on feed failure so prices
* in USDC still show "≈ $X" while SOL amounts just show the raw amount.
*/
+import { fetchFirst } from './failover-fetch.js';
+
const SOL_MINT = 'So11111111111111111111111111111111111111112';
const CACHE_TTL_MS = 60_000;
+const asPrice = (v) => {
+ const n = Number(v);
+ return Number.isFinite(n) && n > 0 ? n : null;
+};
+
+// Ordered, all keyless and CORS-enabled (Access-Control-Allow-Origin: *), so
+// they work from the browser. Kraken/Bitfinex are omitted here (no CORS header)
+// though the server chain uses them.
+const SOL_FEEDS = [
+ {
+ name: 'jupiter',
+ url: `https://lite-api.jup.ag/price/v3?ids=${SOL_MINT}`,
+ parse: async (r) => {
+ const d = await r.json();
+ return asPrice(d?.[SOL_MINT]?.usdPrice ?? d?.[SOL_MINT]?.price);
+ },
+ },
+ {
+ name: 'coingecko',
+ url: 'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd',
+ parse: async (r) => asPrice((await r.json())?.solana?.usd),
+ },
+ {
+ name: 'coinbase',
+ url: 'https://api.coinbase.com/v2/prices/SOL-USD/spot',
+ parse: async (r) => asPrice((await r.json())?.data?.amount),
+ },
+ {
+ name: 'llama',
+ url: `https://coins.llama.fi/prices/current/solana:${SOL_MINT}`,
+ parse: async (r) => asPrice((await r.json())?.coins?.[`solana:${SOL_MINT}`]?.price),
+ },
+];
+
let _solPrice = 0;
let _solPriceAt = 0;
-/** Fetch (and cache) the live SOL/USD price. Throws if the feed is unavailable. */
+/** Fetch (and cache) the live SOL/USD price. Throws if every feed is unavailable. */
export async function getSolPriceUsd() {
if (Date.now() - _solPriceAt < CACHE_TTL_MS && _solPrice > 0) return _solPrice;
try {
- const r = await fetch(`https://lite-api.jup.ag/price/v3?ids=${SOL_MINT}`);
- if (r.ok) {
- const data = await r.json();
- const p = data?.[SOL_MINT]?.usdPrice ?? data?.[SOL_MINT]?.price ?? 0;
- if (Number(p) > 0) {
- _solPrice = Number(p);
- _solPriceAt = Date.now();
- return _solPrice;
- }
- }
- } catch { /* fall through to CoinGecko */ }
- try {
- const cg = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd');
- if (!cg.ok) throw new Error(`CoinGecko ${cg.status}`);
- const j = await cg.json();
- const p = j?.solana?.usd ?? 0;
- if (Number(p) > 0) {
- _solPrice = Number(p);
- _solPriceAt = Date.now();
- return _solPrice;
- }
- } catch { /* fall through */ }
- throw Object.assign(new Error('SOL price unavailable'), { code: 'price_unavailable' });
+ const { value } = await fetchFirst(SOL_FEEDS, { timeoutMs: 4000, label: 'sol-price-client' });
+ _solPrice = value;
+ _solPriceAt = Date.now();
+ return _solPrice;
+ } catch {
+ throw Object.assign(new Error('SOL price unavailable'), { code: 'price_unavailable' });
+ }
}
/** USDC → USD (1:1, pegged stablecoin). */
diff --git a/tests/market-fallbacks.test.js b/tests/market-fallbacks.test.js
new file mode 100644
index 000000000..e448b48bd
--- /dev/null
+++ b/tests/market-fallbacks.test.js
@@ -0,0 +1,125 @@
+/**
+ * Free-API market fallback normalizers — unit tests.
+ *
+ * Each provider (CoinGecko / CoinPaprika / CoinLore) returns a different upstream
+ * shape; the normalizers collapse them to the single shape the /coins endpoints
+ * emit. These tests pin that mapping with fixtures captured from the real live
+ * APIs, plus the miss semantics (a payload with no headline number returns null
+ * so failover-fetch moves to the next source rather than serving a blank).
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ normalizeGeckoGlobal,
+ normalizePaprikaGlobal,
+ normalizeLoreGlobal,
+ normalizeGeckoRow,
+} from '../api/_lib/market-fallbacks.js';
+
+describe('global stats normalizers', () => {
+ it('CoinGecko /global → top-2 dominance, largest first', () => {
+ const out = normalizeGeckoGlobal({
+ data: {
+ total_market_cap: { usd: 2_300_000_000_000 },
+ total_volume: { usd: 111_000_000_000 },
+ market_cap_change_percentage_24h_usd: 0.92,
+ active_cryptocurrencies: 11979,
+ market_cap_percentage: { btc: 55.56, eth: 10.1, usdt: 4.2 },
+ },
+ });
+ expect(out.market_cap_usd).toBe(2_300_000_000_000);
+ expect(out.volume_24h_usd).toBe(111_000_000_000);
+ expect(out.active_coins).toBe(11979);
+ expect(out.dominance).toEqual([
+ { symbol: 'BTC', pct: 55.56 },
+ { symbol: 'ETH', pct: 10.1 },
+ ]);
+ });
+
+ it('CoinPaprika /global → BTC dominance only', () => {
+ const out = normalizePaprikaGlobal({
+ market_cap_usd: 2_323_129_039_659,
+ volume_24h_usd: 111_219_134_442,
+ bitcoin_dominance_percentage: 55.56,
+ cryptocurrencies_number: 11979,
+ market_cap_change_24h: 0.92,
+ });
+ expect(out.market_cap_usd).toBe(2_323_129_039_659);
+ expect(out.active_coins).toBe(11979);
+ expect(out.market_cap_change_pct_24h).toBe(0.92);
+ expect(out.dominance).toEqual([{ symbol: 'BTC', pct: 55.56 }]);
+ });
+
+ it('CoinLore /global → BTC + ETH dominance from an array payload', () => {
+ const out = normalizeLoreGlobal([
+ {
+ coins_count: 14471,
+ total_mcap: 2_212_184_671_659,
+ total_volume: 59_664_122_147,
+ btc_d: '58.14',
+ eth_d: '10.10',
+ mcap_change: '1.04',
+ },
+ ]);
+ expect(out.market_cap_usd).toBe(2_212_184_671_659);
+ expect(out.active_coins).toBe(14471);
+ expect(out.market_cap_change_pct_24h).toBeCloseTo(1.04);
+ expect(out.dominance).toEqual([
+ { symbol: 'BTC', pct: 58.14 },
+ { symbol: 'ETH', pct: 10.1 },
+ ]);
+ });
+
+ it('returns null (a miss) when the headline market cap is absent', () => {
+ expect(normalizeGeckoGlobal({ data: {} })).toBeNull();
+ expect(normalizeGeckoGlobal(null)).toBeNull();
+ expect(normalizePaprikaGlobal({})).toBeNull();
+ expect(normalizeLoreGlobal([])).toBeNull();
+ expect(normalizeLoreGlobal([{ btc_d: '55' }])).toBeNull();
+ });
+});
+
+describe('markets table row normalizer', () => {
+ it('CoinGecko row → shaped row with a downsampled 7d sparkline', () => {
+ const spark = Array.from({ length: 168 }, (_, i) => 100 + i);
+ const row = normalizeGeckoRow({
+ id: 'bitcoin',
+ symbol: 'btc',
+ name: 'Bitcoin',
+ image: 'https://img/btc.png',
+ market_cap_rank: 1,
+ current_price: 64_000,
+ price_change_percentage_24h_in_currency: 0.58,
+ price_change_percentage_7d_in_currency: 1.71,
+ market_cap: 1_290_000_000_000,
+ total_volume: 12_700_000_000,
+ sparkline_in_7d: { price: spark },
+ });
+ expect(row.id).toBe('bitcoin');
+ expect(row.symbol).toBe('BTC');
+ expect(row.rank).toBe(1);
+ expect(row.price).toBe(64_000);
+ expect(row.change_24h).toBeCloseTo(0.58);
+ expect(row.change_7d).toBeCloseTo(1.71);
+ // Downsampled to at most 32 points, endpoints preserved.
+ expect(row.sparkline.length).toBeLessThanOrEqual(32);
+ expect(row.sparkline.length).toBeGreaterThan(1);
+ expect(row.sparkline[0]).toBe(100);
+ expect(row.sparkline[row.sparkline.length - 1]).toBe(spark[spark.length - 1]);
+ });
+
+ it('falls back to the plain 24h field and null-safe numbers', () => {
+ const row = normalizeGeckoRow({
+ id: 'x',
+ symbol: null,
+ name: null,
+ price_change_percentage_24h: -3.2,
+ current_price: 'not-a-number',
+ });
+ expect(row.symbol).toBe('');
+ expect(row.name).toBe('x');
+ expect(row.change_24h).toBeCloseTo(-3.2);
+ expect(row.price).toBeNull();
+ expect(row.sparkline).toEqual([]);
+ });
+});