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(pump): degrade /api/pump/coin to on-chain data plus first-party metadata instead of a bare 502 when pump.fun is Cloudflare-blocked

nirholas1b636242e1a2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a3cc6f030..b116878a1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Engine bridges are packaged for the Unity, Godot and Unreal stores**: One command, npm run package:engine-stores, validates the Unity, Godot and Unreal bridges and builds a reproducible upload package for each, with listing metadata and a submission checklist. The Unity package and Unreal plugin manifests now carry their documentation links. (`/docs/engine-store-publishing`) `[sdk, docs]`
- **Fixed three more legacy thumbnail links that browsers refused to load**: A handful of forge creations and 3D props stored from before an earlier URL fix still pointed straight at the storage bucket's own domain instead of three.ws's own CDN link, which Chrome blocks as an opaque cross-origin response. Model-page posters, a creation's related-models sidebar, forge share-card previews (the image X and Discord show when a link is pasted), and the Forged gallery's model-viewer thumbnails now all resolve through the same CDN link as everything else. (`/forge`) `[fix]`
- **GET /api/crypto/bonding falls back to an on-chain read when pump.fun is Cloudflare-blocked**: pump.fun's frontend API started answering every request from our servers with a Cloudflare challenge, which hard-failed /api/crypto/bonding for every mint, including $THREE's own, once the 30-minute last-known-good cache expired. The endpoint now reads the bonding-curve account straight off Solana RPC (the same reader already live behind /api/pump/curve) before giving up, so bonding/graduation status stays answerable even while pump.fun's edge blocks us. (`/docs/api-reference`) `[fix]`
+- **GET /api/pump/coin degrades to on-chain data plus first-party metadata instead of a bare 502**: pump.fun's frontend API has stayed Cloudflare-blocked long enough to exhaust /api/pump/coin's 24-hour last-known-good cache for some mints, including $THREE's own, leaving a hard 502 with no partial data. The endpoint now adds a third tier: numeric and curve fields come from the same on-chain bonding-curve reader already live behind /api/pump/curve, and identity fields (name, symbol, creator) come from pump_agent_mints for any mint three.ws itself tracks. Responses on this tier carry an x-pump-degraded: onchain header; a true triple-miss (no cache, no on-chain data, no registry row) still returns an honest 502 naming pump.fun. (`/docs/api-reference`) `[fix]`
- **Hundreds of dependency security advisories cleared across the repo**: Every committed lockfile was audited and patched: same-line security releases everywhere, vetted moves to patched majors (vitest 4, zod 4, helia 7, Svelte 5 and Vite 7 in the chat app, transformers 4 in HQ, gltf-transform 4 for the meshopt worker), and each package's tests and builds were rerun before and after. What remains are advisories with no patched release published anywhere (bigint-buffer, elliptic, node-forge) and pins that upstream SDKs still require. `[security, infra]`
- **Install the three.ws skills with one command on any agent runtime**: Run npx skills add nirholas/three-ws-skills (or the 3D-only and agent-economy repos) to install the three.ws skills into Claude Code, Codex, Cursor and any other runtime that reads the open Agent Skills format. Every skill now passes the Agent Skills spec validator, which fixed 21 skills whose frontmatter some installers could not parse, and an install test proves each repo lists and installs every skill in a clean directory. Publishing the repos is still the owner's step. (`/docs/agent-skills`) `[feature, docs]`
- **Long MCP answers arrive as a summary, and agents can search the docs**: list_my_agents, recall and crypto_data now answer with a short summary, a count, a handle and the first page when the list is long, and the new expand tool reads the rest on request. A 100-coin market list drops from about 47,800 to 4,400 tokens. Handles are signed, account-bound and last 15 minutes. The new free search_docs tool answers how-to questions from the docs index on the main and studio servers. (`/docs/mcp`) `[feature, docs]`
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 27add2073..b7dc8e4d4 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -101,6 +101,7 @@ import { grindVanityNode, GrindExhaustedError } from '../../src/solana/vanity/gr
import { logger } from '../_lib/usage.js';
import { cacheGet, cacheSet } from '../_lib/cache.js';
import { pumpFetchJson } from '../_lib/pump-feed-fetch.js';
+import { getCurveView } from '../_lib/pump-curve-view.js';
import { collectFeeAgentSchema } from '../_lib/pump-fee-schemas.js';
import { isRpcOutageError, staleEnvelope } from '../_lib/rpc-degrade.js';
import { getLaunchEconomics, describeFeeSplit } from '../_lib/launch-economics.js';
@@ -4167,6 +4168,59 @@ const COIN_TTL_MS = 30_000;
const COIN_LKG_TTL_S = 24 * 3600;
const coinLkgKey = (mint) => `pump:coin:lkg:${mint}`;
+// Third degrade tier for handleCoin, reached once both the in-memory cache and
+// the 24h last-known-good copy are empty: pump.fun's own metadata is gone, but
+// two real, first-party sources can still answer. Numeric/curve fields come
+// from the on-chain bonding-curve reader already proven live behind
+// /api/pump/curve (order 423); identity fields (name, symbol, creator) come
+// from pump_agent_mints, the platform's own launch registry, for any mint
+// three.ws itself launched. Neither source carries a stored image URL for a
+// curve launch, so `image`/`image_uri` stay null rather than guessing.
+// Returns null when neither source has anything, so the caller falls through
+// to the honest 502.
+async function fetchOnchainCoinDegrade(mint) {
+ let curveBody = null;
+ try {
+ const view = await getCurveView({ mint, network: 'mainnet' });
+ if (view?.httpStatus === 200 && view.body) curveBody = view.body;
+ } catch (err) {
+ console.warn('[pump/coin] on-chain curve fallback failed: %s', String(err?.message || err).slice(0, 160));
+ }
+
+ let dbRow = null;
+ try {
+ const rows = await sql`
+ select name, symbol, agent_authority from pump_agent_mints
+ where mint = ${mint} and network = 'mainnet'
+ limit 1
+ `;
+ dbRow = rows[0] || null;
+ } catch (err) {
+ console.warn('[pump/coin] pump_agent_mints lookup failed: %s', String(err?.message || err).slice(0, 160));
+ }
+
+ if (!curveBody && !dbRow) return null;
+
+ const curve = curveBody?.curve || null;
+ return {
+ mint,
+ name: dbRow?.name ?? null,
+ symbol: dbRow?.symbol ?? null,
+ image: null,
+ image_uri: null,
+ description: null,
+ creator: curve?.creator ?? dbRow?.agent_authority ?? null,
+ complete: curve ? Boolean(curve.complete) : curveBody?.graduated === true ? true : null,
+ usd_market_cap: curveBody?.graduatedPrice?.marketCapUsd ?? null,
+ virtual_token_reserves: curve?.virtualTokenReserves ?? null,
+ virtual_sol_reserves: curve?.virtualSolReserves ?? null,
+ real_token_reserves: curve?.realTokenReserves ?? null,
+ real_sol_reserves: curve?.realSolReserves ?? null,
+ total_supply: curve?.tokenTotalSupply ?? null,
+ metadataSource: dbRow ? 'platform' : 'onchain',
+ };
+}
+
async function serveStaleCoin(res, mint, status, code, message) {
const hit = COIN_CACHE.get(mint) || (await cacheGet(coinLkgKey(mint)));
if (hit && hit.body && typeof hit.at === 'number') {
@@ -4174,11 +4228,17 @@ async function serveStaleCoin(res, mint, status, code, message) {
res.setHeader('x-pump-stale', '1');
return json(res, 200, staleEnvelope(hit.body, hit.at));
}
+ const degraded = await fetchOnchainCoinDegrade(mint);
+ if (degraded) {
+ res.setHeader('cache-control', 'public, max-age=10');
+ res.setHeader('x-pump-degraded', 'onchain');
+ return json(res, 200, { ...degraded, stale: true, as_of: new Date().toISOString() });
+ }
res.setHeader('Retry-After', '15');
return error(res, status, code, message, { retry_after: 15 });
}
-async function handleCoin(req, res) {
+export async function handleCoin(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
const rl = await limits.mcpIp(clientIp(req));
diff --git a/data/changelog.json b/data/changelog.json
index 43482c9af..73b736759 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-24",
+ "title": "GET /api/pump/coin degrades to on-chain data plus first-party metadata instead of a bare 502",
+ "summary": "pump.fun's frontend API has stayed Cloudflare-blocked long enough to exhaust /api/pump/coin's 24-hour last-known-good cache for some mints, including $THREE's own, leaving a hard 502 with no partial data. The endpoint now adds a third tier: numeric and curve fields come from the same on-chain bonding-curve reader already live behind /api/pump/curve, and identity fields (name, symbol, creator) come from pump_agent_mints for any mint three.ws itself tracks. Responses on this tier carry an x-pump-degraded: onchain header; a true triple-miss (no cache, no on-chain data, no registry row) still returns an honest 502 naming pump.fun.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/docs/api-reference"
+ },
{
"date": "2026-10-24",
"title": "GET /api/crypto/bonding falls back to an on-chain read when pump.fun is Cloudflare-blocked",
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 3e6361397..0bf9c7625 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,11 +1,11 @@
{
- "generated_at": "2026-10-24T23:24:05.471Z",
+ "generated_at": "2026-10-24T23:45:10.921Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 4191,
+ "total": 4192,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
@@ -163,6 +163,16 @@
"fix"
]
},
+ {
+ "date": "2026-10-24",
+ "type": "update",
+ "title": "GET /api/pump/coin degrades to on-chain data plus first-party metadata instead of a bare 502",
+ "summary": "pump.fun's frontend API has stayed Cloudflare-blocked long enough to exhaust /api/pump/coin's 24-hour last-known-good cache for some mints, including $THREE's own, leaving a hard 502 with no partial data. The endpoint now adds a third tier: numeric and curve fields come from the same on-chain bonding-curve reader already live behind /api/pump/curve, and identity fields (name, symbol, creator) come from pump_agent_mints for any mint three.ws itself tracks. Responses on this tier carry an x-pump-degraded: onchain header; a true triple-miss (no cache, no on-chain data, no registry row) still returns an honest 502 naming pump.fun.",
+ "link": "/docs/api-reference",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-10-24",
"type": "update",
@@ -1553,16 +1563,6 @@
"feature",
"improvement"
]
- },
- {
- "date": "2026-10-12",
- "type": "update",
- "title": "Dissolve: turn any 3D model into a GPU particle storm",
- "summary": "A new page that dissolves any GLB into up to a million GPU particles, morphs one shape into another, and lets you bend the storm with a black hole, a vortex, shockwaves and a collapse. Turn on the microphone and bass drives the storm. Pick a look, record a clip, save a PNG or share the exact pair as a link.",
- "link": "/dissolve",
- "tags": [
- "feature"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 7d2626934..490b67ce3 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-10-24T23:24:05.446Z",
+ "generated_at": "2026-10-24T23:45:10.896Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -160,6 +160,16 @@
"fix"
]
},
+ {
+ "date": "2026-10-24",
+ "type": "update",
+ "title": "GET /api/pump/coin degrades to on-chain data plus first-party metadata instead of a bare 502",
+ "summary": "pump.fun's frontend API has stayed Cloudflare-blocked long enough to exhaust /api/pump/coin's 24-hour last-known-good cache for some mints, including $THREE's own, leaving a hard 502 with no partial data. The endpoint now adds a third tier: numeric and curve fields come from the same on-chain bonding-curve reader already live behind /api/pump/curve, and identity fields (name, symbol, creator) come from pump_agent_mints for any mint three.ws itself tracks. Responses on this tier carry an x-pump-degraded: onchain header; a true triple-miss (no cache, no on-chain data, no registry row) still returns an honest 502 naming pump.fun.",
+ "link": "/docs/api-reference",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-10-24",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 917885270..cddce0d9d 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -126,6 +126,14 @@
<category>fix</category>
<description>pump.fun's frontend API started answering every request from our servers with a Cloudflare challenge, which hard-failed /api/crypto/bonding for every mint, including $THREE's own, once the 30-minute last-known-good cache expired. The endpoint now reads the bonding-curve account straight off Solana RPC (the same reader already live behind /api/pump/curve) before giving up, so bonding/graduation status stays answerable even while pump.fun's edge blocks us.</description>
</item>
+ <item>
+ <title>GET /api/pump/coin degrades to on-chain data plus first-party metadata instead of a bare 502</title>
+ <link>https://three.ws/docs/api-reference</link>
+ <guid isPermaLink="false">2026-10-24:GET /api/pump/coin degrades to on-chain data plus first-party metadata instead of a bare 502</guid>
+ <pubDate>Sat, 24 Oct 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>pump.fun's frontend API has stayed Cloudflare-blocked long enough to exhaust /api/pump/coin's 24-hour last-known-good cache for some mints, including $THREE's own, leaving a hard 502 with no partial data. The endpoint now adds a third tier: numeric and curve fields come from the same on-chain bonding-curve reader already live behind /api/pump/curve, and identity fields (name, symbol, creator) come from pump_agent_mints for any mint three.ws itself tracks. Responses on this tier carry an x-pump-degraded: onchain header; a true triple-miss (no cache, no on-chain data, no registry row) still returns an honest 502 naming pump.fun.</description>
+ </item>
<item>
<title>Hundreds of dependency security advisories cleared across the repo</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 9b6a51979..1c7fdadd0 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-10-24T23:24:05.430Z",
+ "generated_at": "2026-10-24T23:45:10.879Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/pump-coin-endpoint.test.js b/tests/pump-coin-endpoint.test.js
new file mode 100644
index 000000000..343c6923b
--- /dev/null
+++ b/tests/pump-coin-endpoint.test.js
@@ -0,0 +1,281 @@
+// handleCoin (api/pump/[action].js) -- the GET /api/pump/coin degrade chain.
+//
+// Reproduces a real production outage (measured 2026-10-24): pump.fun's
+// frontend-api-v3 answers every request from our environment with a
+// Cloudflare 403, and the 24h last-known-good cache for $THREE's own mint has
+// already been exhausted. Before this fix, that triple-miss (no in-memory
+// cache, no LKG, upstream down) was a bare 502 with no partial data, even
+// though two real, first-party sources (the on-chain bonding curve, and the
+// platform's own pump_agent_mints launch registry) could still answer.
+//
+// Mocking pattern mirrors tests/pump-bonding.test.js (Map-backed cache.js,
+// mocked getCurveView) plus tests/pump-live-stream.test.js (the minimal mock
+// set required to import api/pump/[action].js, a large dispatcher file with
+// many heavy module-level imports that are irrelevant to this handler).
+//
+// handleCoin keeps its own in-process `COIN_CACHE` Map (module-scoped, never
+// reset by this file's cache.js mock). Each test below that does not care
+// about priming it uses its own synthetic mint so a prior test's cache entry
+// can never leak into it; the one test that deliberately exercises the
+// in-memory-stale-but-present path uses fake timers to age its own entry past
+// the 30s freshness window within a single test, then restores real timers.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+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); },
+}));
+
+const sql = vi.fn(async () => []);
+vi.mock('../api/_lib/db.js', () => ({
+ sql,
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: () => false,
+}));
+
+// The on-chain fallback (getCurveView) is the proven reader already live
+// behind /api/pump/curve (order 423); mocked here so this stays a unit test of
+// handleCoin's branching, not an RPC integration test.
+vi.mock('../api/_lib/pump-curve-view.js', () => ({
+ getCurveView: vi.fn(),
+}));
+
+const pumpFetchJson = vi.fn();
+vi.mock('../api/_lib/pump-feed-fetch.js', () => ({ pumpFetchJson }));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { mcpIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://test', ISSUER: 'http://test', MCP_RESOURCE: 'http://test' },
+}));
+
+// Heavy Solana SDK / unrelated subsystem imports not needed for this handler.
+vi.mock('../api/_lib/pump.js', () => ({}));
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => null),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+vi.mock('../api/_lib/solana-wallet.js', () => ({}));
+vi.mock('../api/_lib/agent-pumpfun.js', () => ({ solanaConnection: vi.fn() }));
+vi.mock('../api/_lib/skill-runtime.js', () => ({ makeRuntime: vi.fn() }));
+vi.mock('../api/_lib/agent-spend-policy.js', () => ({}));
+vi.mock('../api/payments/_config.js', () => ({
+ SOLANA_USDC_MINT: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ SOLANA_USDC_MINT_DEVNET: 'Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr',
+ toUsdcAtomics: vi.fn((v) => BigInt(Math.round(v * 1e6))),
+}));
+
+const { handleCoin } = await import('../api/pump/[action].js');
+const { getCurveView } = await import('../api/_lib/pump-curve-view.js');
+
+// $THREE's own mint: the platform's own coin, not a third-party placeholder.
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// Clearly-synthetic per-test mints (CLAUDE.md's sanctioned placeholder style):
+// handleCoin keyes its in-process cache by mint, so giving each independent
+// test its own key means no test can ever observe another test's cache entry.
+function synthMint(tag) {
+ return (`THREEtest${tag}` + '9'.repeat(44)).slice(0, 44);
+}
+
+function mockReq(mint) {
+ return {
+ method: 'GET',
+ headers: { host: 'localhost' },
+ url: `/api/pump/coin?mint=${encodeURIComponent(mint)}`,
+ };
+}
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ _headers: {},
+ _body: '',
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end(b) { this._body = b || ''; },
+ get headersSent() { return false; },
+ get writableEnded() { return false; },
+ get json() { try { return JSON.parse(this._body); } catch { return null; } },
+ };
+}
+
+function pumpfunCoinBody(mint, overrides = {}) {
+ return {
+ mint,
+ name: 'three.ws',
+ symbol: 'THREE',
+ image_uri: 'https://ipfs.io/ipfs/bafy-three',
+ usd_market_cap: 296832.56,
+ complete: true,
+ total_supply: 1_000_000_000_000_000,
+ ...overrides,
+ };
+}
+
+function onchainCurveBody(mint) {
+ return {
+ httpStatus: 200,
+ body: {
+ mint,
+ network: 'mainnet',
+ curve: {
+ virtualTokenReserves: '0',
+ virtualSolReserves: '0',
+ realTokenReserves: '0',
+ realSolReserves: '0',
+ tokenTotalSupply: '1000000000000000',
+ complete: true,
+ creator: '9wgvwps9qK5jNniC5RJdrYCfaV3CLKTnxYVqBjXwegEV',
+ },
+ graduated: true,
+ graduation: { isGraduated: true, progressBps: 10_000 },
+ graduatedPrice: { priceUsd: 0.00029683255767706676, source: 'jupiter', marketCapUsd: 296832.55767706677 },
+ },
+ };
+}
+
+beforeEach(() => {
+ cache.clear();
+ sql.mockReset().mockResolvedValue([]);
+ pumpFetchJson.mockReset();
+ getCurveView.mockReset().mockResolvedValue({
+ httpStatus: 404,
+ body: { error: 'no_curve', error_description: 'no bonding curve found for that mint' },
+ });
+});
+
+describe('handleCoin -- live fetch (regression guard)', () => {
+ it('live fetch succeeds: 200 with the unmodified pump.fun body', async () => {
+ pumpFetchJson.mockResolvedValue({ ok: true, status: 200, body: pumpfunCoinBody(THREE_MINT) });
+ const req = mockReq(THREE_MINT);
+ const res = mockRes();
+
+ await handleCoin(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.json.symbol).toBe('THREE');
+ expect(res.json.usd_market_cap).toBe(296832.56);
+ expect(res._headers['x-pump-stale']).toBeUndefined();
+ expect(res._headers['x-pump-degraded']).toBeUndefined();
+ });
+});
+
+describe('handleCoin -- in-memory cache fallback (regression guard)', () => {
+ it('live fetch fails, an aged in-memory entry exists: stale 200 with x-pump-stale', async () => {
+ const mint = synthMint('A');
+ vi.useFakeTimers();
+ try {
+ // Prime the cache the way a prior successful handleCoin call would.
+ pumpFetchJson.mockResolvedValueOnce({ ok: true, status: 200, body: pumpfunCoinBody(mint) });
+ await handleCoin(mockReq(mint), mockRes());
+
+ // Age the entry past COIN_TTL_MS (30s) so the next call's freshness
+ // check misses and a live fetch is actually attempted (and fails).
+ vi.advanceTimersByTime(31_000);
+
+ pumpFetchJson.mockResolvedValueOnce({ ok: false, status: 403 });
+ const req = mockReq(mint);
+ const res = mockRes();
+ await handleCoin(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res._headers['x-pump-stale']).toBe('1');
+ expect(res._headers['x-pump-degraded']).toBeUndefined();
+ expect(res.json.symbol).toBe('THREE');
+ expect(res.json.stale).toBe(true);
+ expect(getCurveView).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('handleCoin -- on-chain degrade (the new tier)', () => {
+ it('upstream down, no in-memory cache, no LKG, curve read works, no DB row: 200 with numeric fields and an explicit unavailable identity', async () => {
+ const mint = synthMint('B');
+ pumpFetchJson.mockResolvedValue({ ok: false, status: 403 });
+ getCurveView.mockResolvedValue(onchainCurveBody(mint));
+ sql.mockResolvedValue([]); // no pump_agent_mints row
+
+ const req = mockReq(mint);
+ const res = mockRes();
+ await handleCoin(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res._headers['x-pump-degraded']).toBe('onchain');
+ expect(res._headers['x-pump-stale']).toBeUndefined();
+ expect(res.json.mint).toBe(mint);
+ expect(res.json.usd_market_cap).toBeCloseTo(296832.55767706677, 3);
+ expect(res.json.complete).toBe(true);
+ expect(res.json.name).toBeNull();
+ expect(res.json.symbol).toBeNull();
+ expect(res.json.image).toBeNull();
+ expect(res.json.metadataSource).toBe('onchain');
+ expect(res.json.stale).toBe(true);
+ });
+
+ it('same triple-miss but a pump_agent_mints row exists: 200 with identity fields from the platform registry', async () => {
+ const mint = synthMint('C');
+ pumpFetchJson.mockResolvedValue({ ok: false, status: 403 });
+ getCurveView.mockResolvedValue(onchainCurveBody(mint));
+ sql.mockResolvedValue([
+ { name: 'three.ws', symbol: 'THREE', agent_authority: '9wgvwps9qK5jNniC5RJdrYCfaV3CLKTnxYVqBjXwegEV' },
+ ]);
+
+ const req = mockReq(mint);
+ const res = mockRes();
+ await handleCoin(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res._headers['x-pump-degraded']).toBe('onchain');
+ expect(res.json.name).toBe('three.ws');
+ expect(res.json.symbol).toBe('THREE');
+ expect(res.json.creator).toBe('9wgvwps9qK5jNniC5RJdrYCfaV3CLKTnxYVqBjXwegEV');
+ expect(res.json.metadataSource).toBe('platform');
+ expect(res.json.usd_market_cap).toBeCloseTo(296832.55767706677, 3);
+ });
+});
+
+describe('handleCoin -- true triple-miss (regression guard on the honest-failure path)', () => {
+ it('upstream down, no caches, on-chain fallback also unavailable, no DB row: still a 502 naming pump.fun', async () => {
+ const mint = synthMint('D');
+ pumpFetchJson.mockResolvedValue({ ok: false, status: 403 });
+ getCurveView.mockResolvedValue({
+ httpStatus: 404,
+ body: { error: 'no_curve', error_description: 'no bonding curve found for that mint' },
+ });
+ sql.mockResolvedValue([]);
+
+ const req = mockReq(mint);
+ const res = mockRes();
+ await handleCoin(req, res);
+
+ expect(res.statusCode).toBe(502);
+ expect(res.json.error).toBe('upstream_failed');
+ expect(res.json.error_description).toContain('pump.fun');
+ expect(res._headers['x-pump-degraded']).toBeUndefined();
+ expect(res._headers['x-pump-stale']).toBeUndefined();
+ });
+
+ it('also 502s honestly when the on-chain reader itself throws', async () => {
+ const mint = synthMint('E');
+ pumpFetchJson.mockResolvedValue({ ok: false, status: 403 });
+ getCurveView.mockRejectedValue(new Error('all RPC lanes failed'));
+ sql.mockResolvedValue([]);
+
+ const req = mockReq(mint);
+ const res = mockRes();
+ await handleCoin(req, res);
+
+ expect(res.statusCode).toBe(502);
+ expect(res.json.error_description).toContain('pump.fun');
+ });
+});