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.

fix(crypto): add last-known-good cache to the bonding-curve endpoint so pump.fun blips serve stale data instead of a hard 503

nirholas1e1607397c64
diff --git a/api/_lib/pump-bonding.js b/api/_lib/pump-bonding.js
index 2b5eba30e..a783612b8 100644
--- a/api/_lib/pump-bonding.js
+++ b/api/_lib/pump-bonding.js
@@ -17,12 +17,22 @@
// no chain required.
import { isGraduated } from './pump-launch-feed.js';
+import { pumpFetchJson } from './pump-feed-fetch.js';
+import { cacheGet, cacheSet } from './cache.js';
export const PUMP_FRONTEND_BASE =
process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';
const FETCH_TIMEOUT_MS = 6_000;
-const UA = 'three.ws-crypto-api/1';
+
+// Live cache: collapses repeat polls of the same mint (a trading agent watching
+// a curve typically re-checks every few seconds) into one upstream fetch.
+const LIVE_TTL_S = Number(process.env.PUMP_BONDING_LIVE_TTL_S || 25);
+// Last-known-good: survives a Cloudflare challenge/rate-limit window so a mint
+// with a prior successful fetch never hard-fails, only goes stale.
+const LKG_TTL_S = Number(process.env.PUMP_BONDING_LKG_TTL_S || 1800);
+const liveKey = (mint) => `pump:bonding:live:${mint}`;
+const bondingLkgKey = (mint) => `pump:bonding:lkg:${mint}`;
// pump.fun mints a fixed 1B supply (6 decimals). Of that, 793.1M tokens sit in
// the bonding curve at launch; the coin graduates once the curve's float has been
@@ -136,29 +146,21 @@ export function mapBondingStatus(coin, { solPriceUsd = 0 } = {}) {
};
}
+// Bounded retry on 429/5xx (honours Retry-After), never throws: the same
+// resilience the sibling pump.fun readers (trending, whales, /api/pump/coin)
+// already rely on, so a Cloudflare rate-limit blip recovers inside one request
+// instead of being treated as a hard outage on the first non-OK response.
async function fetchOnce(url) {
- const ctrl = new AbortController();
- const tid = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
- try {
- const r = await fetch(url, {
- signal: ctrl.signal,
- headers: { accept: 'application/json', 'user-agent': UA },
- });
- // 404 = this mint isn't a pump.fun-indexed coin; a hard distinction from a
- // transient upstream fault (5xx / network / timeout) so the caller can answer
- // 400 vs 503 correctly.
- if (r.status === 404) return { kind: 'not_found' };
- if (!r.ok) return { kind: 'upstream_down' };
- const j = await r.json().catch(() => null);
- // A returned record that isn't a native bonding-curve launch (an externally
- // indexed token) is "not a pump.fun mint", not a data-source fault.
- if (j && j.mint && isPumpLaunch(j)) return { kind: 'ok', coin: j };
- return { kind: 'not_found' };
- } catch {
- return { kind: 'upstream_down' };
- } finally {
- clearTimeout(tid);
- }
+ const { ok, status, body } = await pumpFetchJson(url, { timeoutMs: FETCH_TIMEOUT_MS, retries: 1 });
+ // 404 = this mint isn't a pump.fun-indexed coin; a hard distinction from a
+ // transient upstream fault (5xx / network / timeout) so the caller can answer
+ // 400 vs 503 correctly.
+ if (status === 404) return { kind: 'not_found' };
+ if (!ok) return { kind: 'upstream_down' };
+ // A returned record that isn't a native bonding-curve launch (an externally
+ // indexed token) is "not a pump.fun mint", not a data-source fault.
+ if (body && body.mint && isPumpLaunch(body)) return { kind: 'ok', coin: body };
+ return { kind: 'not_found' };
}
/**
@@ -183,15 +185,36 @@ export async function fetchPumpCoin(mint) {
}
/**
- * Resolve the full bonding-curve status for a mint: fetch + map.
+ * Resolve the full bonding-curve status for a mint: live cache, then fetch +
+ * map, then a last-known-good fallback on upstream failure. Mirrors
+ * `readThroughFeed` in pump-feed-fetch.js: a live hit answers first; a miss
+ * fetches and writes through both tiers; a failed fetch serves the
+ * last-known-good copy (flagged `stale`) rather than hard-failing, and only
+ * reports `upstream_down` when no cached data exists at all for this mint.
*
* @param {string} mint
- * @returns {Promise<{ kind: 'ok', status: object, coin: object } | { kind: 'not_found' } | { kind: 'upstream_down' }>}
+ * @returns {Promise<{ kind: 'ok', status: object, coin: object, stale: boolean } | { kind: 'not_found' } | { kind: 'upstream_down' }>}
*/
export async function getBondingStatus(mint) {
+ const lk = liveKey(mint);
+ const live = await cacheGet(lk);
+ if (live) return { kind: 'ok', status: live.status, coin: live.coin, stale: false };
+
const res = await fetchPumpCoin(mint);
- if (res.kind !== 'ok') return res;
- // pump.fun's coin object already carries `usd_market_cap`, so no extra SOL-price
- // fetch is needed on the hot path; pass 0 and let mapBondingStatus prefer it.
- return { kind: 'ok', status: mapBondingStatus(res.coin, { solPriceUsd: 0 }), coin: res.coin };
+ if (res.kind === 'ok') {
+ // pump.fun's coin object already carries `usd_market_cap`, so no extra
+ // SOL-price fetch is needed on the hot path; pass 0 and let
+ // mapBondingStatus prefer it.
+ const status = mapBondingStatus(res.coin, { solPriceUsd: 0 });
+ const entry = { status, coin: res.coin };
+ cacheSet(lk, entry, LIVE_TTL_S).catch(() => {});
+ cacheSet(bondingLkgKey(mint), entry, LKG_TTL_S).catch(() => {});
+ return { kind: 'ok', status, coin: res.coin, stale: false };
+ }
+ // Not a pump.fun mint is a real, stable answer; never masked by a stale cache.
+ if (res.kind === 'not_found') return res;
+
+ const lkg = await cacheGet(bondingLkgKey(mint));
+ if (lkg) return { kind: 'ok', status: lkg.status, coin: lkg.coin, stale: true };
+ return { kind: 'upstream_down' };
}
diff --git a/api/crypto/bonding.js b/api/crypto/bonding.js
index ae3aa3fe1..01262fffc 100644
--- a/api/crypto/bonding.js
+++ b/api/crypto/bonding.js
@@ -97,8 +97,14 @@ export default wrap(async (req, res) => {
ts,
source: s.source,
},
- // Bonding-curve state moves fast; short CDN cache + SWR keeps a polling agent
- // responsive without hammering the pump.fun feed.
- { 'cache-control': 'public, s-maxage=15, stale-while-revalidate=30' },
+ result.stale
+ // Last-known-good: pump.fun's live feed failed but a prior fetch for
+ // this mint exists. Flag it and keep the CDN window short so a real
+ // recovery is picked back up quickly, matching /api/pump/coin's
+ // serveStaleCoin convention.
+ ? { 'cache-control': 'public, max-age=10', 'x-pump-stale': '1' }
+ // Bonding-curve state moves fast; short CDN cache + SWR keeps a polling
+ // agent responsive without hammering the pump.fun feed.
+ : { 'cache-control': 'public, s-maxage=15, stale-while-revalidate=30' },
);
});
diff --git a/data/changelog.json b/data/changelog.json
index 2b0949e32..bde623326 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$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-23",
+ "title": "Bonding-curve status API no longer hard-fails when pump.fun blips",
+ "summary": "GET /api/crypto/bonding was returning a 503 to every caller during a pump.fun outage, even for mints it had already fetched successfully. It now caches each mint's bonding-curve status and keeps a longer last-known-good copy, so a failed upstream fetch serves that cached data (flagged with an x-pump-stale header) instead of a hard error. A 503 with a retry hint is now only returned for a mint that has no cached data at all.",
+ "tags": ["fix"],
+ "link": "/api/crypto/bonding"
+ },
{
"date": "2026-10-23",
"title": "Give your agent a spending cap and confirm anything bigger from your own wallet",
diff --git a/tests/crypto-bonding-endpoint.test.js b/tests/crypto-bonding-endpoint.test.js
index 644ff9fef..dc3790235 100644
--- a/tests/crypto-bonding-endpoint.test.js
+++ b/tests/crypto-bonding-endpoint.test.js
@@ -14,8 +14,8 @@ vi.mock('../api/_lib/http.js', () => ({
res._json = { status, body: { error: code, error_description: message, ...extra } };
return res;
},
- json: (res, status, body) => {
- res._json = { status, body };
+ json: (res, status, body, headers = {}) => {
+ res._json = { status, body, headers };
return res;
},
}));
@@ -132,6 +132,27 @@ describe('GET /api/crypto/bonding', () => {
});
});
+ it('200s a stale last-known-good result with x-pump-stale set instead of 503', async () => {
+ getBondingStatus.mockResolvedValue({
+ kind: 'ok',
+ stale: true,
+ status: {
+ onCurve: true,
+ graduated: false,
+ migratedTo: null,
+ bondingProgressPct: 62.5,
+ solInCurve: 40,
+ tokensRemaining: 297_412_500,
+ marketCapUsd: 48000,
+ source: 'pumpfun',
+ },
+ });
+ const res = await call(`/api/crypto/bonding?mint=${THREE_MINT}`);
+ expect(res._json.status).toBe(200);
+ expect(res._json.headers['x-pump-stale']).toBe('1');
+ expect(res._json.body.onCurve).toBe(true);
+ });
+
it('429s when the per-IP limiter denies', async () => {
const { limits } = await import('../api/_lib/rate-limit.js');
limits.marketDataIp.mockResolvedValueOnce({ success: false });
diff --git a/tests/pump-bonding.test.js b/tests/pump-bonding.test.js
index c3fb6e241..96204f8da 100644
--- a/tests/pump-bonding.test.js
+++ b/tests/pump-bonding.test.js
@@ -1,9 +1,22 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// api/_lib/pump-bonding.js now reads/writes through api/_lib/cache.js (live +
+// last-known-good tiers). Fake it with a plain Map so getBondingStatus's cache
+// behavior is tested without Redis: same pattern as
+// tests/api/pump-feed-fetch.test.js, which proved this approach for the
+// sibling pump.fun readers.
+const cache = new Map();
+vi.mock('../api/_lib/cache.js', () => ({
+ cacheGet: async (k) => (cache.has(k) ? cache.get(k) : null),
+ cacheSet: async (k, v) => { cache.set(k, v); },
+}));
+
import {
bondingProgressPct,
mapBondingStatus,
isPumpLaunch,
PUMP_CURVE_INITIAL_REAL_TOKENS,
+ getBondingStatus,
} from '../api/_lib/pump-bonding.js';
// Synthetic pump.fun coin objects. No real third-party mint — $THREE's CA is the
@@ -141,4 +154,87 @@ describe('mapBondingStatus — graduated branch', () => {
expect(s.onCurve).toBe(false);
expect(s.migratedTo).toBe('pumpswap');
});
+
+});
+// getBondingStatus: live cache / last-known-good fallback. Bug: before this,
+// a failed upstream fetch always returned `{kind:'upstream_down'}`, even when
+// a prior successful fetch for the same mint existed -- the live production
+// outage this suite reproduces.
+function jsonRes(body, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ headers: { get: () => null },
+ json: async () => body,
+ };
+}
+
+const bondingCoin = {
+ mint: THREE_MINT,
+ complete: false,
+ real_token_reserves: String(PUMP_CURVE_INITIAL_REAL_TOKENS / 2),
+ real_sol_reserves: String(21 * 1e9),
+ usd_market_cap: 30000,
+};
+
+beforeEach(() => {
+ cache.clear();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('getBondingStatus -- cache + last-known-good fallback', () => {
+ it('reproduces the outage: upstream down, no last-known-good, reports upstream_down', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network unreachable')));
+ const out = await getBondingStatus(THREE_MINT);
+ expect(out).toEqual({ kind: 'upstream_down' });
+ });
+
+ it('the bug: upstream down but a last-known-good copy exists, serves it stale instead of failing', async () => {
+ const status = mapBondingStatus(bondingCoin);
+ cache.set(`pump:bonding:lkg:${THREE_MINT}`, { status, coin: bondingCoin });
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network unreachable')));
+
+ const out = await getBondingStatus(THREE_MINT);
+ expect(out.kind).toBe('ok');
+ expect(out.stale).toBe(true);
+ expect(out.status).toEqual(status);
+ expect(out.coin).toEqual(bondingCoin);
+ });
+
+ it('a successful fetch writes through to both the live and last-known-good caches', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonRes(bondingCoin));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const out = await getBondingStatus(THREE_MINT);
+ expect(out.kind).toBe('ok');
+ expect(out.stale).toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(1); // coins-v2 hit, coins never tried
+
+ const live = cache.get(`pump:bonding:live:${THREE_MINT}`);
+ const lkg = cache.get(`pump:bonding:lkg:${THREE_MINT}`);
+ expect(live.coin).toEqual(bondingCoin);
+ expect(lkg.coin).toEqual(bondingCoin);
+ });
+
+ it('serves a second request for the same mint from the live cache without a second fetch', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonRes(bondingCoin));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await getBondingStatus(THREE_MINT);
+ const out = await getBondingStatus(THREE_MINT);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(out.kind).toBe('ok');
+ expect(out.stale).toBe(false);
+ });
+
+ it('not_found is never masked by a stale cache', async () => {
+ cache.set(`pump:bonding:lkg:${THREE_MINT}`, { status: mapBondingStatus(bondingCoin), coin: bondingCoin });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonRes(null, 404)));
+
+ const out = await getBondingStatus(THREE_MINT);
+ expect(out).toEqual({ kind: 'not_found' });
+ });
});