Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(coin-api): decide cohort access before spending a Helius call, and stop faking a week-over-week Fear and Greed delta
nirholasa64d91bb47ba
diff --git a/api/coin/README.md b/api/coin/README.mdindex 7cce8d480..e03163f3d 100644--- a/api/coin/README.md+++ b/api/coin/README.md@@ -31,7 +31,13 @@ All endpoints are `GET`, CORS-open, and rate-limited per client IP via [`../_lib| `GET /api/coin/gas` | /gas Ethereum fee tiers with USD estimates | On-chain `eth_feeHistory` via public RPC, no gas API || `GET /api/coin/rates` | /converter fiat rates | CoinGecko `/exchange_rates` || `GET /api/coin/liquidations` | /coins liquidations pulse strip | [`services/liquidation-collector`](../../services/liquidation-collector/README.md) |-| `GET /api/coin/:mint/cohorts[?cohort&…]` | Holder cohorts for one agent token (creator-gated export) | Platform DB, see [`[mint]/cohorts.js`](./%5Bmint%5D/cohorts.js) |+| `GET /api/coin/:mint/cohorts[?cohort&…]` | Holder cohorts for one launched coin or agent token (creator-gated export) | Platform DB snapshot, or a live Helius holder set for agent tokens, see [`[mint]/cohorts.js`](./%5Bmint%5D/cohorts.js) |++### Two contracts worth knowing before you call them++**`/api/coin/fear-greed`** returns `current`, `previous_week`, and the full `history` (oldest first). `previous_week` is the reading exactly seven days before `current`, so it is `null` whenever the requested `limit` is too small to contain one (`limit=7` or less). It is never the oldest point standing in for a week: a client that renders a delta must handle `null` by omitting it, as [`src/fear-greed.js`](../../src/fear-greed.js) does.++**`/api/coin/:mint/cohorts`** has two shapes on one route. Without `?cohort`, it is public: cohort definitions with live counts, cacheable at the CDN. With `?cohort=<id>`, it is a member export restricted to the coin's creator (or an admin), and it answers in this order, before any holder data is fetched: `404` for an unknown cohort id, `401` when signed out, `403` when the caller is not the creator, and `422` for a tenure cohort on an agent token that has not accrued holder history yet. Only after all four pass does it read the holder set, which can itself answer `503 holders_unavailable` when Helius is unreachable. Every shape shares one per-IP limiter (`limits.cohortsIp`).Frontend consumers live in `src/`: `coins-index.js`, `coin-page.js`, `markets-page.js`, `markets-trending.js`, `categories.js`, `category-page.js`, `exchanges.js`, `exchange-page.js`, `derivatives.js`, `fear-greed.js`, `gas.js`, `converter.js`, plus the Markets tools `heatmap.js`, `screener.js`, and `compare.js`. The public pages are declared in [`data/pages.json`](../../data/pages.json) (/coins, /heatmap, /screener, /compare, /categories, /exchanges, /derivatives, /fear-greed, /gas, /converter, /markets/trending).diff --git a/api/coin/[mint]/cohorts.js b/api/coin/[mint]/cohorts.jsindex 38d9dd995..0576f9f98 100644--- a/api/coin/[mint]/cohorts.js+++ b/api/coin/[mint]/cohorts.js@@ -13,7 +13,7 @@// stay open so any surface can render the segmentation UI.import { sql } from '../../_lib/db.js';-import { cors, json, error, method, wrap } from '../../_lib/http.js';+import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';import { isValidSolanaAddress } from '../../_lib/validate.js';import { getSessionUser } from '../../_lib/auth.js';import { limits, clientIp } from '../../_lib/rate-limit.js';@@ -89,9 +89,6 @@ function ownsAgentToken(user, agentToken) {// Tenure cohorts (diamond-hands / new-buyers / exited) report null / 422 —// they need holder history this token has not accrued yet.async function serveLiveCohorts(req, res, { mint, agentToken }) {- const rl = await limits.cohortsIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-const url = new URL(req.url, 'http://localhost');const cohortId = url.searchParams.get('cohort');const params = {@@ -105,6 +102,30 @@ async function serveLiveCohorts(req, res, { mint, agentToken }) {const network = token.cluster === 'devnet' ? 'devnet' : 'mainnet';const coinInfo = { mint, symbol: token.symbol || null, name: token.name || null };+ // Everything the export path can reject on its own is decided BEFORE the+ // holder set is fetched. That fetch costs a Helius call and can fail with a+ // 503 of its own, which used to swallow the real answer: an anonymous caller+ // asking for a bogus cohort got "holder data is temporarily unavailable"+ // instead of 404 or 401, and every such request still spent an upstream call.+ if (cohortId) {+ if (!isCohortId(cohortId)) {+ return error(res, 404, 'not_found', `unknown cohort: ${cohortId}`);+ }+ const user = await getSessionUser(req, res).catch(() => null);+ if (!user) return error(res, 401, 'unauthenticated', 'sign in to export cohort members');+ if (!ownsAgentToken(user, agentToken)) {+ return error(res, 403, 'forbidden', 'only the token creator can export holder cohorts');+ }+ if (!isLiveCohort(cohortId)) {+ return error(+ res,+ 422,+ 'snapshot_required',+ `the "${cohortId}" cohort needs holder history, which this token has not accrued yet`,+ );+ }+ }+let set;try {set = await liveHolderSet({ mint, network });@@ -131,24 +152,7 @@ async function serveLiveCohorts(req, res, { mint, agentToken }) {});}- // ── Member export: token creator only ────────────────────────────────────- if (!isCohortId(cohortId)) {- return error(res, 404, 'not_found', `unknown cohort: ${cohortId}`);- }- const user = await getSessionUser(req, res).catch(() => null);- if (!user) return error(res, 401, 'unauthenticated', 'sign in to export cohort members');- if (!ownsAgentToken(user, agentToken)) {- return error(res, 403, 'forbidden', 'only the token creator can export holder cohorts');- }- if (!isLiveCohort(cohortId)) {- return error(- res,- 422,- 'snapshot_required',- `the "${cohortId}" cohort needs holder history, which this token has not accrued yet`,- );- }-+ // ── Member export: the creator gate above already passed ─────────────const limit = numParam(url, 'limit') ?? 200;const sampleRaw = numParam(url, 'sample');const sample = sampleRaw != null && sampleRaw > 0 && sampleRaw < 1 ? sampleRaw : undefined;@@ -177,9 +181,15 @@ async function serveLiveCohorts(req, res, { mint, agentToken }) {}export default wrap(async (req, res) => {- if (cors(req, res)) return;+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;+ // One limiter for every shape. It used to guard only the live (Helius) path,+ // so the snapshot overview and the snapshot member export, both of which run+ // unbounded DB work, were reachable at any rate.+ const rl = await limits.cohortsIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const mint = mintFromReq(req);if (!mint || !isValidSolanaAddress(mint)) {return error(res, 400, 'bad_request', 'a valid token mint is required');@@ -208,6 +218,7 @@ export default wrap(async (req, res) => {// ── Overview: definitions + counts (public) ──────────────────────────────if (!cohortId) {const counts = await cohortCounts({ coinId: coin.id, params });+ res.setHeader('Cache-Control', OVERVIEW_CACHE);return json(res, 200, {coin: { mint: coin.mint, symbol: coin.symbol, name: coin.name },lastSnapshotAt: coin.last_snapshot_at || null,diff --git a/api/coin/fear-greed.js b/api/coin/fear-greed.jsindex 4399876c3..d580b4bec 100644--- a/api/coin/fear-greed.js+++ b/api/coin/fear-greed.js@@ -53,8 +53,12 @@ async function fetchFng(limit) {if (!history.length) throw new Error('empty fng payload');const latest = history[history.length - 1];- // A 7-day-ago comparison point powers the "vs last week" delta.- const weekAgo = history.length > 7 ? history[Math.max(0, history.length - 8)] : history[0];+ // A 7-day-ago comparison point powers the "vs last week" delta. Only a real+ // week back qualifies: a short window used to fall back to history[0], so+ // `?limit=1` reported the current reading as its own previous week and the+ // page rendered "Unchanged from last week" from a single data point. With no+ // week-old point the field is null and the client omits the delta.+ const weekAgo = history.length > 7 ? history[history.length - 8] : null;const value = {current: { value: latest.value, label: latest.label, ts: latest.ts },previous_week: weekAgodiff --git a/api/coin/gas.js b/api/coin/gas.jsindex 28c550593..19b4431e2 100644--- a/api/coin/gas.js+++ b/api/coin/gas.js@@ -35,11 +35,14 @@ const TTL_MS = 15_000;const hexToNum = (h) => (typeof h === 'string' ? parseInt(h, 16) : Number(h));const weiToGwei = (wei) => wei / 1e9;-async function rpc(url, method, params) {+// `rpcMethod`, not `method`: the module already imports a `method()` request+// guard from ../_lib/http.js, and a parameter of that name shadows it inside+// this function.+async function rpc(url, rpcMethod, params) {const resp = await fetch(url, {method: 'POST',headers: { 'content-type': 'application/json', accept: 'application/json' },- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: rpcMethod, params }),signal: AbortSignal.timeout(6000),});if (!resp.ok) throw new Error(`rpc ${resp.status}`);diff --git a/prompts/swarm-100/api-coin-01.md b/prompts/swarm-100/api-coin-01.mddeleted file mode 100644index 21a7c9b3f..000000000--- a/prompts/swarm-100/api-coin-01.md+++ /dev/null@@ -1,110 +0,0 @@-# API audit: api/coin batch 01 (10 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/coin/[mint]/cohorts.js-- api/coin/categories.js-- api/coin/category.js-- api/coin/derivatives.js-- api/coin/detail.js-- api/coin/exchange.js-- api/coin/exchanges.js-- api/coin/fear-greed.js-- api/coin/gas.js-- api/coin/global.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-coin-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/tests/api/coin-cohorts-gate.test.js b/tests/api/coin-cohorts-gate.test.jsnew file mode 100644index 000000000..27683ccfa--- /dev/null+++ b/tests/api/coin-cohorts-gate.test.js@@ -0,0 +1,198 @@+// GET /api/coin/:mint/cohorts: the authorization and cost-ordering contract.+//+// The live (agent-token) branch fetches the holder set from Helius. That call+// costs an upstream request and can fail 503 on its own, so every rejection the+// handler can decide by itself must happen FIRST. It used to happen last, with+// two consequences: an anonymous caller asking for a bogus cohort got+// "holder data is temporarily unavailable" instead of 404/401, and any+// unauthenticated request could make the platform spend a Helius call.+//+// The same tests pin the surrounding guards: the IP limiter covers every shape+// (it once guarded only the live branch, leaving the snapshot DB reads+// unbounded), and CORS advertises exactly the one method the handler accepts.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));++const cohortsIp = vi.fn(async () => ({ success: true }));+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { cohortsIp: (...a) => cohortsIp(...a) },+ clientIp: () => '203.0.113.9',+}));++const sql = vi.fn(async () => []);+vi.mock('../../api/_lib/db.js', () => ({+ sql: (...a) => sql(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));++const getSessionUser = vi.fn(async () => null);+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: (...a) => getSessionUser(...a) }));++const loadCoinByMint = vi.fn(async () => null);+const liveHolderSet = vi.fn();+const cohortCounts = vi.fn(async () => ({ holders: 3 }));+vi.mock('../../api/_lib/coin/index.js', () => ({+ loadCoinByMint: (...a) => loadCoinByMint(...a),+ listCohorts: () => [{ id: 'holders', name: 'All holders' }, { id: 'whales', name: 'Whales' }],+ isCohortId: (id) => ['holders', 'whales', 'diamond-hands'].includes(id),+ cohortCounts: (...a) => cohortCounts(...a),+ queryCohort: async () => ({ members: [], nextCursor: null, sampled: false }),+ isLiveCohort: (id) => id !== 'diamond-hands',+ liveHolderSet: (...a) => liveHolderSet(...a),+ liveCohortCounts: () => ({ holderCount: 3, counts: { holders: 3 }, concentration: { top1Share: 1 } }),+ liveCohortMembers: () => ({ members: ['A'], sampled: false, total: 1, truncated: false }),+}));++const MINT = 'AXsKDdVquPPm8c4vc65Ycw1yMvZFMSXc5DHDz56HNmjp';+const AGENT_TOKEN_ROW = { id: 7, user_id: 42, token: { symbol: 'AA', name: 'a' } };++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; },+ };+}++const handler = (await import('../../api/coin/[mint]/cohorts.js')).default;++async function call(query = '', { httpMethod = 'GET', mint = MINT } = {}) {+ const res = makeRes();+ await handler({ url: `/api/coin/${mint}/cohorts${query}`, method: httpMethod, headers: {}, query: { mint } }, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++/** The mint resolves to an agent token (no coin_launches row) → the live branch. */+function asAgentToken() {+ loadCoinByMint.mockResolvedValue(null);+ sql.mockResolvedValue([AGENT_TOKEN_ROW]);+}++beforeEach(() => {+ cohortsIp.mockReset().mockResolvedValue({ success: true });+ sql.mockReset().mockResolvedValue([]);+ getSessionUser.mockReset().mockResolvedValue(null);+ loadCoinByMint.mockReset().mockResolvedValue(null);+ liveHolderSet.mockReset().mockResolvedValue({ stale: false });+ cohortCounts.mockReset().mockResolvedValue({ holders: 3 });+});++describe('/api/coin/:mint/cohorts guards', () => {+ it('rejects a mint that is not a Solana address before touching the database', async () => {+ const { res, body } = await call('', { mint: 'notavalidmint' });+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_request');+ expect(loadCoinByMint).not.toHaveBeenCalled();+ });++ it('advertises only the method it accepts', async () => {+ const res = makeRes();+ await handler({ url: `/api/coin/${MINT}/cohorts`, method: 'OPTIONS', headers: {}, query: { mint: MINT } }, res);+ expect(res.statusCode).toBe(204);+ expect(res.getHeader('access-control-allow-methods')).toBe('GET,OPTIONS');+ });++ it('rate-limits the snapshot path, not only the live one', async () => {+ cohortsIp.mockResolvedValue({ success: false, limit: 45, remaining: 0, reset: Date.now() + 1000 });+ loadCoinByMint.mockResolvedValue({ id: 1, mint: MINT, symbol: 'AA', name: 'a' });+ const { res, body } = await call();+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ expect(loadCoinByMint).not.toHaveBeenCalled();+ });++ it('404s a mint that is neither a launch nor an agent token', async () => {+ const { res, body } = await call();+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ });+});++describe('/api/coin/:mint/cohorts live branch ordering', () => {+ it('404s an unknown cohort id without spending a Helius call', async () => {+ asAgentToken();+ const { res, body } = await call('?cohort=bogus');+ expect(res.statusCode).toBe(404);+ expect(body.error_description).toBe('unknown cohort: bogus');+ expect(liveHolderSet).not.toHaveBeenCalled();+ });++ it('401s an anonymous member export without spending a Helius call', async () => {+ asAgentToken();+ const { res, body } = await call('?cohort=whales');+ expect(res.statusCode).toBe(401);+ expect(body.error).toBe('unauthenticated');+ expect(liveHolderSet).not.toHaveBeenCalled();+ });++ it('403s a signed-in caller who does not own the token, still without the call', async () => {+ asAgentToken();+ getSessionUser.mockResolvedValue({ id: 999, is_admin: false });+ const { res, body } = await call('?cohort=whales');+ expect(res.statusCode).toBe(403);+ expect(body.error).toBe('forbidden');+ expect(liveHolderSet).not.toHaveBeenCalled();+ });++ it('422s a tenure cohort this token has no history for, still without the call', async () => {+ asAgentToken();+ getSessionUser.mockResolvedValue({ id: 42, is_admin: false });+ const { res, body } = await call('?cohort=diamond-hands');+ expect(res.statusCode).toBe(422);+ expect(body.error).toBe('snapshot_required');+ expect(liveHolderSet).not.toHaveBeenCalled();+ });++ it('exports members for the token creator', async () => {+ asAgentToken();+ getSessionUser.mockResolvedValue({ id: 42, is_admin: false });+ const { res, body } = await call('?cohort=whales');+ expect(res.statusCode).toBe(200);+ expect(liveHolderSet).toHaveBeenCalledTimes(1);+ expect(body).toMatchObject({ cohort: 'whales', count: 1, members: ['A'], source: 'live' });+ });++ it('serves public counts with a CDN cache header and no auth', async () => {+ asAgentToken();+ const { res, body } = await call();+ expect(res.statusCode).toBe(200);+ expect(body.holderCount).toBe(3);+ expect(res.getHeader('cache-control')).toContain('s-maxage=120');+ expect(getSessionUser).not.toHaveBeenCalled();+ });++ it('reports a Helius outage as a typed 503 that never echoes the upstream message', async () => {+ asAgentToken();+ liveHolderSet.mockRejectedValue(new Error('403 https://mainnet.helius-rpc.com/?api-key=secret'));+ const { res, body } = await call();+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('holders_unavailable');+ expect(JSON.stringify(body)).not.toContain('api-key');+ });+});++describe('/api/coin/:mint/cohorts snapshot branch', () => {+ it('serves cacheable public counts for a launched coin', async () => {+ loadCoinByMint.mockResolvedValue({ id: 1, mint: MINT, symbol: 'AA', name: 'a', last_snapshot_at: null });+ const { res, body } = await call();+ expect(res.statusCode).toBe(200);+ expect(res.getHeader('cache-control')).toContain('s-maxage=120');+ expect(body.cohorts.find((c) => c.id === 'holders').count).toBe(3);+ // Counts absent upstream render as 0 on the snapshot path, not null.+ expect(body.cohorts.find((c) => c.id === 'whales').count).toBe(0);+ });++ it('401s an anonymous member export', async () => {+ loadCoinByMint.mockResolvedValue({ id: 1, mint: MINT, symbol: 'AA', name: 'a' });+ const { res, body } = await call('?cohort=whales');+ expect(res.statusCode).toBe(401);+ expect(body.error).toBe('unauthenticated');+ });+});diff --git a/tests/api/coin-market-endpoints.test.js b/tests/api/coin-market-endpoints.test.jsnew file mode 100644index 000000000..743fc387d--- /dev/null+++ b/tests/api/coin-market-endpoints.test.js@@ -0,0 +1,427 @@+// Contract tests for the /api/coin/* market read endpoints.+//+// These eight handlers all sit in front of a rate-limited third-party upstream+// (CoinGecko keyless, alternative.me, public Ethereum RPCs). What matters is+// not the happy path alone but what a caller sees when an upstream is throttled+// or half-answers: a typed 4xx/5xx JSON envelope, never a stack trace, never a+// partially-shaped body, and never a 502 when a working fallback exists.+//+// Each load() resets the module registry first, because every one of these+// handlers keeps a per-instance memory cache: without it a success case would+// serve the following failure case its cached payload and the test would pass+// for the wrong reason.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { marketDataIp: async () => ({ success: true }) },+ clientIp: () => '203.0.113.7',+}));++const geckoFetch = vi.fn();+vi.mock('../../api/_lib/coingecko.js', () => ({+ geckoFetch: (...a) => geckoFetch(...a),+ isPlausibleCoinId: (id) => /^[a-z0-9][a-z0-9_-]*$/.test(id),+ htmlToText: (s) => String(s || '').replace(/<[^>]+>/g, '').trim(),+ COINGECKO_BASE: 'https://api.coingecko.com/api/v3',+}));++const fetchGlobalMarket = vi.fn();+const fetchCoinPriceUsd = vi.fn();+const fetchCoinPriceUsdOrNull = vi.fn();+vi.mock('../../api/_lib/market-fallbacks.js', () => ({+ fetchGlobalMarket: (...a) => fetchGlobalMarket(...a),+ fetchCoinPriceUsd: (...a) => fetchCoinPriceUsd(...a),+ fetchCoinPriceUsdOrNull: (...a) => fetchCoinPriceUsdOrNull(...a),+}));++const fetchHyperliquidPerps = vi.fn();+vi.mock('../../api/_lib/hyperliquid.js', () => ({+ fetchHyperliquidPerps: (...a) => fetchHyperliquidPerps(...a),+}));++const fetchDeribitSummary = vi.fn();+vi.mock('../../api/_lib/deribit.js', () => ({+ fetchDeribitSummary: (...a) => fetchDeribitSummary(...a),+}));++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; },+ };+}++/** Fresh handler instance (empties the module's in-process cache). */+async function load(path) {+ vi.resetModules();+ return (await import(path)).default;+}++async function call(handler, url, httpMethod = 'GET') {+ const res = makeRes();+ await handler({ url, method: httpMethod, headers: {} }, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++const upstream = (status) => {+ const err = new Error(`CoinGecko ${status}`);+ err.status = status;+ return err;+};++const CATEGORIES = [+ {+ id: 'layer-1',+ name: 'Layer 1 (L1)',+ market_cap: 1_500_000_000_000,+ market_cap_change_24h: -1.25,+ volume_24h: 70_000_000_000,+ top_3_coins: ['https://img/btc.png', 'https://img/eth.png', 'https://img/sol.png', 'https://img/bnb.png'],+ content: '<p>Layer 1 blockchains settle their own transactions.</p>',+ },+ {+ id: 'smart-contract-platform',+ name: 'Smart Contract Platform',+ market_cap: 900_000_000_000,+ market_cap_change_24h: 0.4,+ volume_24h: 40_000_000_000,+ top_3_coins: [],+ },+ {+ id: 'meme-token',+ name: 'Meme',+ market_cap: Number.NaN,+ market_cap_change_24h: null,+ volume_24h: 5_000_000_000,+ top_3_coins: null,+ },+];++beforeEach(() => {+ geckoFetch.mockReset();+ fetchGlobalMarket.mockReset();+ fetchCoinPriceUsd.mockReset();+ fetchCoinPriceUsdOrNull.mockReset();+ fetchHyperliquidPerps.mockReset();+ fetchDeribitSummary.mockReset();+});++describe('/api/coin/categories', () => {+ it('shapes the sector leaderboard and drops non-finite numbers', async () => {+ geckoFetch.mockResolvedValue(CATEGORIES);+ const { res, body } = await call(await load('../../api/coin/categories.js'), '/api/coin/categories');+ expect(res.statusCode).toBe(200);+ expect(body.categories).toHaveLength(3);+ expect(body.categories[0]).toMatchObject({ id: 'layer-1', market_cap: 1_500_000_000_000 });+ // NaN upstream must land as null, never as the string "NaN" in JSON.+ expect(body.categories[2].market_cap).toBeNull();+ // The avatar stack renders three icons; a longer upstream list is capped.+ expect(body.categories[0].top_3_coins).toHaveLength(3);+ expect(body.categories[2].top_3_coins).toEqual([]);+ expect(res.getHeader('cache-control')).toContain('s-maxage=600');+ });++ it('answers 502 with a typed envelope when the upstream is throttled', async () => {+ geckoFetch.mockRejectedValue(upstream(429));+ const { res, body } = await call(await load('../../api/coin/categories.js'), '/api/coin/categories');+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');+ expect(res.getHeader('cache-control')).toBe('no-store');+ });++ it('rejects a non-GET method', async () => {+ const { res, body } = await call(await load('../../api/coin/categories.js'), '/api/coin/categories', 'POST');+ expect(res.statusCode).toBe(405);+ expect(body.error).toBe('method_not_allowed');+ });+});++describe('/api/coin/category', () => {+ it('rejects an id that is not a slug', async () => {+ const { res, body } = await call(await load('../../api/coin/category.js'), '/api/coin/category?id=Layer%201!');+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_id');+ expect(geckoFetch).not.toHaveBeenCalled();+ });++ it('404s a slug the upstream does not list', async () => {+ geckoFetch.mockResolvedValue(CATEGORIES);+ const { res, body } = await call(await load('../../api/coin/category.js'), '/api/coin/category?id=no-such-sector');+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('derives rank, categorized share, and rank-nearest neighbours', async () => {+ geckoFetch.mockResolvedValue(CATEGORIES);+ const { res, body } = await call(+ await load('../../api/coin/category.js'),+ '/api/coin/category?id=smart-contract-platform',+ );+ expect(res.statusCode).toBe(200);+ expect(body.category.rank).toBe(2);+ // share is of the SUM of category market caps (1.5T + 0.9T), not of total crypto.+ expect(body.category.share_of_total).toBeCloseTo((900 / 2400) * 100, 6);+ expect(body.related.map((r) => r.id)).toEqual(['layer-1', 'meme-token']);+ });++ it('strips upstream HTML out of the description', async () => {+ geckoFetch.mockResolvedValue(CATEGORIES);+ const { body } = await call(await load('../../api/coin/category.js'), '/api/coin/category?id=layer-1');+ expect(body.category.description).toBe('Layer 1 blockchains settle their own transactions.');+ });+});++describe('/api/coin/global', () => {+ it('renders each half independently when the other upstream fails', async () => {+ fetchGlobalMarket.mockRejectedValue(new Error('all sources down'));+ globalThis.fetch = vi.fn(async () => ({+ ok: true,+ json: async () => ({ data: [{ value: '31', value_classification: 'Fear' }] }),+ }));+ const { res, body } = await call(await load('../../api/coin/global.js'), '/api/coin/global');+ expect(res.statusCode).toBe(200);+ expect(body.market).toBeNull();+ expect(body.fear_greed).toEqual({ value: 31, label: 'Fear' });+ });++ it('502s only when both halves fail', async () => {+ fetchGlobalMarket.mockRejectedValue(new Error('all sources down'));+ globalThis.fetch = vi.fn(async () => ({ ok: false, status: 503 }));+ const { res, body } = await call(await load('../../api/coin/global.js'), '/api/coin/global');+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');+ });+});++describe('/api/coin/exchanges', () => {+ const ROWS = [+ {+ id: 'binance',+ name: 'Binance',+ trade_volume_24h_btc: '120000',+ trust_score: 10,+ trust_score_rank: 1,+ url: 'https://www.binance.com',+ },+ {+ id: 'sketchy',+ name: 'Sketchy',+ trade_volume_24h_btc: 'n/a',+ trust_score: 1,+ trust_score_rank: 99,+ url: 'javascript:alert(1)',+ },+ ];++ it('converts BTC volume to USD with the live price', async () => {+ geckoFetch.mockResolvedValue(ROWS);+ fetchCoinPriceUsd.mockResolvedValue(60_000);+ const { res, body } = await call(await load('../../api/coin/exchanges.js'), '/api/coin/exchanges');+ expect(res.statusCode).toBe(200);+ expect(body.btc_usd).toBe(60_000);+ expect(body.exchanges[0].volume_24h_usd).toBe(120_000 * 60_000);+ // A non-numeric upstream volume must not become NaN in the JSON body.+ expect(body.exchanges[1].volume_24h_btc).toBeNull();+ expect(body.exchanges[1].volume_24h_usd).toBeNull();+ // Only http(s) links reach the client.+ expect(body.exchanges[1].url).toBeNull();+ });++ it('still serves the table when the price feed is down', async () => {+ geckoFetch.mockResolvedValue(ROWS);+ fetchCoinPriceUsd.mockRejectedValue(new Error('price sources down'));+ const { res, body } = await call(await load('../../api/coin/exchanges.js'), '/api/coin/exchanges');+ expect(res.statusCode).toBe(200);+ expect(body.btc_usd).toBeNull();+ expect(body.exchanges[0].volume_24h_btc).toBe(120_000);+ expect(body.exchanges[0].volume_24h_usd).toBeNull();+ });++ it('502s when the exchange list itself is unavailable', async () => {+ geckoFetch.mockRejectedValue(upstream(429));+ fetchCoinPriceUsd.mockResolvedValue(60_000);+ const { res, body } = await call(await load('../../api/coin/exchanges.js'), '/api/coin/exchanges');+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');+ });+});++describe('/api/coin/derivatives', () => {+ it('falls back to Hyperliquid when CoinGecko is throttled', async () => {+ geckoFetch.mockRejectedValue(upstream(429));+ fetchDeribitSummary.mockResolvedValue(null);+ fetchHyperliquidPerps.mockResolvedValue([+ { market: 'Hyperliquid', symbol: 'BTC-USD', price: 64_093, funding_rate: 0.01, open_interest: 1, volume_24h: 2 },+ ]);+ const { res, body } = await call(await load('../../api/coin/derivatives.js'), '/api/coin/derivatives');+ expect(res.statusCode).toBe(200);+ expect(body.source).toBe('hyperliquid');+ expect(body.tickers[0].symbol).toBe('BTC-USD');+ });++ it('keeps only perpetuals and sorts them by 24h volume', async () => {+ geckoFetch.mockResolvedValue([+ { market: 'A', symbol: 'ETH', contract_type: 'perpetual', price: 1, volume_24h: 10 },+ { market: 'B', symbol: 'BTC', contract_type: 'perpetual', price: 2, volume_24h: 99 },+ { market: 'C', symbol: 'BTC-DEC', contract_type: 'futures', price: 3, volume_24h: 500 },+ ]);+ fetchDeribitSummary.mockResolvedValue(null);+ const { body } = await call(await load('../../api/coin/derivatives.js'), '/api/coin/derivatives');+ expect(body.source).toBe('coingecko');+ expect(body.tickers.map((t) => t.symbol)).toEqual(['BTC', 'ETH']);+ });++ it('502s the exchanges view on an empty upstream payload', async () => {+ geckoFetch.mockResolvedValue([]);+ const { res, body } = await call(+ await load('../../api/coin/derivatives.js'),+ '/api/coin/derivatives?view=exchanges',+ );+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');+ });+});++describe('/api/coin/exchange', () => {+ it('rejects an id outside the slug charset', async () => {+ const { res, body } = await call(await load('../../api/coin/exchange.js'), '/api/coin/exchange?id=%21%21bad');+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_id');+ });++ it('serves the spot profile with the normalized volume from the ranked list', async () => {+ fetchCoinPriceUsdOrNull.mockResolvedValue(60_000);+ geckoFetch.mockImplementation(async (path) => {+ if (path === '/exchanges/binance') {+ return {+ name: 'Binance',+ description: '<p>An exchange.</p>',+ url: 'https://www.binance.com',+ trade_volume_24h_btc: 120_000,+ tickers: [+ {+ base: '0x1234567890abcdef1234567890abcdef12345678',+ target: 'USDT',+ converted_last: { usd: 1 },+ converted_volume: { usd: 2 },+ },+ ],+ };+ }+ if (path.startsWith('/exchanges/binance/volume_chart')) return [[1_700_000_000_000, '13421.89']];+ if (path.startsWith('/exchanges?')) return [{ id: 'binance', trade_volume_24h_btc_normalized: 99_000 }];+ throw upstream(404);+ });+ const { res, body } = await call(await load('../../api/coin/exchange.js'), '/api/coin/exchange?id=binance');+ expect(res.statusCode).toBe(200);+ expect(body.detail.type).toBe('spot');+ expect(body.detail.trade_volume_24h_btc_normalized).toBe(99_000);+ expect(body.detail.description).toBe('An exchange.');+ // A contract-address base symbol is truncated, not dumped into the pair cell.+ expect(body.detail.tickers[0].pair).toBe('0x1234…5678/USDT');+ expect(body.volume_chart).toEqual([[1_700_000_000_000, 13_421.89]]);+ });++ it('falls back to the derivatives namespace when the spot lookup 404s', async () => {+ fetchCoinPriceUsdOrNull.mockResolvedValue(60_000);+ geckoFetch.mockImplementation(async (path) => {+ if (path.startsWith('/derivatives/exchanges/')) {+ return { name: 'Deriv Venue', open_interest_btc: '4200', number_of_perpetual_pairs: 120, tickers: [] };+ }+ throw upstream(404);+ });+ const { res, body } = await call(await load('../../api/coin/exchange.js'), '/api/coin/exchange?id=deriv-venue');+ expect(res.statusCode).toBe(200);+ expect(body.detail.type).toBe('derivatives');+ expect(body.detail.open_interest_btc).toBe(4200);+ expect(body.volume_chart).toBeNull();+ });++ it('404s when neither namespace knows the id', async () => {+ fetchCoinPriceUsdOrNull.mockResolvedValue(null);+ geckoFetch.mockRejectedValue(upstream(404));+ const { res, body } = await call(await load('../../api/coin/exchange.js'), '/api/coin/exchange?id=ghost-venue');+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ });+});++describe('/api/coin/fear-greed', () => {+ const fngRows = (n) =>+ Array.from({ length: n }, (_, i) => ({+ value: String(30 + i),+ value_classification: 'Fear',+ timestamp: String(1_700_000_000 + i * 86_400),+ }));++ it('reports a week-over-week comparison point once a week of history exists', async () => {+ globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => ({ data: fngRows(30) }) }));+ const { res, body } = await call(await load('../../api/coin/fear-greed.js'), '/api/coin/fear-greed?limit=30');+ expect(res.statusCode).toBe(200);+ expect(body.history).toHaveLength(30);+ // History is returned oldest-first even though alternative.me sends newest-first.+ expect(body.history[0].ts).toBeLessThan(body.history[29].ts);+ expect(body.current.value).toBe(59);+ // Exactly 7 days back, not "the oldest point we happen to have".+ expect(body.previous_week.ts).toBe(body.current.ts - 7 * 86_400_000);+ });++ it('reports no previous week rather than comparing the latest reading to itself', async () => {+ globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => ({ data: fngRows(1) }) }));+ const { res, body } = await call(await load('../../api/coin/fear-greed.js'), '/api/coin/fear-greed?limit=1');+ expect(res.statusCode).toBe(200);+ expect(body.previous_week).toBeNull();+ });++ it('502s when alternative.me is unavailable', async () => {+ globalThis.fetch = vi.fn(async () => ({ ok: false, status: 503 }));+ const { res, body } = await call(await load('../../api/coin/fear-greed.js'), '/api/coin/fear-greed');+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');+ });+});++describe('/api/coin/gas', () => {+ const feeHistory = {+ baseFeePerGas: ['0x3b9aca00', '0x77359400'], // 1 gwei, then 2 gwei pending+ reward: [+ ['0x3b9aca00', '0x77359400', '0xb2d05e00'], // 1 / 2 / 3 gwei+ ['0x3b9aca00', '0x77359400', '0xb2d05e00'],+ ],+ };++ it('derives slow/standard/fast from eth_feeHistory and prices each action', async () => {+ globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => ({ result: feeHistory }) }));+ fetchCoinPriceUsd.mockResolvedValue(2000);+ const { res, body } = await call(await load('../../api/coin/gas.js'), '/api/coin/gas');+ expect(res.statusCode).toBe(200);+ expect(body.base_fee_gwei).toBe(2);+ expect(body.tiers.map((t) => t.key)).toEqual(['slow', 'standard', 'fast']);+ expect(body.tiers.map((t) => t.gas_price_gwei)).toEqual([3, 4, 5]);+ const transfer = body.tiers[0].actions.find((a) => a.key === 'transfer');+ expect(transfer.usd).toBeCloseTo(3 * 1e-9 * 21_000 * 2000, 12);+ });++ it('serves the oracle without USD costs when the price feed is down', async () => {+ globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => ({ result: feeHistory }) }));+ fetchCoinPriceUsd.mockRejectedValue(new Error('price sources down'));+ const { res, body } = await call(await load('../../api/coin/gas.js'), '/api/coin/gas');+ expect(res.statusCode).toBe(200);+ expect(body.eth_price_usd).toBeNull();+ expect(body.tiers[0].actions.every((a) => a.usd === null)).toBe(true);+ });++ it('502s when every RPC in the failover chain fails', async () => {+ globalThis.fetch = vi.fn(async () => ({ ok: false, status: 502 }));+ fetchCoinPriceUsd.mockResolvedValue(2000);+ const { res, body } = await call(await load('../../api/coin/gas.js'), '/api/coin/gas');+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');+ });+});