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.

feat(crypto): free momentum-ranked trending/hot tokens API

nich151854a30104
diff --git a/api/_lib/crypto-catalog/trending.js b/api/_lib/crypto-catalog/trending.js
new file mode 100644
index 000000000..34488fbd6
--- /dev/null
+++ b/api/_lib/crypto-catalog/trending.js
@@ -0,0 +1,87 @@
+// Crypto Data API catalog entry — trending / hot tokens.
+// Globbed by api/_lib/crypto-catalog/index.js (prompt 10) into the /api/crypto
+// index + OpenAPI doc. Stands alone if that assembler doesn't exist yet.
+
+export default {
+ slug: 'trending',
+ method: 'GET',
+ path: '/api/crypto/trending',
+ title: 'Trending / hot tokens',
+ summary:
+ "Solana tokens ranked by momentum (windowed volume + buy pressure + volume spike + " +
+ "short-window price change) fused across pump.fun, DexScreener, and GMGN smart money. " +
+ "One call for a discovery agent's \"what's hot right now\".",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ window: {
+ type: 'string',
+ enum: ['5m', '1h', '24h'],
+ default: '1h',
+ description: 'Trade window the momentum score measures.',
+ },
+ limit: {
+ type: 'integer',
+ minimum: 1,
+ maximum: 50,
+ default: 20,
+ description: 'Max tokens to return (capped at 50).',
+ },
+ source: {
+ type: 'string',
+ enum: ['pumpfun', 'all'],
+ default: 'all',
+ description: "'pumpfun' restricts to the pump.fun board; 'all' fuses every source.",
+ },
+ },
+ },
+ outputSchema: {
+ type: 'object',
+ properties: {
+ window: { type: 'string' },
+ tokens: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ symbol: { type: ['string', 'null'] },
+ name: { type: ['string', 'null'] },
+ marketCapUsd: { type: ['number', 'null'] },
+ volumeUsd: { type: ['number', 'null'] },
+ change: { type: ['number', 'null'], description: 'Price change % over the window.' },
+ score: { type: 'number', description: 'Momentum score 0–100, ranked desc.' },
+ url: { type: ['string', 'null'] },
+ },
+ required: ['mint', 'score'],
+ },
+ },
+ count: { type: 'integer' },
+ ts: { type: 'string', format: 'date-time' },
+ sources: { type: 'array', items: { type: 'string' } },
+ note: { type: 'string' },
+ },
+ required: ['window', 'tokens', 'count', 'ts', 'sources'],
+ },
+ example: {
+ request: '/api/crypto/trending?window=1h&limit=5&source=all',
+ response: {
+ window: '1h',
+ tokens: [
+ {
+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ symbol: 'THREE',
+ name: 'three.ws',
+ marketCapUsd: 412000,
+ volumeUsd: 18450.32,
+ change: 12.4,
+ score: 87.5,
+ url: 'https://pump.fun/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ },
+ ],
+ count: 1,
+ ts: '2026-07-07T00:00:00.000Z',
+ sources: ['pumpfun', 'dexscreener'],
+ },
+ },
+};
diff --git a/api/_lib/crypto-trending.js b/api/_lib/crypto-trending.js
new file mode 100644
index 000000000..b521fad05
--- /dev/null
+++ b/api/_lib/crypto-trending.js
@@ -0,0 +1,370 @@
+// api/_lib/crypto-trending.js
+//
+// Composition engine behind the free GET /api/crypto/trending endpoint.
+//
+// "What's hot right now" = tokens ranked by MOMENTUM, not raw size. We fuse three
+// live, keyless signals and reuse the platform's existing scoring primitives
+// rather than inventing new market math:
+//
+// • pump.fun — the live board (frontend-api-v3) + per-coin swap-API trade feed.
+// Windowed USD volume comes from summarizeWindowUsd() and buy
+// pressure from scorePressure() — the exact helpers that power the
+// paid crypto-intel `pump_trending` / `pump_volume_anomaly` topics.
+// • DexScreener — the boosted-token board via gmgn-feed.js dexScreenerTrending()
+// (24h volume, 1h/24h price change, buy/sell txn counts). Cross-chain
+// attention/spend signal.
+// • GMGN — smart-money rank via gmgn-feed.js gmgnSmartMoneyRank(), best-effort:
+// serverless egress IPs are frequently Cloudflare-blocked, so this
+// degrades to nothing (never an error) when unavailable.
+//
+// ── The ranking signal (documented, stable) ──────────────────────────────────
+// Each token is reduced to up-to-four momentum features, normalized WITHIN its
+// source so cross-source volume-scale differences don't distort the blend:
+// volShare = volumeUsd / max(volumeUsd in that source) weight 0.45
+// buyDom = clamp((buyPressure - 0.5) / 0.5, 0, 1) weight 0.25
+// spike = min(volumeUsd / median(peer volumeUsd), CAP)/CAP weight 0.20
+// change = clamp(changePct / CHANGE_CAP, 0, 1) weight 0.10
+// score = 100 × Σ(weightᵢ·featureᵢ over PRESENT features) / Σ(present weights),
+// so a source that can't supply one feature (e.g. no buy pressure) is scored on
+// what it has rather than penalized. Tokens are ranked by `score` desc; ties break
+// on volumeUsd. The volume "spike" reuses pump-volume-anomaly's median() baseline —
+// the same robust peer-median an anomaly verdict is built on.
+
+import { scorePressure } from './x402/pump-trending-score.js';
+import { summarizeWindowUsd, median } from './x402/pump-volume-anomaly.js';
+import { dexScreenerTrending, gmgnSmartMoneyRank } from './gmgn-feed.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);
+const PUMP_TRADES_PER_COIN = Number(process.env.CRYPTO_TRENDING_TRADES_PER_COIN || 100);
+const PUMP_CONCURRENCY = Number(process.env.CRYPTO_TRENDING_CONCURRENCY || 6);
+
+// Ranking weights + saturation caps (see header). Exported so tests + docs read
+// from one source of truth.
+export const WEIGHTS = { volume: 0.45, buyDom: 0.25, spike: 0.2, change: 0.1 };
+export const SPIKE_RATIO_CAP = 3; // volume ratio at which the spike term saturates
+export const CHANGE_CAP = 50; // % price change at which the change term saturates
+
+export const WINDOWS = new Set(['5m', '1h', '24h']);
+const WINDOW_SEC = { '5m': 300, '1h': 3600, '24h': 86400 };
+
+/** Map a window token → trailing seconds. Unknown → 1h. Pure. */
+export function windowToSec(window) {
+ return WINDOW_SEC[window] || WINDOW_SEC['1h'];
+}
+
+function num(v) {
+ const n = typeof v === 'string' ? parseFloat(v) : v;
+ return Number.isFinite(n) ? n : null;
+}
+
+function clamp01(n) {
+ return n < 0 ? 0 : n > 1 ? 1 : n;
+}
+
+function round(n, dp = 2) {
+ if (!Number.isFinite(n)) return null;
+ const f = 10 ** dp;
+ return Math.round(n * f) / f;
+}
+
+/**
+ * Assign a 0–100 momentum score to each token in a single-source set and return
+ * a NEW array sorted by score desc (ties broken on volumeUsd desc). Pure — the
+ * whole ranking signal lives here so it's unit-testable without any network.
+ *
+ * @param {Array<{ mint, symbol?, name?, marketCapUsd?, volumeUsd?, buyPressure?, changePct? }>} tokens
+ * @returns {Array<object>} tokens with `score` added, ranked
+ */
+export function rankTokens(tokens) {
+ const list = Array.isArray(tokens) ? tokens.filter(Boolean) : [];
+ if (!list.length) return [];
+
+ const vols = list.map((t) => num(t.volumeUsd)).filter((v) => v != null && v > 0);
+ const maxVol = vols.length ? Math.max(...vols) : 0;
+ // Robust peer baseline for the "spike" term — the same median() an anomaly
+ // verdict is built on. Zero when there aren't enough peers to compare against.
+ const baseline = median(vols);
+
+ const scored = list.map((t) => {
+ const vol = num(t.volumeUsd);
+ const bp = num(t.buyPressure);
+ const chg = num(t.changePct);
+
+ let weighted = 0;
+ let presentWeight = 0;
+
+ if (vol != null && vol > 0 && maxVol > 0) {
+ weighted += WEIGHTS.volume * clamp01(vol / maxVol);
+ presentWeight += WEIGHTS.volume;
+ if (baseline > 0) {
+ const ratio = vol / baseline;
+ weighted += WEIGHTS.spike * clamp01(Math.min(ratio, SPIKE_RATIO_CAP) / SPIKE_RATIO_CAP);
+ presentWeight += WEIGHTS.spike;
+ }
+ }
+ if (bp != null) {
+ weighted += WEIGHTS.buyDom * clamp01((bp - 0.5) / 0.5);
+ presentWeight += WEIGHTS.buyDom;
+ }
+ if (chg != null) {
+ weighted += WEIGHTS.change * clamp01(chg / CHANGE_CAP);
+ presentWeight += WEIGHTS.change;
+ }
+
+ const score = presentWeight > 0 ? round((100 * weighted) / presentWeight) : 0;
+ return { ...t, volumeUsd: vol, changePct: chg, score };
+ });
+
+ scored.sort((a, b) => b.score - a.score || (num(b.volumeUsd) ?? 0) - (num(a.volumeUsd) ?? 0));
+ return scored;
+}
+
+/**
+ * Merge scored token sets from several sources, dedupe by mint (keep the highest
+ * score), re-sort desc, and slice to `limit`. Pure. Later argument order does not
+ * matter — the max-score winner is kept regardless.
+ */
+export function mergeAndRank(sets, limit) {
+ const byMint = new Map();
+ for (const set of sets) {
+ for (const t of set || []) {
+ if (!t || !t.mint) continue;
+ const prev = byMint.get(t.mint);
+ if (!prev || t.score > prev.score) byMint.set(t.mint, t);
+ }
+ }
+ const merged = [...byMint.values()].sort(
+ (a, b) => b.score - a.score || (num(b.volumeUsd) ?? 0) - (num(a.volumeUsd) ?? 0),
+ );
+ return merged.slice(0, Math.max(0, limit));
+}
+
+/** Shape a ranked internal token into the public output row. Pure. */
+export function toOutputRow(t) {
+ return {
+ mint: t.mint,
+ symbol: t.symbol || null,
+ name: t.name || null,
+ marketCapUsd: num(t.marketCapUsd),
+ volumeUsd: num(t.volumeUsd),
+ change: num(t.changePct),
+ score: t.score,
+ url: t.url || null,
+ };
+}
+
+// ── 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);
+ let cursor = 0;
+ const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
+ for (;;) {
+ const i = cursor++;
+ if (i >= items.length) break;
+ out[i] = await fn(items[i], i);
+ }
+ });
+ await Promise.all(workers);
+ return out;
+}
+
+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),
+ }));
+}
+
+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 : [];
+}
+
+/**
+ * Live pump.fun momentum set: board coins scored by windowed USD volume +
+ * per-coin buy pressure, using the shared pure scorers. Returns [] on outage
+ * (never throws) so the aggregate call degrades gracefully.
+ */
+export async function fetchPumpfunTrending({ windowSec, limit, nowMs = Date.now() }) {
+ const board = await fetchPumpBoard(Math.min(50, Math.max(limit, 20)));
+ if (!board || !board.length) return [];
+ const top = board.slice(0, Math.min(PUMP_TRADE_COINS, board.length));
+
+ const enriched = await mapLimit(top, PUMP_CONCURRENCY, async (c) => {
+ const trades = await fetchCoinTrades(c.mint);
+ const { usd } = summarizeWindowUsd(trades, nowMs, windowSec);
+ // scorePressure() is the crypto-intel buy-pressure primitive; feed it a
+ // single-coin group to get this coin's buy/sell balance for the window.
+ const { buyPressure, totalBuys, totalSells } = scorePressure([{ mint: c.mint, trades }]);
+ const hasFlow = totalBuys + totalSells > 0;
+ return {
+ ...c,
+ volumeUsd: usd,
+ buyPressure: hasFlow ? buyPressure : null,
+ changePct: null, // pump.fun swap feed carries no per-window % change; left honest-null
+ url: `https://pump.fun/coin/${c.mint}`,
+ _source: 'pumpfun',
+ };
+ });
+
+ // Keep only coins that actually traded in the window — a board coin with zero
+ // window volume isn't "hot right now", it's just large.
+ return rankTokens(enriched.filter((t) => (num(t.volumeUsd) ?? 0) > 0));
+}
+
+/** Map a gmgn-feed dexScreenerTrending() rank row → internal token. Pure. */
+export function mapDexRow(row, window) {
+ const buys = num(row.txns_h1_buys);
+ const sells = num(row.txns_h1_sells);
+ const flow = (buys ?? 0) + (sells ?? 0);
+ const changePct = window === '24h' ? num(row.price_change_24h) : num(row.price_change_1h);
+ return {
+ mint: row.address,
+ symbol: row.symbol || null,
+ name: row.name || null,
+ marketCapUsd: num(row.market_cap),
+ volumeUsd: num(row.volume),
+ buyPressure: flow > 0 ? (buys ?? 0) / flow : null,
+ changePct,
+ url: `https://dexscreener.com/solana/${row.address}`,
+ _source: 'dexscreener',
+ };
+}
+
+/** Live DexScreener boosted-token momentum set. Returns [] on outage. */
+export async function fetchDexTrending({ window }) {
+ const res = await dexScreenerTrending({ chain: 'sol' }).catch(() => null);
+ if (!res || !res.ok || !Array.isArray(res.rank) || !res.rank.length) return [];
+ const tokens = res.rank
+ .filter((r) => r && typeof r.address === 'string' && r.address.length >= 32)
+ .map((r) => mapDexRow(r, window));
+ return rankTokens(tokens);
+}
+
+/** Map a raw GMGN smart-money rank row → internal token. Pure, fully guarded. */
+export function mapGmgnRow(row, window) {
+ if (!row || typeof row.address !== 'string' || row.address.length < 32) return null;
+ const smartBuy = num(row.smart_buy_24h ?? row.smartbuy_24h);
+ const smartSell = num(row.smart_sell_24h ?? row.smartsell_24h);
+ const flow = (smartBuy ?? 0) + (smartSell ?? 0);
+ const changePct =
+ window === '24h'
+ ? num(row.price_change_percent24h ?? row.price_change_percent)
+ : num(row.price_change_percent1h ?? row.price_change_percent);
+ return {
+ mint: row.address,
+ symbol: row.symbol || null,
+ name: row.name || row.symbol || null,
+ marketCapUsd: num(row.market_cap_usd ?? row.market_cap),
+ volumeUsd: num(row.volume ?? row.volume_24h),
+ buyPressure: flow > 0 ? (smartBuy ?? 0) / flow : null,
+ changePct,
+ url: `https://gmgn.ai/sol/token/${row.address}`,
+ _source: 'gmgn',
+ };
+}
+
+/**
+ * Best-effort GMGN smart-money momentum set. Serverless IPs are usually
+ * Cloudflare-blocked, so this returns [] far more often than not — by design,
+ * never an error.
+ */
+export async function fetchGmgnTrending({ window }) {
+ const interval = window === '24h' ? '24h' : '1h';
+ const res = await gmgnSmartMoneyRank({ chain: 'sol', interval }).catch(() => null);
+ if (!res || !res.ok || !Array.isArray(res.rank) || !res.rank.length) return [];
+ const tokens = res.rank.map((r) => mapGmgnRow(r, window)).filter(Boolean);
+ return rankTokens(tokens);
+}
+
+/**
+ * Compose the ranked trending list across the requested sources.
+ *
+ * @param {{ window: string, limit: number, source: 'pumpfun'|'all', nowMs?: number,
+ * deps?: { pumpfun?, dexscreener?, gmgn? } }} opts
+ * `deps` overrides the live source fetchers (each returns a scored token array);
+ * used by tests to exercise source filtering / limit cap / dedupe without network.
+ * @returns {Promise<{ window, tokens, count, ts, sources: string[], note?: string }>}
+ */
+export async function composeTrending({ window, limit, source, nowMs = Date.now(), deps = {} }) {
+ const windowSec = windowToSec(window);
+ const cappedLimit = Math.min(50, Math.max(1, limit));
+ const pumpfun = deps.pumpfun || (() => fetchPumpfunTrending({ windowSec, limit: cappedLimit, nowMs }));
+ const dexscreener = deps.dexscreener || (() => fetchDexTrending({ window }));
+ const gmgn = deps.gmgn || (() => fetchGmgnTrending({ window }));
+
+ const jobs = [];
+ jobs.push({ name: 'pumpfun', run: pumpfun });
+ if (source === 'all') {
+ jobs.push({ name: 'dexscreener', run: dexscreener });
+ jobs.push({ name: 'gmgn', run: gmgn });
+ }
+
+ const settled = await Promise.all(
+ jobs.map(async (j) => {
+ try {
+ return { name: j.name, rows: await j.run() };
+ } catch {
+ // A source helper already swallows its own errors; this is the last
+ // guard so one bad upstream can never fail the whole aggregate call.
+ return { name: j.name, rows: [] };
+ }
+ }),
+ );
+
+ const contributing = settled.filter((s) => s.rows.length > 0);
+ const sources = contributing.map((s) => s.name);
+ const tokens = mergeAndRank(contributing.map((s) => s.rows), cappedLimit).map(toOutputRow);
+
+ const out = {
+ window,
+ tokens,
+ count: tokens.length,
+ ts: new Date(nowMs).toISOString(),
+ sources,
+ };
+ if (!sources.length) {
+ out.note = 'All upstream market sources were unavailable — returning an empty ranking. Retry shortly.';
+ } 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(', ')}.`;
+ }
+ return out;
+}
diff --git a/api/_lib/gmgn-feed.js b/api/_lib/gmgn-feed.js
index 0179141a0..a360404fd 100644
--- a/api/_lib/gmgn-feed.js
+++ b/api/_lib/gmgn-feed.js
@@ -100,6 +100,20 @@ async function fetchDexScreener({ chain = 'sol' } = {}) {
}
}
+// Public, one-shot wrappers around the internal pollers' fetchers so other
+// server routes (e.g. the free /api/crypto/trending aggregator) can reuse the
+// exact same live sources — the DexScreener boosted-token board and the GMGN
+// smart-money rank — without opening a streaming poll. Both return the poller's
+// `{ ok, rank, source }` / `{ ok, status|error }` result verbatim and never
+// throw, so a caller can compose them and degrade gracefully when one is down.
+export function dexScreenerTrending(opts = {}) {
+ return fetchDexScreener(opts);
+}
+
+export function gmgnSmartMoneyRank(opts = {}) {
+ return fetchRank(opts);
+}
+
let _pollerId = 0;
// Map<pollerId, Map<address, prevItem>>
const _snapshots = new Map();
diff --git a/api/crypto/trending.js b/api/crypto/trending.js
new file mode 100644
index 000000000..40161673f
--- /dev/null
+++ b/api/crypto/trending.js
@@ -0,0 +1,54 @@
+// GET /api/crypto/trending
+// -------------------------
+// Free, keyless "what's hot right now" feed for AI agents. Returns Solana tokens
+// ranked by MOMENTUM — a blend of windowed trade volume, buy pressure, a volume
+// spike (anomaly) signal, and short-window price change — fused across pump.fun,
+// DexScreener's boosted board, and (best-effort) GMGN smart money.
+//
+// A discovery agent asks one URL instead of scraping five sites: it gets a
+// ranked list it can act on (surface, alert, position) without wiring up its own
+// scoring. The ranking signal is documented in api/_lib/crypto-trending.js and
+// docs/crypto-api.md.
+//
+// Query:
+// window = 5m | 1h | 24h (default 1h) — trade window the score measures
+// limit = 1..50 (default 20)
+// source = pumpfun | all (default all) — 'pumpfun' restricts to the
+// pump.fun board; 'all' fuses every source
+//
+// Response: { window, tokens: [{ mint, symbol, name, marketCapUsd, volumeUsd,
+// change, score, url }], count, ts, sources[] } — tokens ranked by score desc.
+//
+// Never 500s on a well-formed request: every source failing yields 200 with an
+// empty ranking + a note. Bad window/source/limit are coerced to sane defaults.
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { composeTrending, WINDOWS } from '../_lib/crypto-trending.js';
+
+const SOURCES = new Set(['pumpfun', 'all']);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const p = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const window = WINDOWS.has(p.get('window')) ? p.get('window') : '1h';
+ const source = SOURCES.has(p.get('source')) ? p.get('source') : 'all';
+ const rawLimit = Number(p.get('limit'));
+ const limit = Math.min(50, Math.max(1, Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 20));
+
+ const result = await composeTrending({ window, limit, source });
+
+ // A live, momentum-ranked feed shifts minute to minute but doesn't need
+ // sub-minute freshness; a short CDN cache absorbs bursts of agents polling the
+ // same window without hammering the pump.fun / DexScreener upstreams. An empty
+ // result (all sources down) is cached only briefly so we retry the live feeds soon.
+ const cache = result.count
+ ? 'public, max-age=30, s-maxage=30, stale-while-revalidate=30'
+ : 'public, max-age=5, s-maxage=5';
+ return json(res, 200, result, { 'cache-control': cache });
+});
diff --git a/tests/crypto-trending.test.js b/tests/crypto-trending.test.js
new file mode 100644
index 000000000..b07b62faa
--- /dev/null
+++ b/tests/crypto-trending.test.js
@@ -0,0 +1,259 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ windowToSec,
+ rankTokens,
+ mergeAndRank,
+ mapDexRow,
+ mapGmgnRow,
+ toOutputRow,
+ composeTrending,
+ WEIGHTS,
+ SPIKE_RATIO_CAP,
+} from '../api/_lib/crypto-trending.js';
+
+// Synthetic mints only — never a real third-party mint in fixtures (CLAUDE.md).
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const M2 = 'THREEsynthetic1111111111111111111111111111A';
+const M3 = 'THREEsynthetic2222222222222222222222222222B';
+
+describe('windowToSec', () => {
+ it('maps known windows', () => {
+ expect(windowToSec('5m')).toBe(300);
+ expect(windowToSec('1h')).toBe(3600);
+ expect(windowToSec('24h')).toBe(86400);
+ });
+ it('falls back to 1h for unknown/garbage', () => {
+ expect(windowToSec('bogus')).toBe(3600);
+ expect(windowToSec(undefined)).toBe(3600);
+ });
+});
+
+describe('rankTokens — ranking order', () => {
+ it('ranks higher combined momentum first and scores 0–100', () => {
+ const ranked = rankTokens([
+ { mint: M2, volumeUsd: 100, buyPressure: 0.5, changePct: 0 }, // low
+ { mint: THREE, volumeUsd: 1000, buyPressure: 0.9, changePct: 40 }, // high
+ { mint: M3, volumeUsd: 400, buyPressure: 0.6, changePct: 10 }, // mid
+ ]);
+ expect(ranked.map((t) => t.mint)).toEqual([THREE, M3, M2]);
+ for (const t of ranked) {
+ expect(t.score).toBeGreaterThanOrEqual(0);
+ expect(t.score).toBeLessThanOrEqual(100);
+ }
+ expect(ranked[0].score).toBeGreaterThan(ranked[2].score);
+ });
+
+ it('does not penalize a token missing buy pressure / change (present-weight renorm)', () => {
+ // Two tokens, identical volume-share leader, one with only volume present.
+ const ranked = rankTokens([
+ { mint: THREE, volumeUsd: 1000, buyPressure: null, changePct: null },
+ { mint: M2, volumeUsd: 10, buyPressure: 0.5, changePct: 0 },
+ ]);
+ const three = ranked.find((t) => t.mint === THREE);
+ // Volume-only leader: full volShare (1.0) + saturated spike → high score,
+ // scored purely on the features it has rather than dragged to zero.
+ expect(three.score).toBeGreaterThan(80);
+ });
+
+ it('returns [] for empty/invalid input', () => {
+ expect(rankTokens([])).toEqual([]);
+ expect(rankTokens(null)).toEqual([]);
+ });
+
+ it('buy pressure lifts an otherwise-tied token', () => {
+ const [a, b] = rankTokens([
+ { mint: THREE, volumeUsd: 500, buyPressure: 0.95, changePct: 0 },
+ { mint: M2, volumeUsd: 500, buyPressure: 0.2, changePct: 0 },
+ ]);
+ expect(a.mint).toBe(THREE);
+ expect(a.score).toBeGreaterThan(b.score);
+ });
+});
+
+describe('mergeAndRank — dedupe + limit cap', () => {
+ it('dedupes by mint keeping the higher score, regardless of set order', () => {
+ const setA = [{ mint: THREE, volumeUsd: 100, score: 40 }];
+ const setB = [{ mint: THREE, volumeUsd: 100, score: 90 }];
+ const merged = mergeAndRank([setA, setB], 10);
+ expect(merged).toHaveLength(1);
+ expect(merged[0].score).toBe(90);
+ });
+
+ it('caps output to the limit', () => {
+ const set = Array.from({ length: 60 }, (_, i) => ({
+ mint: `mint${i}`,
+ volumeUsd: i,
+ score: i,
+ }));
+ expect(mergeAndRank([set], 50)).toHaveLength(50);
+ expect(mergeAndRank([set], 5)).toHaveLength(5);
+ // Highest score first after the cap.
+ expect(mergeAndRank([set], 5)[0].score).toBe(59);
+ });
+
+ it('drops rows without a mint', () => {
+ const merged = mergeAndRank([[{ volumeUsd: 1, score: 99 }, { mint: THREE, score: 10 }]], 10);
+ expect(merged).toHaveLength(1);
+ expect(merged[0].mint).toBe(THREE);
+ });
+});
+
+describe('mapDexRow — window → change mapping + buy pressure', () => {
+ const row = {
+ address: THREE,
+ symbol: 'THREE',
+ name: 'three.ws',
+ market_cap: 412000,
+ volume: 18450,
+ price_change_1h: 5,
+ price_change_24h: 42,
+ txns_h1_buys: 75,
+ txns_h1_sells: 25,
+ };
+ it('uses 1h change for 5m/1h and 24h change for 24h', () => {
+ expect(mapDexRow(row, '1h').changePct).toBe(5);
+ expect(mapDexRow(row, '5m').changePct).toBe(5);
+ expect(mapDexRow(row, '24h').changePct).toBe(42);
+ });
+ it('derives buy pressure from h1 txn counts', () => {
+ expect(mapDexRow(row, '1h').buyPressure).toBeCloseTo(0.75);
+ });
+ it('null buy pressure when no txn flow', () => {
+ expect(mapDexRow({ ...row, txns_h1_buys: null, txns_h1_sells: null }, '1h').buyPressure).toBeNull();
+ });
+});
+
+describe('mapGmgnRow — guarded parsing', () => {
+ it('rejects rows without a valid address', () => {
+ expect(mapGmgnRow({ symbol: 'X' }, '1h')).toBeNull();
+ expect(mapGmgnRow({ address: 'short' }, '1h')).toBeNull();
+ });
+ it('maps smart-money buy/sell into buy pressure', () => {
+ const t = mapGmgnRow({ address: M2, symbol: 'S', smart_buy_24h: 8, smart_sell_24h: 2 }, '1h');
+ expect(t.mint).toBe(M2);
+ expect(t.buyPressure).toBeCloseTo(0.8);
+ });
+});
+
+describe('toOutputRow — public shape', () => {
+ it('emits exactly the documented fields, nulling missing ones', () => {
+ const row = toOutputRow({ mint: THREE, score: 50, volumeUsd: 10 });
+ expect(row).toEqual({
+ mint: THREE,
+ symbol: null,
+ name: null,
+ marketCapUsd: null,
+ volumeUsd: 10,
+ change: null,
+ score: 50,
+ url: null,
+ });
+ });
+});
+
+describe('composeTrending — source filter, states', () => {
+ const pumpRows = [{ mint: THREE, symbol: 'THREE', volumeUsd: 1000, score: 90, changePct: 5 }];
+ const dexRows = [{ mint: M2, symbol: 'DEX', volumeUsd: 500, score: 70, changePct: 2 }];
+ const gmgnRows = [{ mint: M3, symbol: 'GM', volumeUsd: 200, score: 40, changePct: 1 }];
+
+ it("source='pumpfun' only calls pump.fun", async () => {
+ let dexCalled = false;
+ const out = await composeTrending({
+ window: '1h',
+ limit: 20,
+ source: 'pumpfun',
+ nowMs: 1_750_000_000_000,
+ deps: {
+ pumpfun: async () => pumpRows,
+ dexscreener: async () => {
+ dexCalled = true;
+ return dexRows;
+ },
+ gmgn: async () => gmgnRows,
+ },
+ });
+ expect(dexCalled).toBe(false);
+ expect(out.sources).toEqual(['pumpfun']);
+ expect(out.tokens.map((t) => t.mint)).toEqual([THREE]);
+ expect(out.count).toBe(1);
+ expect(out.window).toBe('1h');
+ });
+
+ it("source='all' fuses every contributing source, ranked desc", async () => {
+ const out = await composeTrending({
+ window: '1h',
+ limit: 20,
+ source: 'all',
+ nowMs: 1_750_000_000_000,
+ deps: {
+ pumpfun: async () => pumpRows,
+ dexscreener: async () => dexRows,
+ gmgn: async () => gmgnRows,
+ },
+ });
+ expect(out.sources.sort()).toEqual(['dexscreener', 'gmgn', 'pumpfun']);
+ expect(out.tokens.map((t) => t.score)).toEqual([90, 70, 40]);
+ });
+
+ it('respects the limit cap after merge', async () => {
+ const out = await composeTrending({
+ window: '1h',
+ limit: 2,
+ source: 'all',
+ nowMs: 1_750_000_000_000,
+ deps: {
+ pumpfun: async () => pumpRows,
+ dexscreener: async () => dexRows,
+ gmgn: async () => gmgnRows,
+ },
+ });
+ expect(out.tokens).toHaveLength(2);
+ expect(out.tokens.map((t) => t.mint)).toEqual([THREE, M2]);
+ });
+
+ it('all sources down → 200-shaped empty result with a note, never throws', async () => {
+ const out = await composeTrending({
+ window: '1h',
+ limit: 20,
+ source: 'all',
+ nowMs: 1_750_000_000_000,
+ deps: {
+ pumpfun: async () => [],
+ dexscreener: async () => {
+ throw new Error('dex down');
+ },
+ gmgn: async () => [],
+ },
+ });
+ expect(out.count).toBe(0);
+ expect(out.tokens).toEqual([]);
+ expect(out.sources).toEqual([]);
+ expect(out.note).toMatch(/unavailable/i);
+ });
+
+ it('partial data notes which source was down', async () => {
+ const out = await composeTrending({
+ window: '24h',
+ limit: 20,
+ source: 'all',
+ nowMs: 1_750_000_000_000,
+ deps: {
+ pumpfun: async () => pumpRows,
+ dexscreener: async () => [],
+ gmgn: async () => [],
+ },
+ });
+ expect(out.sources).toEqual(['pumpfun']);
+ expect(out.note).toMatch(/dexscreener/);
+ expect(out.note).toMatch(/gmgn/);
+ });
+});
+
+describe('ranking weights are a coherent unit split', () => {
+ it('weights sum to 1', () => {
+ const sum = WEIGHTS.volume + WEIGHTS.buyDom + WEIGHTS.spike + WEIGHTS.change;
+ expect(sum).toBeCloseTo(1);
+ expect(SPIKE_RATIO_CAP).toBeGreaterThan(0);
+ });
+});