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): share one rate-limit-aware pump.fun read layer so trending and whale scans stop reporting phantom outages

nirholasbb893fb64dfe
diff --git a/api/_lib/crypto-trending.js b/api/_lib/crypto-trending.js
index 950c04cb5..a65c91cee 100644
--- a/api/_lib/crypto-trending.js
+++ b/api/_lib/crypto-trending.js
@@ -34,11 +34,9 @@ import { scorePressure } from './x402/pump-trending-score.js';
import { summarizeWindowUsd, median } from './x402/pump-volume-anomaly.js';
import { dexScreenerTrending, gmgnSmartMoneyRank } from './gmgn-feed.js';
import { cacheWrap } from './cache.js';
+import { fetchPumpBoard as fetchPumpBoardRaw, fetchPumpTrades } from './pump-feed-fetch.js';
import { gmgnTokenUrl } from '../../src/shared/trading-terminals.js';
-const PUMP_FRONTEND_BASE = process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';
-const PUMP_SWAP_BASE = process.env.PUMP_SWAP_BASE || 'https://swap-api.pump.fun';
-const UA = 'three.ws-crypto-trending/1';
const FETCH_TIMEOUT_MS = Number(process.env.CRYPTO_TRENDING_TIMEOUT_MS || 6000);
// How many top board coins to pull trades for (trade fetch is the slow path).
const PUMP_TRADE_COINS = Number(process.env.CRYPTO_TRENDING_TRADE_COINS || 20);
@@ -165,23 +163,6 @@ export function toOutputRow(t) {
// ── live fetch layer ─────────────────────────────────────────────────────────
-async function fetchJson(url) {
- const ctrl = new AbortController();
- const tid = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
- try {
- const r = await fetch(url, {
- headers: { accept: 'application/json', 'user-agent': UA },
- signal: ctrl.signal,
- });
- if (!r.ok) return null;
- return await r.json();
- } catch {
- return null;
- } finally {
- clearTimeout(tid);
- }
-}
-
/** Bounded-concurrency map preserving order. */
async function mapLimit(items, limit, fn) {
const out = new Array(items.length);
@@ -197,29 +178,28 @@ async function mapLimit(items, limit, fn) {
return out;
}
+// Board + trades come from the shared pump.fun read layer, so the 5m, 1h and 24h
+// rankings reuse one set of trade pulls instead of each re-fetching 20 coins and
+// tripping the upstream rate limit (see api/_lib/pump-feed-fetch.js).
async function fetchPumpBoard(limit) {
- const url = new URL('/coins', PUMP_FRONTEND_BASE);
- url.searchParams.set('offset', '0');
- url.searchParams.set('limit', String(limit));
- url.searchParams.set('sort', 'market_cap');
- url.searchParams.set('order', 'DESC');
- url.searchParams.set('includeNsfw', 'false');
- const body = await fetchJson(url.toString());
- const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;
- if (!Array.isArray(coins)) return null;
- return coins
- .filter((c) => c && typeof c.mint === 'string' && c.mint.length >= 32)
- .map((c) => ({
- mint: c.mint,
- symbol: c.symbol || null,
- name: c.name || c.symbol || null,
- marketCapUsd: num(c.usd_market_cap),
- }));
+ const board = await fetchPumpBoardRaw({ limit, timeoutMs: FETCH_TIMEOUT_MS });
+ if (!board) return null;
+ return board.rows.map((c) => ({
+ mint: c.mint,
+ symbol: c.symbol || null,
+ name: c.name || c.symbol || null,
+ marketCapUsd: num(c.usd_market_cap),
+ }));
}
+// Trade rows keep their own timestamps and summarizeWindowUsd filters on them,
+// so a last-known-good pull can only shrink a window's volume, never invent it.
async function fetchCoinTrades(mint) {
- const body = await fetchJson(`${PUMP_SWAP_BASE}/v2/coins/${mint}/trades?limit=${PUMP_TRADES_PER_COIN}`);
- return Array.isArray(body) ? body : Array.isArray(body?.trades) ? body.trades : [];
+ const feed = await fetchPumpTrades(mint, {
+ limit: PUMP_TRADES_PER_COIN,
+ timeoutMs: FETCH_TIMEOUT_MS,
+ });
+ return feed?.rows || [];
}
/**
@@ -376,10 +356,11 @@ export async function composeTrending({ window, limit, source, nowMs = Date.now(
sources,
};
if (!sources.length) {
- out.note = 'All upstream market sources were unavailable. Returning an empty ranking; retry shortly.';
+ out.note =
+ 'No market source returned ranked tokens: the upstreams are unavailable, or nothing qualified in this window. Retry shortly or widen the window.';
} else if (source === 'all' && sources.length < jobs.length) {
const down = settled.filter((s) => s.rows.length === 0).map((s) => s.name);
- out.note = `Partial data: ${down.join(', ')} unavailable; ranked from ${sources.join(', ')}.`;
+ out.note = `Partial data: ${down.join(', ')} returned nothing; ranked from ${sources.join(', ')}.`;
}
return out;
}
diff --git a/api/_lib/pump-feed-fetch.js b/api/_lib/pump-feed-fetch.js
new file mode 100644
index 000000000..f2cdf877d
--- /dev/null
+++ b/api/_lib/pump-feed-fetch.js
@@ -0,0 +1,192 @@
+// Shared, rate-limit-aware read layer for the public pump.fun feeds.
+//
+// Why this module exists: one GET /api/crypto/trending call pulls the coin board
+// plus the trade feed for up to 20 coins, and one GET /api/crypto/whales market
+// scan pulls 8 more. pump.fun sits behind Cloudflare, which answers a burst that
+// size with HTTP 429 ("error code: 1015") for the next several seconds. Both
+// endpoints then reported "all upstream sources unavailable" while pump.fun was
+// perfectly healthy: three trending calls in a row (5m, 1h, 24h) reliably left
+// the last two empty.
+//
+// Two mechanics fix it, and both belong in one place so every pump.fun reader
+// inherits them:
+//
+// 1. A short shared cache on the raw board and per-coin trade pulls, keyed only
+// by mint + row limit. Trade rows carry their own timestamps and are window
+// agnostic, so the 5m, 1h and 24h rankings all reuse a single fetch, and a
+// second agent polling the same coin pays nothing. A failed fetch is never
+// cached (cacheWrap skips null), so an outage is retried on the next call
+// rather than pinned for the TTL.
+// 2. One bounded retry that honours Retry-After on 429/5xx, so a burst that
+// just clips the rate limit recovers inside the same request.
+//
+// A longer last-known-good copy sits behind the live TTL. When Cloudflare is
+// mid-ban there is nothing to retry into, so rather than answer "the feed is
+// down" while holding minutes-old real trades, we serve those and mark the
+// result stale. Trade rows carry their own timestamps, so a windowed sum built
+// from them stays arithmetically honest: an old row simply falls outside the
+// window and contributes nothing.
+//
+// Failure contract, relied on by callers to tell a real outage from a quiet
+// market: `null` means the call failed and no last-known-good exists, while
+// `{ rows: [], stale: false }` means the upstream answered with no rows.
+// Reporting an empty array as "feed down" is what made a brand-new mint with no
+// trades look like a pump.fun outage.
+
+import { cacheGet, cacheSet } from './cache.js';
+
+export const PUMP_FRONTEND_BASE =
+ process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';
+export const PUMP_SWAP_BASE = process.env.PUMP_SWAP_BASE || 'https://swap-api.pump.fun';
+
+const UA = 'three.ws-pump-feed/1';
+const DEFAULT_TIMEOUT_MS = Number(process.env.PUMP_FEED_TIMEOUT_MS || 6000);
+// Trade rows for a mint are shared by every window and every caller; a short TTL
+// keeps the data live while collapsing a burst of identical pulls into one.
+const TRADES_TTL_S = Number(process.env.PUMP_FEED_TRADES_TTL_S || 20);
+// The market-cap board turns over far more slowly than the trade feed.
+const BOARD_TTL_S = Number(process.env.PUMP_FEED_BOARD_TTL_S || 30);
+// How long a last-known-good copy stays servable once the live TTL has lapsed.
+// Long enough to ride out a Cloudflare rate-limit window, short enough that a
+// stale answer is still about the current market.
+const TRADES_LKG_TTL_S = Number(process.env.PUMP_FEED_TRADES_LKG_TTL_S || 600);
+const BOARD_LKG_TTL_S = Number(process.env.PUMP_FEED_BOARD_LKG_TTL_S || 1800);
+// Upper bound on a Retry-After honoured inline. Cloudflare sometimes asks for a
+// minute, which is longer than the whole request budget; past this we give up on
+// the retry and let the caller degrade.
+const MAX_RETRY_WAIT_MS = 1500;
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// Parse Retry-After (delta-seconds or HTTP-date) into a bounded millisecond wait.
+// Absent or unparseable → a short fixed backoff, which is what a 1015 needs.
+function retryDelayMs(res) {
+ const raw = res?.headers?.get?.('retry-after');
+ if (raw) {
+ const secs = Number(raw);
+ if (Number.isFinite(secs) && secs >= 0) return Math.min(secs * 1000, MAX_RETRY_WAIT_MS);
+ const at = Date.parse(raw);
+ if (Number.isFinite(at)) return Math.min(Math.max(at - Date.now(), 0), MAX_RETRY_WAIT_MS);
+ }
+ return 400;
+}
+
+/**
+ * Fetch JSON from a pump.fun feed with one bounded retry on a rate limit or a
+ * transient server error. Never throws: a network failure, timeout or bad body
+ * is reported as `{ ok: false }`.
+ *
+ * @param {string} url
+ * @param {{ timeoutMs?: number, retries?: number }} [opts]
+ * @returns {Promise<{ ok: boolean, status: number, body: any }>}
+ */
+export async function pumpFetchJson(url, { timeoutMs = DEFAULT_TIMEOUT_MS, retries = 1 } = {}) {
+ let attempt = 0;
+ let lastStatus = 0;
+ for (;;) {
+ let res;
+ try {
+ res = await fetch(url, {
+ headers: { accept: 'application/json', 'user-agent': UA },
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ } catch {
+ return { ok: false, status: 0, body: null };
+ }
+ lastStatus = res.status;
+ if (res.ok) {
+ const body = await res.json().catch(() => null);
+ if (body == null) return { ok: false, status: res.status, body: null };
+ return { ok: true, status: res.status, body };
+ }
+ const retryable = res.status === 429 || res.status >= 500;
+ if (!retryable || attempt >= retries) return { ok: false, status: res.status, body: null };
+ await sleep(retryDelayMs(res));
+ attempt += 1;
+ }
+}
+
+/** Pull the trade array out of either accepted swap-api envelope. */
+function tradesFrom(body) {
+ if (Array.isArray(body)) return body;
+ if (Array.isArray(body?.trades)) return body.trades;
+ return [];
+}
+
+/**
+ * Read-through cache with a last-known-good tier. A live hit answers first; a
+ * miss fetches and refreshes both tiers; a failed fetch falls back to the
+ * last-known-good copy and says so. Cache writes are fire-and-forget: the rows
+ * are already in hand and the cache is an optimization, never part of the result.
+ *
+ * @returns {Promise<{ rows: Array<object>, stale: boolean }|null>}
+ */
+async function readThroughFeed({ key, ttlSeconds, lkgKey, lkgTtlSeconds, fetchRows }) {
+ const hit = await cacheGet(key);
+ if (Array.isArray(hit)) return { rows: hit, stale: false };
+ const rows = await fetchRows();
+ if (Array.isArray(rows)) {
+ cacheSet(key, rows, ttlSeconds).catch(() => {});
+ cacheSet(lkgKey, rows, lkgTtlSeconds).catch(() => {});
+ return { rows, stale: false };
+ }
+ const lkg = await cacheGet(lkgKey);
+ if (Array.isArray(lkg)) return { rows: lkg, stale: true };
+ return null;
+}
+
+/**
+ * Recent trades for one mint, shared across callers and windows for TRADES_TTL_S.
+ *
+ * @param {string} mint
+ * @param {{ limit?: number, timeoutMs?: number }} [opts]
+ * @returns {Promise<{ rows: Array<object>, stale: boolean }|null>} null when the
+ * upstream failed and no last-known-good copy is left
+ */
+export async function fetchPumpTrades(mint, { limit = 100, timeoutMs } = {}) {
+ const rows = Math.max(1, Math.floor(limit));
+ return readThroughFeed({
+ key: `pump:feed:trades:${mint}:${rows}`,
+ ttlSeconds: TRADES_TTL_S,
+ lkgKey: `pump:feed:trades:lkg:${mint}:${rows}`,
+ lkgTtlSeconds: TRADES_LKG_TTL_S,
+ fetchRows: async () => {
+ const url = `${PUMP_SWAP_BASE}/v2/coins/${encodeURIComponent(mint)}/trades?limit=${rows}`;
+ const { ok, body } = await pumpFetchJson(url, { timeoutMs });
+ return ok ? tradesFrom(body) : null;
+ },
+ });
+}
+
+/** Pull the coin array out of either accepted frontend-api envelope. */
+function coinsFrom(body) {
+ const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : [];
+ return coins.filter((c) => c && typeof c.mint === 'string' && c.mint.length >= 32);
+}
+
+/**
+ * The pump.fun market-cap board, shared across callers for BOARD_TTL_S.
+ *
+ * @param {{ limit?: number, timeoutMs?: number }} [opts]
+ * @returns {Promise<{ rows: Array<object>, stale: boolean }|null>} raw coin rows,
+ * or null when the upstream failed with no last-known-good copy left
+ */
+export async function fetchPumpBoard({ limit = 20, timeoutMs } = {}) {
+ const rows = Math.max(1, Math.floor(limit));
+ return readThroughFeed({
+ key: `pump:feed:board:${rows}`,
+ ttlSeconds: BOARD_TTL_S,
+ lkgKey: `pump:feed:board:lkg:${rows}`,
+ lkgTtlSeconds: BOARD_LKG_TTL_S,
+ fetchRows: async () => {
+ const url = new URL('/coins', PUMP_FRONTEND_BASE);
+ url.searchParams.set('offset', '0');
+ url.searchParams.set('limit', String(rows));
+ url.searchParams.set('sort', 'market_cap');
+ url.searchParams.set('order', 'DESC');
+ url.searchParams.set('includeNsfw', 'false');
+ const { ok, body } = await pumpFetchJson(url.toString(), { timeoutMs });
+ return ok ? coinsFrom(body) : null;
+ },
+ });
+}
diff --git a/api/_lib/pump-whale-scan.js b/api/_lib/pump-whale-scan.js
index dd57740c0..63b5114fe 100644
--- a/api/_lib/pump-whale-scan.js
+++ b/api/_lib/pump-whale-scan.js
@@ -12,13 +12,14 @@
// in computeSignal + docs/crypto-api.md) — never an LLM. All fetches degrade to
// an empty result on upstream failure so the endpoint answers 200, never 500.
//
-// Data source: pump.fun public swap-api (trades) + frontend-api-v3 (top coins).
-// Both are keyless. Reuses the same hosts + trade shape as the paid
-// api/x402/pump-agent-audit.js whale oracle, exposed here free and cleaner.
+// Data source: pump.fun public swap-api (trades) + frontend-api-v3 (top coins),
+// read through api/_lib/pump-feed-fetch.js so a market scan shares its cached
+// board and trade pulls with every other pump.fun reader instead of re-tripping
+// Cloudflare's rate limit. Both are keyless. Reuses the same hosts + trade shape
+// as the paid api/x402/pump-agent-audit.js whale oracle, exposed here free and
+// cleaner.
-const PUMP_FRONTEND_BASE =
- process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';
-const PUMP_SWAP_BASE = process.env.PUMP_SWAP_BASE || 'https://swap-api.pump.fun';
+import { fetchPumpTrades, fetchPumpBoard } from './pump-feed-fetch.js';
export const WHALE_MIN_SOL_DEFAULT = Number(process.env.PUMP_WHALE_SOL_THRESHOLD || 5);
export const WHALE_LIMIT_DEFAULT = 10;
@@ -169,62 +170,50 @@ export function buildWhaleResult({ trades, scope, mint, minSol, limit }) {
}
// ── Upstream fetches (network boundary — always degrade, never throw) ─────────
-async function fetchJson(url, timeoutMs) {
- try {
- const r = await fetch(url, {
- headers: { accept: 'application/json', 'user-agent': 'three.ws-crypto-whales/1' },
- signal: AbortSignal.timeout(timeoutMs),
- });
- if (!r.ok) return null;
- return await r.json().catch(() => null);
- } catch {
- return null;
- }
-}
+// Both helpers answer `{ rows, stale }` or null, where null means the call FAILED
+// with nothing cached to fall back on. That lets `degraded` below mean "the feed
+// is down" rather than "this mint is quiet": a mint with no recent trades is a
+// real, reportable answer, not an outage.
export async function fetchCoinTrades(mint, limit = TRADES_PER_COIN) {
- const body = await fetchJson(
- `${PUMP_SWAP_BASE}/v2/coins/${encodeURIComponent(mint)}/trades?limit=${limit}`,
- 6000,
- );
- if (Array.isArray(body)) return body;
- if (Array.isArray(body?.trades)) return body.trades;
- return [];
+ return fetchPumpTrades(mint, { limit });
}
export async function fetchTopCoins(limit = 20) {
- const body = await fetchJson(
- `${PUMP_FRONTEND_BASE}/coins?offset=0&limit=${limit}&sort=market_cap&order=DESC&includeNsfw=false`,
- 7000,
- );
- const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : [];
- return coins.filter((c) => c && typeof c.mint === 'string' && c.mint.length >= 32);
+ return fetchPumpBoard({ limit });
}
// Token scope — whale buys of one specific mint. Upstream down → empty result.
export async function scanTokenWhales({ mint, minSol, limit }) {
- const trades = await fetchCoinTrades(mint, TRADES_PER_COIN);
- return {
- ...buildWhaleResult({ trades, scope: 'token', mint, minSol, limit }),
- degraded: trades.length === 0,
+ const feed = await fetchCoinTrades(mint, TRADES_PER_COIN);
+ const out = {
+ ...buildWhaleResult({ trades: feed?.rows || [], scope: 'token', mint, minSol, limit }),
+ degraded: feed === null,
};
+ if (feed?.stale) out.stale = true;
+ return out;
}
// Market scope — top whale wallets across the top pump.fun coins right now.
-// Upstream down → empty result (never throws).
+// Upstream down → empty result (never throws). Degraded only when the board is
+// unreachable or every sampled coin's trade pull failed; a board that is simply
+// quiet reports an honest empty set.
export async function scanMarketWhales({ minSol, limit }) {
- const topCoins = await fetchTopCoins(20);
- if (!topCoins.length) {
+ const board = await fetchTopCoins(20);
+ if (!board || !board.rows.length) {
return {
...buildWhaleResult({ trades: [], scope: 'market', mint: null, minSol, limit }),
degraded: true,
};
}
- const sample = topCoins.slice(0, MARKET_COINS_SAMPLE);
+ const sample = board.rows.slice(0, MARKET_COINS_SAMPLE);
const results = await Promise.allSettled(sample.map((c) => fetchCoinTrades(c.mint, TRADES_PER_COIN)));
- const trades = results.flatMap((r) => (r.status === 'fulfilled' ? r.value : []));
- return {
+ const answered = results.flatMap((r) => (r.status === 'fulfilled' && r.value ? [r.value] : []));
+ const trades = answered.flatMap((f) => f.rows);
+ const out = {
...buildWhaleResult({ trades, scope: 'market', mint: null, minSol, limit }),
- degraded: trades.length === 0,
+ degraded: answered.length === 0,
};
+ if (board.stale || answered.some((f) => f.stale)) out.stale = true;
+ return out;
}
diff --git a/api/crypto/whales.js b/api/crypto/whales.js
index 1b6d28bed..d2b275ba7 100644
--- a/api/crypto/whales.js
+++ b/api/crypto/whales.js
@@ -16,8 +16,11 @@
// computeSignal + docs/crypto-api.md), never an LLM.
//
// Never 500 on a well-formed request: no whales over threshold → 200 empty +
-// neutral; feed down → 200 empty + a `note`. A paid, coarser version of this
-// data lives at api/x402/pump-agent-audit.js; this is the free, cleaner read.
+// neutral; feed down → 200 empty + a `note`. When pump.fun rate-limits us the
+// scan falls back to its last-known-good trade pull and the body carries
+// `stale: true`, so an agent can tell live rows from minutes-old ones. A paid,
+// coarser version of this data lives at api/x402/pump-agent-audit.js; this is
+// the free, cleaner read.
import { wrap, cors, method, json, error, rateLimited, setRateLimitHeaders } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
diff --git a/api/v1/pump/whales.js b/api/v1/pump/whales.js
index 1c1ce664d..f9e4b3e9a 100644
--- a/api/v1/pump/whales.js
+++ b/api/v1/pump/whales.js
@@ -80,6 +80,9 @@ export default defineEndpoint({
if (result.degraded) {
body.note = 'pump.fun feed is temporarily unavailable — returning an empty whale set; retry shortly';
}
+ // The feed was rate-limited and these rows came from the last-known-good
+ // pull. Real trades, a few minutes old: say so rather than imply live.
+ if (result.stale) body.stale = true;
return body;
},
});
diff --git a/tests/api/crypto-whales-endpoint.test.js b/tests/api/crypto-whales-endpoint.test.js
new file mode 100644
index 000000000..c3ddec725
--- /dev/null
+++ b/tests/api/crypto-whales-endpoint.test.js
@@ -0,0 +1,166 @@
+// GET /api/crypto/whales — the free whale-activity endpoint contract.
+//
+// The scan engine's pure aggregation (threshold filter, per-scope shaping, the
+// net-flow signal) is covered in tests/crypto-whales.test.js. Here we pin the
+// ENDPOINT: method + input validation, scope selection, the clamps on minSol and
+// limit, the degraded note, the stale flag, and the cache header. The scan module
+// is mocked so no pump.fun request is made. Fixtures use $THREE (CA in CLAUDE.md)
+// and a synthetic mint, never a real third-party mint.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const scanTokenWhalesMock = vi.fn();
+const scanMarketWhalesMock = vi.fn();
+
+vi.mock('../../api/_lib/pump-whale-scan.js', () => ({
+ scanTokenWhales: (...a) => scanTokenWhalesMock(...a),
+ scanMarketWhales: (...a) => scanMarketWhalesMock(...a),
+ WHALE_MIN_SOL_DEFAULT: 5,
+ WHALE_LIMIT_DEFAULT: 10,
+ WHALE_LIMIT_MAX: 25,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { marketDataIp: vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: 0 })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { default: handler } = await import('../../api/crypto/whales.js');
+const { limits } = await import('../../api/_lib/rate-limit.js');
+
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; },
+ };
+}
+
+async function call(url, method = 'GET') {
+ const res = makeRes();
+ await handler({ url, method, headers: { host: 'x' } }, res);
+ let body = null;
+ try { body = JSON.parse(res._body); } catch {}
+ return { res, body };
+}
+
+function scanResult(over = {}) {
+ return {
+ scope: 'market',
+ mint: null,
+ whales: [{ wallet: 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk', solMoved: 12.5, txHash: 'sig1', ts: '2026-08-12T20:00:00.000Z' }],
+ whaleCount: 1,
+ totalSolMoved: 12.5,
+ signal: 'bullish',
+ ts: '2026-08-12T20:00:01.000Z',
+ source: 'pump.fun',
+ degraded: false,
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ scanTokenWhalesMock.mockReset();
+ scanMarketWhalesMock.mockReset();
+ scanMarketWhalesMock.mockResolvedValue(scanResult());
+ scanTokenWhalesMock.mockResolvedValue(scanResult({ scope: 'token', mint: THREE }));
+ limits.marketDataIp.mockResolvedValue({ success: true, limit: 60, remaining: 59, reset: 0 });
+});
+
+describe('GET /api/crypto/whales — scope selection', () => {
+ it('no mint scans the market and never calls the token scan', async () => {
+ const { res, body } = await call('/api/crypto/whales');
+ expect(res.statusCode).toBe(200);
+ expect(scanMarketWhalesMock).toHaveBeenCalledTimes(1);
+ expect(scanTokenWhalesMock).not.toHaveBeenCalled();
+ expect(body.scope).toBe('market');
+ expect(body.minSol).toBe(5);
+ expect(body.signal).toBe('bullish');
+ expect(res.getHeader('cache-control')).toMatch(/s-maxage=15/);
+ });
+
+ it('a mint scans that token and echoes it back', async () => {
+ const { body } = await call(`/api/crypto/whales?mint=${THREE}`);
+ expect(scanTokenWhalesMock).toHaveBeenCalledWith({ mint: THREE, minSol: 5, limit: 10 });
+ expect(body.scope).toBe('token');
+ expect(body.mint).toBe(THREE);
+ });
+});
+
+describe('GET /api/crypto/whales — input validation', () => {
+ it('405s a non-GET method', async () => {
+ const { res, body } = await call('/api/crypto/whales', 'POST');
+ expect(res.statusCode).toBe(405);
+ expect(body.error).toBe('method_not_allowed');
+ expect(scanMarketWhalesMock).not.toHaveBeenCalled();
+ });
+
+ it('400s a malformed mint before any scan', async () => {
+ const { res, body } = await call('/api/crypto/whales?mint=not-base58!!');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_mint');
+ expect(body.example).toContain('mint=');
+ expect(scanTokenWhalesMock).not.toHaveBeenCalled();
+ });
+
+ it('400s a non-numeric or non-positive minSol', async () => {
+ for (const bad of ['abc', '0', '-3']) {
+ const { res, body } = await call(`/api/crypto/whales?minSol=${bad}`);
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_min_sol');
+ }
+ expect(scanMarketWhalesMock).not.toHaveBeenCalled();
+ });
+
+ it('400s a limit below 1', async () => {
+ const { res, body } = await call('/api/crypto/whales?limit=0');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_limit');
+ });
+
+ it('clamps minSol to the 0.1 floor and limit to the 25 ceiling', async () => {
+ await call('/api/crypto/whales?minSol=0.0001&limit=9999');
+ expect(scanMarketWhalesMock).toHaveBeenCalledWith({ minSol: 0.1, limit: 25 });
+ });
+
+ it('429s with the rate-limit headers when the IP bucket is exhausted', async () => {
+ limits.marketDataIp.mockResolvedValue({ success: false, limit: 60, remaining: 0, reset: 1_800_000_000 });
+ const { res, body } = await call('/api/crypto/whales');
+ expect(res.statusCode).toBe(429);
+ expect(body.error).toBeTruthy();
+ expect(scanMarketWhalesMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/crypto/whales — degraded + stale honesty', () => {
+ it('feed down → 200 with an empty set and a retry note, never a 5xx', async () => {
+ scanMarketWhalesMock.mockResolvedValue(
+ scanResult({ whales: [], whaleCount: 0, totalSolMoved: 0, signal: 'neutral', degraded: true }),
+ );
+ const { res, body } = await call('/api/crypto/whales');
+ expect(res.statusCode).toBe(200);
+ expect(body.whales).toEqual([]);
+ expect(body.signal).toBe('neutral');
+ expect(body.note).toMatch(/temporarily unavailable/i);
+ expect(body.degraded).toBeUndefined();
+ });
+
+ it('a quiet market answers empty WITHOUT the outage note', async () => {
+ scanMarketWhalesMock.mockResolvedValue(
+ scanResult({ whales: [], whaleCount: 0, totalSolMoved: 0, signal: 'neutral', degraded: false }),
+ );
+ const { body } = await call('/api/crypto/whales');
+ expect(body.whales).toEqual([]);
+ expect(body.note).toBeUndefined();
+ });
+
+ it('passes a stale flag through when the scan served last-known-good rows', async () => {
+ scanMarketWhalesMock.mockResolvedValue(scanResult({ stale: true }));
+ const { body } = await call('/api/crypto/whales');
+ expect(body.stale).toBe(true);
+ });
+});
diff --git a/tests/api/pump-feed-fetch.test.js b/tests/api/pump-feed-fetch.test.js
new file mode 100644
index 000000000..17eec14b5
--- /dev/null
+++ b/tests/api/pump-feed-fetch.test.js
@@ -0,0 +1,154 @@
+// api/_lib/pump-feed-fetch.js — the shared pump.fun read layer behind
+// /api/crypto/trending and /api/crypto/whales.
+//
+// What is pinned here is exactly what used to break in production: pump.fun sits
+// behind Cloudflare, a burst of per-coin trade pulls earns HTTP 429 ("error code:
+// 1015"), and both endpoints then reported "upstream unavailable" while the feed
+// was healthy. So: the cache collapses repeat pulls, a 429 is retried once, a
+// rate-limited pull falls back to the last-known-good rows and flags them stale,
+// and a genuinely empty answer is NOT reported as an outage.
+//
+// fetch is stubbed; no network is touched. The mint fixture is $THREE.
+
+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 { pumpFetchJson, fetchPumpTrades, fetchPumpBoard } = await import('../../api/_lib/pump-feed-fetch.js');
+
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+function jsonRes(body, status = 200, headers = {}) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ headers: { get: (h) => headers[h.toLowerCase()] ?? null },
+ json: async () => body,
+ };
+}
+
+const tradeRow = { type: 'buy', amountSol: '9.5', userAddress: 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk', tx: 'sig1', timestamp: '2026-08-12T20:00:00.000Z' };
+const coinRow = { mint: THREE, symbol: 'THREE', name: 'three.ws', usd_market_cap: 1234 };
+
+beforeEach(() => {
+ cache.clear();
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+// The module sleeps between retries; run timers as they are scheduled so the
+// retry path completes without a real wall-clock wait.
+async function withTimers(promise) {
+ const settled = promise;
+ await vi.runAllTimersAsync();
+ return settled;
+}
+
+describe('pumpFetchJson — retry on a rate limit', () => {
+ it('retries once on 429 and returns the recovered body', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(jsonRes(null, 429, { 'retry-after': '0.2' }))
+ .mockResolvedValueOnce(jsonRes({ ok: 1 }));
+ vi.stubGlobal('fetch', fetchMock);
+ const out = await withTimers(pumpFetchJson('https://swap-api.pump.fun/x'));
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(out).toEqual({ ok: true, status: 200, body: { ok: 1 } });
+ });
+
+ it('gives up after the bounded retry and reports the failing status', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonRes(null, 429, {}));
+ vi.stubGlobal('fetch', fetchMock);
+ const out = await withTimers(pumpFetchJson('https://swap-api.pump.fun/x'));
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(out.ok).toBe(false);
+ expect(out.status).toBe(429);
+ });
+
+ it('does not retry a client error that will not recover', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonRes(null, 404, {}));
+ vi.stubGlobal('fetch', fetchMock);
+ const out = await withTimers(pumpFetchJson('https://swap-api.pump.fun/x'));
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(out.ok).toBe(false);
+ });
+
+ it('never throws on a network failure', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('econnreset')));
+ const out = await withTimers(pumpFetchJson('https://swap-api.pump.fun/x'));
+ expect(out).toEqual({ ok: false, status: 0, body: null });
+ });
+});
+
+describe('fetchPumpTrades — cache, envelopes, failure contract', () => {
+ it('accepts both the array and the {trades} envelope', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonRes({ trades: [tradeRow] })));
+ const wrapped = await withTimers(fetchPumpTrades(THREE, { limit: 100 }));
+ expect(wrapped).toEqual({ rows: [tradeRow], stale: false });
+
+ cache.clear();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonRes([tradeRow])));
+ const bare = await withTimers(fetchPumpTrades(THREE, { limit: 100 }));
+ expect(bare.rows).toEqual([tradeRow]);
+ });
+
+ it('serves a second pull for the same mint from cache without a second fetch', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonRes({ trades: [tradeRow] }));
+ vi.stubGlobal('fetch', fetchMock);
+ await withTimers(fetchPumpTrades(THREE, { limit: 100 }));
+ await withTimers(fetchPumpTrades(THREE, { limit: 100 }));
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('an upstream that answers with no rows is data, not an outage', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonRes({ trades: [] })));
+ const out = await withTimers(fetchPumpTrades(THREE, { limit: 100 }));
+ expect(out).toEqual({ rows: [], stale: false });
+ });
+
+ it('falls back to last-known-good rows when the feed goes down, flagged stale', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonRes({ trades: [tradeRow] })));
+ await withTimers(fetchPumpTrades(THREE, { limit: 100 }));
+ // Live TTL lapses, last-known-good survives.
+ cache.delete(`pump:feed:trades:${THREE}:100`);
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonRes(null, 429, {})));
+ const out = await withTimers(fetchPumpTrades(THREE, { limit: 100 }));
+ expect(out).toEqual({ rows: [tradeRow], stale: true });
+ });
+
+ it('returns null when the feed is down and nothing was ever cached', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonRes(null, 503, {})));
+ const out = await withTimers(fetchPumpTrades(THREE, { limit: 100 }));
+ expect(out).toBeNull();
+ });
+});
+
+describe('fetchPumpBoard — coin filtering + cache', () => {
+ it('keeps only rows carrying a plausible mint', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonRes([coinRow, { mint: 'short' }, null, { symbol: 'X' }])));
+ const out = await withTimers(fetchPumpBoard({ limit: 20 }));
+ expect(out.rows).toEqual([coinRow]);
+ expect(out.stale).toBe(false);
+ });
+
+ it('reuses the cached board for the same limit', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonRes({ coins: [coinRow] }));
+ vi.stubGlobal('fetch', fetchMock);
+ await withTimers(fetchPumpBoard({ limit: 20 }));
+ await withTimers(fetchPumpBoard({ limit: 20 }));
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('null when the board is unreachable with no last-known-good copy', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('timeout')));
+ expect(await withTimers(fetchPumpBoard({ limit: 20 }))).toBeNull();
+ });
+});
diff --git a/tests/crypto-whales.test.js b/tests/crypto-whales.test.js
index 412680674..2193c8a14 100644
--- a/tests/crypto-whales.test.js
+++ b/tests/crypto-whales.test.js
@@ -1,9 +1,20 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
normalizeTrade,
computeSignal,
buildWhaleResult,
+ scanTokenWhales,
+ scanMarketWhales,
} from '../api/_lib/pump-whale-scan.js';
+import { fetchPumpTrades, fetchPumpBoard } from '../api/_lib/pump-feed-fetch.js';
+
+// The shared pump.fun read layer is exercised in tests/api/pump-feed-fetch.js;
+// here it is stubbed so the scan's own degraded/stale reasoning is what is under
+// test, with no network involved.
+vi.mock('../api/_lib/pump-feed-fetch.js', () => ({
+ fetchPumpTrades: vi.fn(),
+ fetchPumpBoard: vi.fn(),
+}));
// Synthetic pump.fun trades — no real third-party mints/wallets (CLAUDE.md).
// Wallets are placeholder base58-ish strings; the aggregation only keys on them.
@@ -116,3 +127,84 @@ describe('buildWhaleResult — empty case', () => {
expect(r.signal).toBe('neutral');
});
});
+
+// ── scan orchestration: what "degraded" is allowed to mean ───────────────────
+// A quiet mint and a downed feed both produce an empty whale set, and the
+// endpoint prints an outage note for one of them. Conflating the two is what
+// made a brand-new mint with no trades look like a pump.fun outage, so the
+// distinction is pinned here.
+describe('scanTokenWhales / scanMarketWhales — degraded + stale', () => {
+ beforeEach(() => {
+ fetchPumpTrades.mockReset();
+ fetchPumpBoard.mockReset();
+ });
+
+ it('token scope: rows present → not degraded', async () => {
+ fetchPumpTrades.mockResolvedValue({ rows: [buy('W1', 9)], stale: false });
+ const r = await scanTokenWhales({ mint: THREE_MINT, minSol: 5, limit: 10 });
+ expect(r.degraded).toBe(false);
+ expect(r.whales).toHaveLength(1);
+ expect(r.stale).toBeUndefined();
+ });
+
+ it('token scope: a quiet mint answers empty WITHOUT claiming an outage', async () => {
+ fetchPumpTrades.mockResolvedValue({ rows: [], stale: false });
+ const r = await scanTokenWhales({ mint: THREE_MINT, minSol: 5, limit: 10 });
+ expect(r.degraded).toBe(false);
+ expect(r.whales).toEqual([]);
+ expect(r.signal).toBe('neutral');
+ });
+
+ it('token scope: an unreachable feed IS degraded', async () => {
+ fetchPumpTrades.mockResolvedValue(null);
+ const r = await scanTokenWhales({ mint: THREE_MINT, minSol: 5, limit: 10 });
+ expect(r.degraded).toBe(true);
+ expect(r.whales).toEqual([]);
+ });
+
+ it('token scope: last-known-good rows are flagged stale', async () => {
+ fetchPumpTrades.mockResolvedValue({ rows: [buy('W1', 9)], stale: true });
+ const r = await scanTokenWhales({ mint: THREE_MINT, minSol: 5, limit: 10 });
+ expect(r.degraded).toBe(false);
+ expect(r.stale).toBe(true);
+ });
+
+ it('market scope: aggregates the sampled coins and stays live', async () => {
+ fetchPumpBoard.mockResolvedValue({ rows: [{ mint: 'M1' }, { mint: 'M2' }], stale: false });
+ fetchPumpTrades.mockResolvedValue({ rows: [buy('W1', 7)], stale: false });
+ const r = await scanMarketWhales({ minSol: 5, limit: 10 });
+ expect(fetchPumpTrades).toHaveBeenCalledTimes(2);
+ expect(r.degraded).toBe(false);
+ expect(r.whaleCount).toBe(1);
+ expect(r.totalSolMoved).toBe(14);
+ });
+
+ it('market scope: an unreachable board is degraded', async () => {
+ fetchPumpBoard.mockResolvedValue(null);
+ const r = await scanMarketWhales({ minSol: 5, limit: 10 });
+ expect(r.degraded).toBe(true);
+ expect(fetchPumpTrades).not.toHaveBeenCalled();
+ });
+
+ it('market scope: degraded only when EVERY sampled trade pull failed', async () => {
+ fetchPumpBoard.mockResolvedValue({ rows: [{ mint: 'M1' }, { mint: 'M2' }], stale: false });
+ fetchPumpTrades.mockResolvedValue(null);
+ const r = await scanMarketWhales({ minSol: 5, limit: 10 });
+ expect(r.degraded).toBe(true);
+
+ fetchPumpTrades.mockReset();
+ fetchPumpTrades.mockResolvedValueOnce(null).mockResolvedValueOnce({ rows: [buy('W1', 8)], stale: false });
+ const partial = await scanMarketWhales({ minSol: 5, limit: 10 });
+ expect(partial.degraded).toBe(false);
+ expect(partial.whaleCount).toBe(1);
+ });
+
+ it('market scope: one stale leg flags the whole result stale', async () => {
+ fetchPumpBoard.mockResolvedValue({ rows: [{ mint: 'M1' }, { mint: 'M2' }], stale: false });
+ fetchPumpTrades
+ .mockResolvedValueOnce({ rows: [buy('W1', 8)], stale: true })
+ .mockResolvedValueOnce({ rows: [buy('W2', 6)], stale: false });
+ const r = await scanMarketWhales({ minSol: 5, limit: 10 });
+ expect(r.stale).toBe(true);
+ });
+});