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
fix(coin-tickers): fall back to the coin's DEX pairs when CoinGecko and CoinPaprika both miss
nirholasb625237dc04c
diff --git a/api/_lib/coin-fallbacks.js b/api/_lib/coin-fallbacks.jsindex 00beb3ec4..0df98a589 100644--- a/api/_lib/coin-fallbacks.js+++ b/api/_lib/coin-fallbacks.js@@ -499,6 +499,110 @@ export async function fetchFallbackTickers(cgId, { page = 1, perPage = 100 } = {return rows.slice(start, start + perPage);}+// ── DEX listings: the last ticker rung ──────────────────────────────────────+// CoinPaprika does not list every coin CoinGecko does (young DEX-only tokens+// above all), so with CoinGecko throttled those Markets tables answered 502.+// Every such coin that has a contract still trades somewhere DexScreener+// indexes, and its keyless token endpoint returns the coin's pairs across all+// chains in one call. The caller supplies the contract addresses (the coin page+// already holds them from /api/coin/detail): looking them up here would mean+// asking CoinGecko, the very source that just failed.++const DEXSCREENER_TOKENS = 'https://api.dexscreener.com/latest/dex/tokens';+// DexScreener answers at most 30 addresses per call; a coin page carries 8.+export const DEX_TICKER_MAX_ADDRESSES = 8;+const EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;+const BASE58_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++/** True for a contract address the DEX rung can look up (EVM or base58). */+export function isDexLookupAddress(v) {+ return typeof v === 'string' && (EVM_ADDRESS_RE.test(v) || BASE58_ADDRESS_RE.test(v));+}++// "pancakeswap-v3" -> "Pancakeswap V3": readable without a per-venue table.+function titleCase(id) {+ return String(id || '')+ .split(/[-_\s]+/)+ .filter(Boolean)+ .map((w) => w[0].toUpperCase() + w.slice(1))+ .join(' ');+}++/**+ * One DexScreener pair -> one /api/coin/tickers row. DexScreener carries no+ * order-book depth, spread or trust score, so those stay null exactly like the+ * CoinPaprika rows, and the table hides those columns for this source.+ */+export function normalizeDexPair(p) {+ const base = str(p?.baseToken?.symbol)?.toUpperCase() ?? null;+ const target = str(p?.quoteToken?.symbol)?.toUpperCase() ?? null;+ const dex = str(p?.dexId);+ const chain = str(p?.chainId);+ const url = str(p?.url);+ return {+ exchange: {+ id: dex,+ name: dex ? (chain ? `${titleCase(dex)} (${titleCase(chain)})` : titleCase(dex)) : null,+ logo: null,+ },+ base,+ target,+ pair: base && target ? `${base}/${target}` : null,+ price_usd: pos(p?.priceUsd),+ volume_usd: num(p?.volume?.h24),+ spread_pct: null,+ depth_up_usd: null,+ depth_down_usd: null,+ trust: null,+ stale: false,+ trade_url: url && /^https?:\/\//i.test(url) ? url : null,+ coin_id: null,+ target_coin_id: null,+ last_traded: null,+ };+}++/**+ * DEX pairs for a coin's contract addresses, in the /api/coin/tickers shape,+ * by 24h USD volume. Only pairs where the coin is the BASE token are kept, so+ * every row's price is this coin's price. DexScreener has no pagination: page 1+ * is the whole answer and later pages are empty.+ * @param {string[]} addresses contract addresses (validated by isDexLookupAddress)+ * @param {{page?: number, perPage?: number}} [opts]+ * @returns {Promise<object[]|null>} null when unavailable or nothing trades+ */+export async function fetchDexTickers(addresses, { page = 1, perPage = 100 } = {}) {+ const addrs = [...new Set((addresses || []).filter(isDexLookupAddress))].slice(0, DEX_TICKER_MAX_ADDRESSES);+ if (!addrs.length) return null;+ const wanted = new Set(addrs.map((a) => (a.startsWith('0x') ? a.toLowerCase() : a)));+ const rows = await cachedPayload(`dex-fallback:tickers:${[...addrs].sort().join(',')}`, () =>+ fetchFirstOrNull(+ [+ {+ name: 'dexscreener-tokens',+ url: `${DEXSCREENER_TOKENS}/${addrs.map(encodeURIComponent).join(',')}`,+ parse: async (r) => {+ const data = await r.json();+ const pairs = (Array.isArray(data?.pairs) ? data.pairs : []).filter((pair) => {+ const a = str(pair?.baseToken?.address);+ return a && wanted.has(a.startsWith('0x') ? a.toLowerCase() : a);+ });+ const out = pairs+ .map(normalizeDexPair)+ .filter((t) => t.exchange.name && t.price_usd != null)+ .sort((a, b) => (b.volume_usd ?? 0) - (a.volume_usd ?? 0));+ return out.length ? out : null;+ },+ },+ ],+ { timeoutMs: 8000, label: 'coin-dex-tickers' },+ ),+ );+ if (!rows) return null;+ const start = (Math.max(1, page) - 1) * perPage;+ return rows.slice(start, start + perPage);+}+// ── Price series ─────────────────────────────────────────────────────────────// DefiLlama's coins oracle is addressed by CoinGecko id (`coingecko:<id>`), so// this backs the chart for EVERY coin, not just the majors thatdiff --git a/api/coin/README.md b/api/coin/README.mdindex a1eec4cba..fc747d7c5 100644--- a/api/coin/README.md+++ b/api/coin/README.md@@ -18,7 +18,7 @@ All endpoints are `GET`, CORS-open, and rate-limited per client IP via [`../_lib| `GET /api/coin/global` | /coins stats bar (market cap, volume, dominance, Fear & Greed) | CoinGecko, CoinPaprika, CoinLore failover plus alternative.me || `GET /api/coin/detail?id=<id>` or `?contract=<solana-mint>` | /coin/:id profile | CoinGecko `/coins/{id}` || `GET /api/coin/ohlc?id=<id>&days=<1\|7\|30\|90\|365>` | /coin/:id price chart | CoinGecko `market_chart`, Kraken/Coinbase candle fallback |-| `GET /api/coin/tickers?id=<id>&page=1` | /coin/:id exchange listings table | CoinGecko `/coins/{id}/tickers` |+| `GET /api/coin/tickers?id=<id>&page=1[&contracts=<addr,...>]` | /coin/:id exchange listings table | CoinGecko `/coins/{id}/tickers`, CoinPaprika markets fallback, then the coin's DEX pairs from DexScreener when `contracts` (up to 8 EVM or base58 addresses, from the detail payload's `platforms`) is passed; `source` names the rung that answered || `GET /api/coin/pool?address=<token>&network=<net>` | /coin/:id GeckoTerminal chart embed (pool resolution) | GeckoTerminal via [`../_lib/market/ohlcv.js`](../_lib/market/ohlcv.js) || `GET /api/coin/dextools?address=<token>[&network=<net>][&from=<surface>]` | Every DEXTools link on three.ws (terminal links, coin cards, dashboards). 302s to the token's DEXTools pair page and counts the visit per UTC day, token and sending surface in `dextools_referrals` (aggregate only, no visitor data). $THREE is pinned to the pair its Social Boost wins are credited to; a token with no resolvable pool lands on its token-keyed DEXTools page. Build links with `dextoolsTokenUrl()` in [`src/shared/trading-terminals.js`](../../src/shared/trading-terminals.js) | Pool from [`../_lib/market/ohlcv.js`](../_lib/market/ohlcv.js), count in Postgres || `GET /api/coin/news?q=<coin name>&limit=8` | /coin/:id related-news rail | Native aggregator [`../_lib/news.js`](../_lib/news.js) |diff --git a/api/coin/tickers.js b/api/coin/tickers.jsindex 3ab0f629d..3a6b0851f 100644--- a/api/coin/tickers.js+++ b/api/coin/tickers.js@@ -11,11 +11,23 @@// so the Markets table falls back to CoinPaprika's per-coin markets feed// (api/_lib/coin-fallbacks.js) rather than 502ing the whole section. A 404 is// an answer about a real coin id and never falls back.+//+// CoinPaprika does not list every coin, and those Markets tables still 502'd+// whenever CoinGecko was throttled. The last rung is the coin's DEX pairs from+// DexScreener, looked up by the contract addresses the caller passes in+// `contracts` (comma-separated; the coin page has them from /api/coin/detail).+// Without addresses, or when nothing trades, the 502 stands: an honest outage+// beats an invented listing.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { geckoFetch, isPlausibleCoinId } from '../_lib/coingecko.js';-import { fetchFallbackTickers } from '../_lib/coin-fallbacks.js';+import {+ fetchFallbackTickers,+ fetchDexTickers,+ isDexLookupAddress,+ DEX_TICKER_MAX_ADDRESSES,+} from '../_lib/coin-fallbacks.js';const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);@@ -81,6 +93,14 @@ export default wrap(async (req, res) => {return error(res, 400, 'bad_page', 'page must be an integer between 1 and 10');}+ // Optional DEX-rung hint. Malformed entries are dropped rather than+ // rejected: the hint only matters on the fallback path.+ const contracts = (params.get('contracts') || '')+ .split(',')+ .map((v) => v.trim())+ .filter(isDexLookupAddress)+ .slice(0, DEX_TICKER_MAX_ADDRESSES);+const cacheHeaders = {'cache-control': 'public, max-age=60, s-maxage=120, stale-while-revalidate=600',};@@ -100,6 +120,11 @@ export default wrap(async (req, res) => {console.warn(`[coin/tickers] ${id}: coingecko failed (${err?.status || err?.name}); served from coinpaprika`);return json(res, 200, { tickers, page, count: tickers.length, source: 'coinpaprika' }, cacheHeaders);}+ const dexTickers = contracts.length ? await fetchDexTickers(contracts, { page }) : null;+ if (dexTickers) {+ console.warn(`[coin/tickers] ${id}: coingecko failed (${err?.status || err?.name}); served from dexscreener`);+ return json(res, 200, { tickers: dexTickers, page, count: dexTickers.length, source: 'dexscreener' }, cacheHeaders);+ }return error(res, 502, 'upstream_error', 'exchange listings are unavailable right now — retry shortly');}});diff --git a/data/changelog.json b/data/changelog.jsonindex afe1db148..f829bf6c8 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-08",+ "title": "Coin pages keep their Markets table when the listing sources are busy",+ "summary": "When both of our exchange-listing sources were rate-limited, a coin page's Markets table could show an error for coins only one of them lists. It now falls back to the coin's live DEX trading pairs, found by its contract address, with each pair's venue, chain, price, 24h volume and a link to trade it.",+ "tags": [+ "fix"+ ],+ "link": "/coins"+ },{"date": "2026-10-08","title": "3D Studio results now hand every agent plain links to the model",diff --git a/src/coin-page.js b/src/coin-page.jsindex aaea60846..089c1605c 100644--- a/src/coin-page.js+++ b/src/coin-page.js@@ -1014,8 +1014,12 @@ async function loadMarkets(coin) {renderMarkets(coin);try {const next = marketsState.page + 1;+ // The coin's contracts let the server fall back to its DEX pairs when+ // both listing sources are down; omitted for coins with none.+ const contracts = Object.values(coin.platforms || {}).filter(Boolean).slice(0, 8).join(',');const { tickers, count, source } = await getJson(- `/api/coin/tickers?id=${encodeURIComponent(coin.id)}&page=${next}`,+ `/api/coin/tickers?id=${encodeURIComponent(coin.id)}&page=${next}` ++ (contracts ? `&contracts=${encodeURIComponent(contracts)}` : ''),);marketsState.page = next;// Only the primary source carries spread/depth. Once any page arrivesdiff --git a/tests/api/coin-detail-fallback.test.js b/tests/api/coin-detail-fallback.test.jsindex 5ec8c7eec..01ee05deb 100644--- a/tests/api/coin-detail-fallback.test.js+++ b/tests/api/coin-detail-fallback.test.js@@ -28,10 +28,18 @@ vi.mock('../../api/_lib/coingecko.js', () => ({const fetchFallbackCoinDetail = vi.fn();const fetchFallbackTickers = vi.fn();-vi.mock('../../api/_lib/coin-fallbacks.js', () => ({- fetchFallbackCoinDetail: (...args) => fetchFallbackCoinDetail(...args),- fetchFallbackTickers: (...args) => fetchFallbackTickers(...args),-}));+vi.mock('../../api/_lib/coin-fallbacks.js', async (importActual) => {+ const actual = await importActual();+ return {+ fetchFallbackCoinDetail: (...args) => fetchFallbackCoinDetail(...args),+ fetchFallbackTickers: (...args) => fetchFallbackTickers(...args),+ // The DEX rung only runs when the caller names contracts; none of these+ // requests do, so the real helpers stay inert.+ fetchDexTickers: actual.fetchDexTickers,+ isDexLookupAddress: actual.isDexLookupAddress,+ DEX_TICKER_MAX_ADDRESSES: actual.DEX_TICKER_MAX_ADDRESSES,+ };+});const detail = (await import('../../api/coin/detail.js')).default;const tickers = (await import('../../api/coin/tickers.js')).default;diff --git a/tests/api/coin-tickers-page.test.js b/tests/api/coin-tickers-page.test.jsindex 1623ff242..add488d31 100644--- a/tests/api/coin-tickers-page.test.js+++ b/tests/api/coin-tickers-page.test.js@@ -26,9 +26,18 @@ vi.mock('../../api/_lib/coingecko.js', () => ({}));const fetchFallbackTickers = vi.fn();-vi.mock('../../api/_lib/coin-fallbacks.js', () => ({- fetchFallbackTickers: (...a) => fetchFallbackTickers(...a),-}));+const fetchDexTickers = vi.fn();+vi.mock('../../api/_lib/coin-fallbacks.js', async (importActual) => {+ const actual = await importActual();+ return {+ fetchFallbackTickers: (...a) => fetchFallbackTickers(...a),+ fetchDexTickers: (...a) => fetchDexTickers(...a),+ isDexLookupAddress: actual.isDexLookupAddress,+ DEX_TICKER_MAX_ADDRESSES: actual.DEX_TICKER_MAX_ADDRESSES,+ };+});++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';const tickers = (await import('../../api/coin/tickers.js')).default;@@ -61,6 +70,7 @@ describe('/api/coin/tickers page contract', () => {beforeEach(() => {geckoFetch.mockReset();fetchFallbackTickers.mockReset();+ fetchDexTickers.mockReset();geckoFetch.mockResolvedValue({ tickers: [upstreamTicker] });});@@ -152,11 +162,39 @@ describe('/api/coin/tickers page contract', () => {expect(fetchFallbackTickers).toHaveBeenCalledWith('bitcoin', { page: 3 });});- it('502s when both sources are down', async () => {+ it('502s when both sources are down and the caller named no contracts', async () => {geckoFetch.mockRejectedValue(new Error('gateway timeout'));fetchFallbackTickers.mockResolvedValue(null);const { res, body } = await call('id=bitcoin&page=1');expect(res.statusCode).toBe(502);expect(body.error).toBe('upstream_error');+ expect(fetchDexTickers).not.toHaveBeenCalled();+ });++ // Production 2026-10-08: coins CoinPaprika does not list answered 502 on+ // every CoinGecko throttle. Their DEX pairs are the last real source.+ it('falls back to the coin\'s DEX pairs when CoinGecko and CoinPaprika both miss', async () => {+ const err = new Error('CoinGecko 429');+ err.status = 429;+ geckoFetch.mockRejectedValue(err);+ fetchFallbackTickers.mockResolvedValue(null);+ fetchDexTickers.mockResolvedValue([{ pair: 'THREE/SOL', price_usd: 0.0004 }]);+ const { res, body } = await call(+ `id=three-synthetic&page=1&contracts=${THREE_MINT},not-an-address,${'0x' + 'ab'.repeat(20)}`,+ );+ expect(res.statusCode).toBe(200);+ expect(body.source).toBe('dexscreener');+ expect(body.tickers).toHaveLength(1);+ // Malformed entries are dropped, valid ones passed through in order.+ expect(fetchDexTickers).toHaveBeenCalledWith([THREE_MINT, '0x' + 'ab'.repeat(20)], { page: 1 });+ });++ it('still 502s when the DEX rung finds nothing either', async () => {+ geckoFetch.mockRejectedValue(new Error('gateway timeout'));+ fetchFallbackTickers.mockResolvedValue(null);+ fetchDexTickers.mockResolvedValue(null);+ const { res, body } = await call(`id=three-synthetic&page=1&contracts=${THREE_MINT}`);+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');});});diff --git a/tests/coin-fallbacks.test.js b/tests/coin-fallbacks.test.jsindex fc5f6cdf4..8127f4419 100644--- a/tests/coin-fallbacks.test.js+++ b/tests/coin-fallbacks.test.js@@ -32,6 +32,9 @@ import {fetchLlamaChart,fetchFallbackTickers,fetchFallbackCoinDetail,+ fetchDexTickers,+ normalizeDexPair,+ isDexLookupAddress,} from '../api/_lib/coin-fallbacks.js';import { isPaprikaBenched, resetPaprikaHealth } from '../api/_lib/coinpaprika.js';@@ -502,3 +505,69 @@ describe('DefiLlama chart fallback', () => {expect(await fetchLlamaChart('', 30)).toBeNull();});});++// The last ticker rung: a coin's DEX pairs by contract address. Fixtures use+// $THREE and synthetic venue ids only.+describe('DEX ticker rung', () => {+ const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+ const pair = (over = {}) => ({+ chainId: 'solana',+ dexId: 'example-dex-v2',+ url: 'https://dexscreener.com/solana/examplepair',+ baseToken: { address: MINT, symbol: 'three' },+ quoteToken: { address: 'So11111111111111111111111111111111111111112', symbol: 'sol' },+ priceUsd: '0.0004',+ volume: { h24: 1000 },+ ...over,+ });++ afterEach(() => vi.unstubAllGlobals());++ it('accepts EVM and base58 contracts and rejects anything else', () => {+ expect(isDexLookupAddress(MINT)).toBe(true);+ expect(isDexLookupAddress('0x' + 'ab'.repeat(20))).toBe(true);+ expect(isDexLookupAddress('0x123')).toBe(false);+ expect(isDexLookupAddress('three-synthetic')).toBe(false);+ });++ it('maps a pair onto the Markets table row with venue and chain named', () => {+ const row = normalizeDexPair(pair());+ expect(row).toMatchObject({+ exchange: { id: 'example-dex-v2', name: 'Example Dex V2 (Solana)', logo: null },+ pair: 'THREE/SOL',+ price_usd: 0.0004,+ volume_usd: 1000,+ trust: null,+ trade_url: 'https://dexscreener.com/solana/examplepair',+ });+ expect(normalizeDexPair(pair({ url: 'javascript:alert(1)' })).trade_url).toBeNull();+ });++ it('keeps only pairs where the coin is the base token, by volume, and caches the answer', async () => {+ const fetchMock = vi.fn(async () =>+ new Response(+ JSON.stringify({+ pairs: [+ pair({ dexId: 'small-dex', volume: { h24: 10 } }),+ pair({ dexId: 'big-dex', volume: { h24: 5000 } }),+ // The coin as the QUOTE side: its priceUsd is another token's.+ pair({ dexId: 'quote-side', baseToken: { address: 'THREEsynthetic1111111111111111111111111111', symbol: 'x' } }),+ ],+ }),+ { status: 200 },+ ),+ );+ vi.stubGlobal('fetch', fetchMock);+ const rows = await fetchDexTickers([MINT, 'bad'], { page: 1 });+ expect(rows.map((r) => r.exchange.id)).toEqual(['big-dex', 'small-dex']);+ expect(String(fetchMock.mock.calls[0][0])).toContain(`/latest/dex/tokens/${MINT}`);+ expect(await fetchDexTickers([MINT], { page: 2 })).toEqual([]);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('answers null with no addresses, and when nothing trades', async () => {+ expect(await fetchDexTickers([], { page: 1 })).toBeNull();+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ pairs: [] }), { status: 200 })));+ expect(await fetchDexTickers(['0x' + 'cd'.repeat(20)], { page: 1 })).toBeNull();+ });+});