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
refactor: token market extraction, three-token cleanup, price updates
nirholasc140f59a2bec
diff --git a/api/_lib/market/token-market.js b/api/_lib/market/token-market.jsnew file mode 100644index 000000000..81a3fb144--- /dev/null+++ b/api/_lib/market/token-market.js@@ -0,0 +1,177 @@+// Multi-source token market data with sequential failover + stale cache.+//+// Sources, in priority order:+// 1. Birdeye (keyed) — richest: includes holders + circulating supply.+// 2. DexScreener (keyless) — price, 24h change, volume, liquidity, market cap.+// 3. GeckoTerminal (keyless) — price, market cap, volume, liquidity, supply.+//+// Each source is normalized to one shape; a fallback source that lacks a field+// (e.g. DexScreener has no holder count) leaves it null rather than failing the+// whole read. On a cold cache where every source is down/rate-limited we return+// the last good value for up to STALE_MAX_MS, then null — callers render what+// they can and never crash on a single upstream blip. This is the market-data+// analogue of the RPC failover layer.++const BIRDEYE_BASE = 'https://public-api.birdeye.so';+const DEXSCREENER_BASE = 'https://api.dexscreener.com/latest/dex/tokens';+const GECKOTERMINAL_BASE = 'https://api.geckoterminal.com/api/v2/networks/solana/tokens';++const FETCH_TIMEOUT_MS = 6000;+const DEFAULT_TTL_MS = 30_000;+const STALE_MAX_MS = 5 * 60_000;++const _cache = new Map(); // mint → { value, expires, fetchedAt }+const _warnedAt = new Map();+const WARN_COOLDOWN_MS = 60_000;++function warnThrottled(key, msg) {+ const now = Date.now();+ if (now - (_warnedAt.get(key) || 0) < WARN_COOLDOWN_MS) return;+ _warnedAt.set(key, now);+ console.warn(msg);+}++async function fetchJson(url, opts = {}) {+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);+ try {+ const r = await fetch(url, { ...opts, signal: ctrl.signal });+ if (!r.ok) throw new Error(`${r.status}`);+ return await r.json();+ } finally {+ clearTimeout(timer);+ }+}++function shape(partial, source) {+ return {+ price_usd: null,+ price_change_24h: null,+ market_cap: null,+ volume_24h: null,+ holders: null,+ liquidity: null,+ supply: null,+ decimals: 6,+ source,+ ...partial,+ };+}++const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+};++async function fromBirdeye(mint) {+ const key = process.env.BIRDEYE_API_KEY;+ if (!key) return null;+ const data = await fetchJson(`${BIRDEYE_BASE}/defi/token_overview?address=${mint}`, {+ headers: { 'X-API-KEY': key, accept: 'application/json' },+ });+ const ov = data?.data;+ if (!ov || !(num(ov.price) > 0)) return null;+ return shape(+ {+ price_usd: num(ov.price),+ price_change_24h: num(ov.priceChange24hPercent),+ market_cap: num(ov.mc ?? ov.marketCap),+ volume_24h: num(ov.v24hUSD ?? ov.volume24h),+ holders: num(ov.holder ?? ov.uniqueWallet30m),+ liquidity: num(ov.liquidity),+ supply: num(ov.supply),+ decimals: num(ov.decimals) ?? 6,+ },+ 'birdeye',+ );+}++async function fromDexScreener(mint) {+ const data = await fetchJson(`${DEXSCREENER_BASE}/${mint}`);+ const pairs = Array.isArray(data?.pairs) ? data.pairs : [];+ if (!pairs.length) return null;+ // The deepest-liquidity pair is the canonical market for price/volume.+ const best = pairs.reduce((a, b) => ((b.liquidity?.usd || 0) > (a.liquidity?.usd || 0) ? b : a));+ const price = num(best.priceUsd);+ if (!(price > 0)) return null;+ const marketCap = num(best.marketCap ?? best.fdv);+ return shape(+ {+ price_usd: price,+ price_change_24h: num(best.priceChange?.h24),+ market_cap: marketCap,+ volume_24h: num(best.volume?.h24),+ liquidity: num(best.liquidity?.usd),+ // supply ≈ marketCap / price when the source omits it explicitly+ supply: marketCap && price ? marketCap / price : null,+ },+ 'dexscreener',+ );+}++async function fromGeckoTerminal(mint) {+ const data = await fetchJson(`${GECKOTERMINAL_BASE}/${mint}`);+ const a = data?.data?.attributes;+ const price = num(a?.price_usd);+ if (!(price > 0)) return null;+ const decimals = num(a.decimals) ?? 6;+ const totalSupplyAtomic = num(a.total_supply);+ return shape(+ {+ price_usd: price,+ market_cap: num(a.market_cap_usd) ?? num(a.fdv_usd),+ volume_24h: num(a.volume_usd?.h24),+ liquidity: num(a.total_reserve_in_usd),+ supply: totalSupplyAtomic != null ? totalSupplyAtomic / 10 ** decimals : null,+ decimals,+ },+ 'geckoterminal',+ );+}++const SOURCES = [fromBirdeye, fromDexScreener, fromGeckoTerminal];++/**+ * Normalized market data for a mint, with multi-source failover and a stale+ * cache. Returns null only when every source fails and no recent value exists.+ * @param {string} mint+ * @param {{ fresh?: boolean, ttlMs?: number }} [opts]+ */+export async function fetchTokenMarketData(mint, { fresh = false, ttlMs = DEFAULT_TTL_MS } = {}) {+ const now = Date.now();+ const hit = _cache.get(mint);+ if (!fresh && hit && hit.expires > now) return hit.value;++ for (const src of SOURCES) {+ try {+ const result = await src(mint);+ if (result && result.price_usd > 0) {+ _cache.set(mint, { value: result, expires: now + ttlMs, fetchedAt: now });+ if (_cache.size > 256) _cache.delete(_cache.keys().next().value);+ return result;+ }+ } catch (err) {+ warnThrottled(`${mint}:${src.name}`, `[market] ${src.name} failed for ${mint.slice(0, 6)}…: ${err?.message}`);+ }+ }++ // Every source failed — serve the last good value if it's still fresh enough.+ if (hit && now - hit.fetchedAt < STALE_MAX_MS) {+ warnThrottled(`${mint}:stale`, `[market] all sources failed for ${mint.slice(0, 6)}… — serving stale (${Math.round((now - hit.fetchedAt) / 1000)}s old)`);+ hit.expires = now + Math.min(ttlMs, 15_000); // brief backoff before retrying upstreams+ return hit.value;+ }+ return null;+}++/** Just the USD price — convenience for the price/quote path. */+export async function fetchTokenPriceUsd(mint, opts) {+ const md = await fetchTokenMarketData(mint, opts);+ return md?.price_usd ?? null;+}++/** Test seam: clear the in-memory caches between cases. */+export function __resetMarketCache() {+ _cache.clear();+ _warnedAt.clear();+}diff --git a/api/_lib/token/price.js b/api/_lib/token/price.jsindex f00a9fcb8..cc903957b 100644--- a/api/_lib/token/price.js+++ b/api/_lib/token/price.js@@ -2,11 +2,13 @@//// Price source mirrors the rest of the platform: Jupiter Lite is the primary// Solana price feed (same source api/_lib/balances.js uses; no key, knows-// pump.fun bonding curves), with Birdeye as a keyed fallback (the source-// api/three-token uses). A short cache smooths bursts without letting a quote+// pump.fun bonding curves). If Jupiter is down it falls through to the shared+// market module (Birdeye → DexScreener → GeckoTerminal), so a single feed outage+// never blocks a paid quote. A short cache smooths bursts without letting a quote// drift far from the live market — the quote's own expiry is the hard guard.import { cacheGet, cacheSet } from '../cache.js';+import { fetchTokenMarketData } from '../market/token-market.js';import { TOKEN_MINT, TOKEN_DECIMALS, ATOMICS_PER_TOKEN } from './config.js';const PRICE_TTL_S = 30;@@ -30,16 +32,6 @@ async function jupiterPrice(mint) {return Number.isFinite(n) && n > 0 ? n : null;}-async function birdeyePrice(mint) {- const key = process.env.BIRDEYE_API_KEY;- if (!key) return null;- const data = await fetchJson(`https://public-api.birdeye.so/defi/price?address=${mint}`, {- headers: { 'X-API-KEY': key, accept: 'application/json' },- });- const n = Number(data?.data?.value);- return Number.isFinite(n) && n > 0 ? n : null;-}-/*** Live USD price of one whole token. Throws 503 price_unavailable when no feed* returns a usable number — a paid action must never proceed on a guessed price.@@ -61,11 +53,14 @@ export async function getTokenPriceUsd({ fresh = false } = {}) {console.warn('[token] jupiter price failed:', err?.message);}if (!priceUsd) {- try {- priceUsd = await birdeyePrice(TOKEN_MINT);- if (priceUsd) source = 'birdeye';- } catch (err) {- console.warn('[token] birdeye price failed:', err?.message);+ // Jupiter down → shared market module: Birdeye → DexScreener → GeckoTerminal.+ const md = await fetchTokenMarketData(TOKEN_MINT, { fresh }).catch((err) => {+ console.warn('[token] market-data fallback failed:', err?.message);+ return null;+ });+ if (md?.price_usd) {+ priceUsd = md.price_usd;+ source = md.source;}}if (!priceUsd) {diff --git a/api/three-token/[action].js b/api/three-token/[action].jsindex ab25482cb..597f9a131 100644--- a/api/three-token/[action].js+++ b/api/three-token/[action].js@@ -6,17 +6,19 @@* GET /api/three-token/burns — deploy-to-burn ledger (per-deploy burns)* GET /api/three-token/activity — protocol activity feed*- * Market data (price, market cap, supply, holders) is sourced from Birdeye.- * Protocol data (agents, revenue, deploy burns) is derived from the- * application database; deploy burns = deployed agents × AGENT_DEPLOY_BURN.+ * Market data (price, market cap, supply, holders) comes from the shared market+ * module — Birdeye → DexScreener → GeckoTerminal failover with a stale cache —+ * so a Birdeye 429 transparently falls over to the keyless sources instead of+ * blanking the price panel. Protocol data (agents, revenue, deploy burns) is+ * derived from the application database; deploy burns = deployed agents ×+ * AGENT_DEPLOY_BURN.*/import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, wrap } from '../_lib/http.js';import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';--const BIRDEYE_BASE = 'https://public-api.birdeye.so';+import { fetchTokenMarketData } from '../_lib/market/token-market.js';// Protocol tokenomics (fixed parameters of the $THREE protocol).// AGENT_DEPLOY_BURN: $THREE permanently burned each time an agent is deployed.@@ -24,95 +26,6 @@ const BIRDEYE_BASE = 'https://public-api.birdeye.so';const AGENT_DEPLOY_BURN = 1000;const REVENUE_SHARE_POOL_PCT = 10;-const _cache = new Map();-// How long a last-good value stays usable as a stale fallback after its TTL-// expires. Birdeye rate-limits the shared key under bursty traffic; rather than-// drop the price to null (and spam the error log) on every 429, we serve the-// last good market data for up to STALE_MAX_MS while the limit clears. Token-// price/market-cap drifting a couple of minutes is invisible to the UI; a blank-// price panel is not.-const STALE_MAX_MS = 5 * 60_000;--// One warn per key per cooldown so a sustained Birdeye 429 can't itself flood the-// logs (the very failure mode brief 09 is about).-const _warnedAt = new Map();-const STALE_WARN_COOLDOWN_MS = 60_000;-function warnThrottled(key, msg) {- const now = Date.now();- if (now - (_warnedAt.get(key) || 0) < STALE_WARN_COOLDOWN_MS) return;- _warnedAt.set(key, now);- console.warn(msg);-}-function warnStaleOnce(url, status) {- warnThrottled(url, `[three-token] birdeye ${status} — serving last good value (stale) for ${url.split('?')[0]}`);-}--async function cachedFetch(url, headers, ttlMs = 30_000) {- const now = Date.now();- const hit = _cache.get(url);- if (hit && hit.expires > now) return hit.value;-- let resp;- try {- resp = await fetch(url, { headers });- } catch (err) {- // Network failure — fall back to stale if we have a usable copy.- if (hit && now - hit.fetchedAt < STALE_MAX_MS) {- warnStaleOnce(url, 'fetch-failed');- return hit.value;- }- throw err;- }- if (!resp.ok) {- const text = await resp.text().catch(() => '');- // Rate-limited / upstream error: serve the last good value if it's still- // within the stale window instead of throwing and blanking the price.- if (hit && now - hit.fetchedAt < STALE_MAX_MS) {- warnStaleOnce(url, resp.status);- // Refresh the TTL briefly so we don't re-hit the limited endpoint on- // every request while it's throttled (cheap backoff).- hit.expires = now + Math.min(ttlMs, 15_000);- return hit.value;- }- throw new Error(`Birdeye ${resp.status}: ${text.slice(0, 200)}`);- }- const value = await resp.json();- _cache.set(url, { value, expires: now + ttlMs, fetchedAt: now });- if (_cache.size > 128) {- const oldest = _cache.keys().next().value;- _cache.delete(oldest);- }- return value;-}--async function fetchTokenOverview(apiKey) {- const headers = { 'X-API-KEY': apiKey, accept: 'application/json' };- // token_overview already carries price + 24h change alongside market cap,- // volume, holders, liquidity and supply — so one call covers everything the- // stats panel needs. We deliberately do NOT also hit /defi/price: a second- // request per stats load only doubles pressure on the shared, rate-limited- // Birdeye key (the source of the 429s).- const resp = await cachedFetch(`${BIRDEYE_BASE}/defi/token_overview?address=${THREE_MINT}`, headers, 60_000);- const ov = resp?.data ?? null;- return {- price: ov?.price ?? null,- priceChange24h: ov?.priceChange24hPercent ?? null,- overview: ov,- };-}--// Birdeye 429/5xx on a cold cache (no last-good value to fall back to) is an-// upstream throttle, not a bug on our side — warn (throttled) instead of-// error-spamming. A genuine client/auth error (4xx other than 429) still logs.-function logBirdeyeFailure(err) {- const status = Number(/Birdeye (\d+)/.exec(err?.message || '')?.[1] || 0);- if (status === 429 || status >= 500) {- warnThrottled('birdeye-cold', `[three-token] birdeye ${status} (cold cache) — price temporarily unavailable`);- return;- }- console.error('[three-token] birdeye error:', err?.message);-}-async function fetchPlatformMetrics() {const [agentCount, revenueData, paymentCount] = await Promise.all([sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`.catch(@@ -177,21 +90,12 @@ export default wrap(async (req, res) => {const parts = url.pathname.split('/').filter(Boolean);const action = parts[2];- const apiKey = process.env.BIRDEYE_API_KEY;-if (action === 'stats') {- const [tokenData, platform] = await Promise.all([- apiKey- ? fetchTokenOverview(apiKey).catch((err) => {- logBirdeyeFailure(err);- return { price: null, priceChange24h: null, overview: null };- })- : { price: null, priceChange24h: null, overview: null },+ const [market, platform] = await Promise.all([+ fetchTokenMarketData(THREE_MINT).catch(() => null),fetchPlatformMetrics(),]);- const ov = tokenData.overview || {};-return json(res,200,@@ -199,14 +103,15 @@ export default wrap(async (req, res) => {token: {mint: THREE_MINT,symbol: '$THREE',- price_usd: tokenData.price,- price_change_24h: tokenData.priceChange24h,- market_cap: ov.mc ?? ov.marketCap ?? null,- volume_24h: ov.v24hUSD ?? ov.volume24h ?? null,- holders: ov.holder ?? ov.uniqueWallet30m ?? null,- liquidity: ov.liquidity ?? null,- supply: ov.supply ?? null,- decimals: ov.decimals ?? 6,+ price_usd: market?.price_usd ?? null,+ price_change_24h: market?.price_change_24h ?? null,+ market_cap: market?.market_cap ?? null,+ volume_24h: market?.volume_24h ?? null,+ holders: market?.holders ?? null,+ liquidity: market?.liquidity ?? null,+ supply: market?.supply ?? null,+ decimals: market?.decimals ?? 6,+ source: market?.source ?? null,},protocol: {total_agents: platform.total_agents,@@ -227,24 +132,21 @@ export default wrap(async (req, res) => {const user = await getSessionUser(req, res);if (!user) return error(res, 401, 'unauthorized', 'sign in required');- const [platform, tokenData] = await Promise.all([+ const [platform, market] = await Promise.all([fetchPlatformMetrics(),- apiKey- ? fetchTokenOverview(apiKey).catch(() => ({ price: null, overview: null }))- : { price: null, overview: null },+ fetchTokenMarketData(THREE_MINT).catch(() => null),]);- const ov = tokenData.overview || {};- const totalSupply = ov.supply ?? null;+ const totalSupply = market?.supply ?? null;const totalRevenue = platform.total_revenue_gross / 1_000_000;const poolPct = REVENUE_SHARE_POOL_PCT;const revenuePool = totalRevenue * (poolPct / 100);return json(res, 200, {user_id: user.id,- token_price: tokenData.price,+ token_price: market?.price_usd ?? null,total_supply: totalSupply,- total_holders: ov.holder ?? null,+ total_holders: market?.holders ?? null,platform_revenue_usd: totalRevenue,revenue_share_pool_pct: poolPct,revenue_share_pool_usd: revenuePool,diff --git a/tests/token-layer.test.js b/tests/token-layer.test.jsindex 5e3e76d06..15154d834 100644--- a/tests/token-layer.test.js+++ b/tests/token-layer.test.js@@ -69,6 +69,7 @@ import {publicConfig,} from '../api/_lib/token/config.js';import { getTokenPriceUsd, quoteTokenForUsd, atomicsToTokens } from '../api/_lib/token/price.js';+import { __resetMarketCache } from '../api/_lib/market/token-market.js';import { issueQuote, verifyQuote } from '../api/_lib/token/quote.js';import { verifyOnChain } from '../api/_lib/token/payments.js';import { cacheGet, cacheSet } from '../api/_lib/cache.js';@@ -80,6 +81,7 @@ beforeEach(() => {cacheGet.mockResolvedValue(null);cacheSet.mockResolvedValue();sql.mockResolvedValue([]);+ __resetMarketCache();});afterEach(() => {@@ -234,10 +236,10 @@ describe('getTokenPriceUsd', () => {it('falls back to Birdeye when Jupiter returns null price', async () => {const priorKey = process.env.BIRDEYE_API_KEY;process.env.BIRDEYE_API_KEY = 'test-key';- // Jupiter returns with missing field+ // Jupiter returns with missing field → nullfetchResponses.push({ body: { [TOKEN_MINT]: {} } });- // Birdeye- fetchResponses.push({ body: { data: { value: 0.0004 } } });+ // Market module's first source is Birdeye token_overview ({ data: { price } }).+ fetchResponses.push({ body: { data: { price: 0.0004 } } });const p = await getTokenPriceUsd({ fresh: true });expect(p.priceUsd).toBe(0.0004);expect(p.source).toBe('birdeye');@@ -261,8 +263,12 @@ describe('getTokenPriceUsd', () => {it('throws price_unavailable when all feeds fail', async () => {const priorKey = process.env.BIRDEYE_API_KEY;process.env.BIRDEYE_API_KEY = 'test-key';- fetchResponses.push({ ok: false, status: 503, body: 'down' });- fetchResponses.push({ ok: false, status: 503, body: 'down' });+ // Jupiter, then the market module's three sources (Birdeye, DexScreener,+ // GeckoTerminal) all 503 → no price → price_unavailable.+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // jupiter+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // birdeye+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // dexscreener+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // geckoterminalawait expect(getTokenPriceUsd({ fresh: true })).rejects.toMatchObject({code: 'price_unavailable',});