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(market-data): return a retryable 503 when a provider throttles us, not a 429
nirholas439830b9910c
diff --git a/api/_lib/market-data/fetch.js b/api/_lib/market-data/fetch.jsindex ca2d253a6..f6b73a532 100644--- a/api/_lib/market-data/fetch.js+++ b/api/_lib/market-data/fetch.js@@ -36,15 +36,26 @@ const fail = (status, code, message) => {const invalid = (code, message) => fail(422, code, message);+// Only these upstream statuses describe something the CALLER got wrong, and so+// are the only ones worth repeating back verbatim. Everything else is our+// problem to report as downtime. 429/401/403 matter most: api/_lib/coingecko.js+// rethrows the provider's status as-is, so passing them through told a paying+// buyer "you are rate limited" on an endpoint whose whole pitch is no per-IP+// rate limits, and leaked the provider name plus the internal upstream path in+// the error text.+const CALLER_FAULT_STATUSES = new Set([400, 404, 422]);+// Wrap an upstream call so an outage surfaces as a 503 the payment wrapper-// short-circuits BEFORE settling — a paid endpoint never charges for downtime.-// 4xx errors thrown by builders (unknown coin, unknown pool) pass through.+// short-circuits BEFORE settling: a paid endpoint never charges for downtime.+// Genuine caller faults thrown by builders (unknown coin, unknown pool) pass+// through; every other failure, throttles and upstream auth faults included,+// becomes the documented 503.async function upstream(label, fn) {try {return await fn();} catch (err) {- if (err?.status && err.status < 500) throw err;- fail(503, 'data_unavailable', `live ${label} data is temporarily unavailable — retry shortly`);+ if (CALLER_FAULT_STATUSES.has(err?.status)) throw err;+ fail(503, 'data_unavailable', `live ${label} data is temporarily unavailable, retry shortly`);}}@@ -180,9 +191,16 @@ export const MARKET_FETCHERS = {'market-stablecoins': () => upstream('stablecoin', () => buildStablecoins()),+ // A typo in ?type= must refuse rather than quietly serve the other dataset:+ // validation runs pre-settle, so a 422 is free, while a silent fallback to+ // 'fees' charges the buyer for data they did not ask for. Same contract as+ // market-derivatives' ?view=.'market-fees': async (params) => {- const type = params.get('type') === 'revenue' ? 'revenue' : 'fees';- return upstream('protocol fee', () => buildFees(type));+ const type = (params.get('type') || '').trim().toLowerCase();+ if (type && type !== 'fees' && type !== 'revenue') {+ invalid('invalid_type', "type must be 'fees' or 'revenue'");+ }+ return upstream('protocol fee', () => buildFees(type || 'fees'));},'market-dex-volumes': () => upstream('DEX volume', () => buildDexVolumes()),diff --git a/api/x402/market-categories.js b/api/x402/market-categories.jsindex 98fbb8eae..55e97247b 100644--- a/api/x402/market-categories.js+++ b/api/x402/market-categories.js@@ -1,4 +1,4 @@-// GET /api/x402/market-categories — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-categories: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-chains.js b/api/x402/market-chains.jsindex 4c1cf22e9..64da7c103 100644--- a/api/x402/market-chains.js+++ b/api/x402/market-chains.js@@ -1,4 +1,4 @@-// GET /api/x402/market-chains — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-chains: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-chart.js b/api/x402/market-chart.jsindex 5b027ffd6..053997ff5 100644--- a/api/x402/market-chart.js+++ b/api/x402/market-chart.js@@ -1,4 +1,4 @@-// GET /api/x402/market-chart — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-chart: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-coin.js b/api/x402/market-coin.jsindex 2c3d2e9a3..df0f7c2bc 100644--- a/api/x402/market-coin.js+++ b/api/x402/market-coin.js@@ -1,4 +1,4 @@-// GET /api/x402/market-coin — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-coin: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-coins.js b/api/x402/market-coins.jsindex f77554b45..70f2b661a 100644--- a/api/x402/market-coins.js+++ b/api/x402/market-coins.js@@ -1,4 +1,4 @@-// GET /api/x402/market-coins — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-coins: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-defi.js b/api/x402/market-defi.jsindex aa2eae4f7..484383a41 100644--- a/api/x402/market-defi.js+++ b/api/x402/market-defi.js@@ -1,4 +1,4 @@-// GET /api/x402/market-defi — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-defi: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-derivatives.js b/api/x402/market-derivatives.jsindex 4f8392c65..595d5c8f2 100644--- a/api/x402/market-derivatives.js+++ b/api/x402/market-derivatives.js@@ -1,4 +1,4 @@-// GET /api/x402/market-derivatives — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-derivatives: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-dex-volumes.js b/api/x402/market-dex-volumes.jsindex d09207b95..9dac287c8 100644--- a/api/x402/market-dex-volumes.js+++ b/api/x402/market-dex-volumes.js@@ -1,4 +1,4 @@-// GET /api/x402/market-dex-volumes — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-dex-volumes: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-exchanges.js b/api/x402/market-exchanges.jsindex 824b63d91..c62a15e20 100644--- a/api/x402/market-exchanges.js+++ b/api/x402/market-exchanges.js@@ -1,4 +1,4 @@-// GET /api/x402/market-exchanges — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-exchanges: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-fees.js b/api/x402/market-fees.jsindex 12d4bf70e..c03831ab6 100644--- a/api/x402/market-fees.js+++ b/api/x402/market-fees.js@@ -1,4 +1,4 @@-// GET /api/x402/market-fees — paid Market Data API (x402, USDC on Solana/Base).+// GET /api/x402/market-fees: paid Market Data API (x402, USDC on Solana/Base).// Thin route shell: the category registry + shared factory in// api/_lib/market-data/ define the price, discovery listing, and handler.import { marketEndpoint } from '../_lib/market-data/endpoint.js';diff --git a/api/x402/market-heatmap.js b/api/x402/market-heatmap.jsindex b9337531b..46562258a 100644--- a/api/x402/market-heatmap.js+++ b/api/x402/market-heatmap.js@@ -30,6 +30,16 @@ let _cache = null; // { coins, source, expiresAt }const finite = (n) => (Number.isFinite(n) ? n : null);+// Market-cap rank, or the row's board position when the upstream has none.+// CoinGecko sends `market_cap_rank: null` for coins it has not ranked, and+// Number(null) is 0, so a plain finite() check let a nonsense rank of 0 through+// instead of falling back. Ranks are 1-based; anything else takes the fallback.+// (The CoinPaprika branch already filters rank > 0, so both sources agree.)+export const rankOr = (raw, fallback) => {+ const n = Number(raw);+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;+};+async function fetchCoinGecko() {const url ='https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc' +@@ -42,7 +52,7 @@ async function fetchCoinGecko() {const raw = await r.json();if (!Array.isArray(raw) || !raw.length) throw new Error('coingecko empty');return raw.map((c, i) => ({- rank: finite(Number(c.market_cap_rank)) ?? i + 1,+ rank: rankOr(c.market_cap_rank, i + 1),symbol: typeof c.symbol === 'string' ? c.symbol.toUpperCase() : null,name: typeof c.name === 'string' ? c.name : null,price_usd: finite(Number(c.current_price)),@@ -106,7 +116,11 @@ async function loadBoard() {return _cache;}-function breadth(coins) {+// Market breadth over the board's 24h moves. A +/- 0.05% dead band keeps+// rounding noise out of the advancer/decliner split, and coins the upstream+// could not price (change_24h null) are excluded rather than counted as flat,+// so the three buckets always sum to the number of coins actually measured.+export function breadth(coins) {const moves = coins.map((c) => c.change_24h).filter((n) => n != null);const advancers = moves.filter((n) => n > 0.05).length;const decliners = moves.filter((n) => n < -0.05).length;diff --git a/api/x402/market.js b/api/x402/market.jsindex df9af4353..edccebcf5 100644--- a/api/x402/market.js+++ b/api/x402/market.js@@ -1,7 +1,9 @@// GET /api/x402/market — FREE front-door index for the paid Market Data API.//-// Lists every /api/x402/market-* category with its price, params, and a-// runnable example so an agent (or a human with curl) can discover the whole+// Lists every paid /api/x402/market-* endpoint (the registry family plus the+// hand-written siblings market-heatmap and market-mood) with its live price,+// params, and a runnable example so an agent (or a human with curl) can+// discover the whole// bundle in one unauthenticated call. The paid endpoints themselves are// x402-gated (USDC on Solana or Base); this index is free the same way// /api/crypto is free for the crypto bundle — discovery costs nothing,@@ -10,13 +12,80 @@import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';-import { MARKET_CATEGORIES, MARKET_SERVICE_NAME } from '../_lib/market-data/registry.js';+import { priceFor } from '../_lib/x402-prices.js';+import {+ MARKET_CATEGORIES,+ MARKET_CATEGORY_BY_SLUG,+ MARKET_SERVICE_NAME,+} from '../_lib/market-data/registry.js';+import { PAID_SERVICES } from '../_lib/service-catalog/services/index.js';+// USDC atomics to a display price. The decimal count is derived from the value+// so a sub-cent endpoint never renders as "$0": a fixed 3-decimal format turned+// $0.0005 into "$0.000" and then into "$0" once the trailing zeros were+// trimmed. Trailing zeros are still trimmed, but only inside the fraction.const usd = (atomics) => {const n = Number(atomics) / 1_000_000;- return `$${n.toFixed(n < 0.01 ? 3 : 2).replace(/0+$/, '').replace(/\.$/, '')}`;+ if (!Number.isFinite(n)) return null;+ const decimals = n > 0 ? Math.max(2, Math.min(6, Math.ceil(-Math.log10(n)) + 1)) : 2;+ return `$${n.toFixed(decimals).replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '')}`;};+// The index covers every paid /api/x402/market-* endpoint, not only the+// registry family. market-heatmap and market-mood are hand-written siblings+// with their own service-catalog descriptors, and an agent that discovers the+// bundle here has no other way to learn they exist. Both halves are derived+// (registry + catalog), so the next sibling shows up the day its descriptor+// lands rather than the day someone remembers to edit this file.+const SIBLING_SERVICES = PAID_SERVICES.filter(+ (s) =>+ s.status === 'live' &&+ !s.free &&+ typeof s.path === 'string' &&+ s.path.startsWith('/api/x402/market-') &&+ !MARKET_CATEGORY_BY_SLUG.has(s.slug),+);++const LISTED = [+ ...MARKET_CATEGORIES.map((c) => ({+ slug: c.slug,+ title: c.title,+ priceAtomics: c.priceAtomics,+ summary: c.useCase,+ properties: c.inputSchema.properties || {},+ example: c.inputExample,+ })),+ ...SIBLING_SERVICES.map((s) => ({+ slug: s.slug,+ title: s.title,+ priceAtomics: s.priceAtomics,+ summary: s.useCase,+ properties: s.inputSchema?.properties || {},+ example: s.input || {},+ })),+];++// Price through priceFor() rather than the declared default: the live endpoint+// resolves the same way, so an X402_PRICE_MARKET_* override moves the index and+// the 402 challenge together instead of leaving the free index quoting a price+// no longer charged.+function describeEndpoint(entry, origin) {+ const query = new URLSearchParams(+ Object.entries(entry.example || {}).map(([k, v]) => [k, String(v)]),+ ).toString();+ return {+ slug: entry.slug,+ title: entry.title,+ price_usdc: usd(priceFor(entry.slug, entry.priceAtomics)),+ url: `${origin}/api/x402/${entry.slug}`,+ summary: entry.summary,+ params: Object.fromEntries(+ Object.entries(entry.properties).map(([k, v]) => [k, v.description]),+ ),+ example: `${origin}/api/x402/${entry.slug}${query ? `?${query}` : ''}`,+ };+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -44,21 +113,7 @@ export default wrap(async (req, res) => {'Need one value instead of a payload? Every individual datapoint is its own $0.0005 endpoint — 480,000+ of them.',catalog: `${origin}/api/x402/d`,},- endpoints: MARKET_CATEGORIES.map((c) => ({- slug: c.slug,- title: c.title,- price_usdc: usd(c.priceAtomics),- url: `${origin}/api/x402/${c.slug}`,- summary: c.useCase,- params: Object.fromEntries(- Object.entries(c.inputSchema.properties || {}).map(([k, v]) => [k, v.description]),- ),- example: `${origin}/api/x402/${c.slug}${- Object.keys(c.inputExample).length- ? `?${new URLSearchParams(c.inputExample).toString()}`- : ''- }`,- })),+ endpoints: LISTED.map((entry) => describeEndpoint(entry, origin)),},{ 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1800' },);diff --git a/docs/market-data-api.md b/docs/market-data-api.mdindex d5b1c6c9f..8ed927378 100644--- a/docs/market-data-api.md+++ b/docs/market-data-api.md@@ -2,7 +2,7 @@The same live market data behind every three.ws `/markets` page — coin prices, DeFi TVL, yields, stablecoins, gas, derivatives, exploits, and more — packaged as **17 paid endpoints agents can discover and buy autonomously**. No API key, no signup, no subscription: request an endpoint, receive an HTTP 402 challenge, pay a USDC micro-payment on Solana or Base, get the data.-- **Free index (start here):** [`GET /api/x402/market`](https://three.ws/api/x402/market) — lists every endpoint with price, params, and a runnable example+- **Free index (start here):** [`GET /api/x402/market`](https://three.ws/api/x402/market): lists every paid `market-*` endpoint with its live price, params, and a runnable example, including the `market-heatmap` and `market-mood` siblings below- **Discovery:** every endpoint is listed in [`/.well-known/x402.json`](https://three.ws/.well-known/x402.json), so x402scan, agentic.market, and CDP Bazaar crawlers index it automatically- **Pricing:** $0.001 USDC per call for every category; the `market-pulse` bundle is $0.005- **Rails:** x402 v2, `exact` scheme — USDC on Solana mainnet or Base mainnet@@ -28,7 +28,7 @@ The browser pages (`/coins`, `/yields`, `/gas`, …) stay free for humans, with| `GET /api/x402/market-chains` | $0.001 | Chains ranked by TVL with share of total locked value || `GET /api/x402/market-yields` | $0.001 | ~15k yield pools, filterable/sortable; `?pool=<uuid>` for APY history || `GET /api/x402/market-stablecoins` | $0.001 | Top 100 stablecoins by supply with peg health |-| `GET /api/x402/market-fees` | $0.001 | Protocol fees (`?type=fees`) or revenue (`?type=revenue`) rankings |+| `GET /api/x402/market-fees` | $0.001 | Protocol fees (`?type=fees`, the default) or revenue (`?type=revenue`) rankings; any other `type` is a 422 || `GET /api/x402/market-dex-volumes` | $0.001 | Top 100 DEXs by 24h volume with market share || `GET /api/x402/market-hacks` | $0.001 | Full DeFi exploit database, searchable, with loss stats || `GET /api/x402/market-pulse` | $0.005 | **The bundle**: global + Fear & Greed + top-10 coins + trending + gas + DeFi TVL + stablecoins + DEX volume + fees in one call |@@ -105,6 +105,11 @@ A failed upstream never charges you: the endpoint verifies payment, runs the dat| 422 | `invalid_*` | A parameter failed validation (message says which) || 503 | `data_unavailable` | Upstream outage — retry shortly; you were not charged |+There is no 429 on this API. These endpoints impose no per-IP rate limit, so a+provider-side throttle upstream of us is reported as the 503 above, never as a+rate-limit status attributed to you. Retry logic should treat `data_unavailable`+as the single retryable class.+## Related- [x402 developer tools](/docs/x402-dev-tools) - free test bench for debugging payment envelopesdiff --git a/tests/market-data-api.test.js b/tests/market-data-api.test.jsindex 0d3f66887..6a4fdd731 100644--- a/tests/market-data-api.test.js+++ b/tests/market-data-api.test.js@@ -9,7 +9,23 @@// 3. Live 402 challenge — each thin route module builds a real paidEndpoint// whose unpaid response advertises the registry's exact price.-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';++// The sector builder is swappable so the upstream-failure suite below can drive+// a real provider error (429, 401) through the fetcher without a network call.+// Unswapped it delegates to the real module, so every other suite is untouched.+const realCategories = await vi.importActual('../api/coin/categories.js');+const categoriesImpl = { fn: realCategories.buildCategories };+vi.mock('../api/coin/categories.js', () => ({+ buildCategories: (...args) => categoriesImpl.fn(...args),+}));++function categoriesBuilder(fn) {+ categoriesImpl.fn = fn;+ return () => {+ categoriesImpl.fn = realCategories.buildCategories;+ };+}// Discovery env must be set BEFORE the paid-endpoint stack loads — same stub// set tests/service-catalog.test.js uses.@@ -131,6 +147,13 @@ describe('market-data fetcher validation', () => {});});+ it('market-fees rejects an unknown type instead of silently serving fees', async () => {+ await expectRejection(MARKET_FETCHERS['market-fees'](params({ type: 'revenu' })), {+ status: 422,+ code: 'invalid_type',+ });+ });+it('market-yields rejects a malformed pool uuid', async () => {await expectRejection(MARKET_FETCHERS['market-yields'](params({ pool: 'not-a-uuid' })), {status: 422,@@ -139,6 +162,54 @@ describe('market-data fetcher validation', () => {});});+// ── Upstream failure translation ────────────────────────────────────────────+//+// A provider throttle is OUR downtime, not the buyer's fault. Passing the+// upstream status through told a paying agent it was rate limited (on an+// endpoint sold as having no per-IP limits) and leaked the provider name and+// internal path in the error text. Only genuine caller faults survive intact.+describe('market-data upstream failure translation', () => {+ const throwing = (status, message) => async () => {+ throw Object.assign(new Error(message), { status });+ };++ it('reports an upstream 429 as retryable downtime, leaking no provider detail', async () => {+ const restore = categoriesBuilder(throwing(429, 'CoinGecko 429 for /coins/categories?order=market_cap_desc'));+ try {+ await expectRejection(MARKET_FETCHERS['market-categories'](params()), {+ status: 503,+ code: 'data_unavailable',+ });+ } finally {+ restore();+ }+ });++ it('reports an upstream auth fault as downtime too', async () => {+ const restore = categoriesBuilder(throwing(401, 'CoinGecko 401 for /coins/categories'));+ try {+ await expectRejection(MARKET_FETCHERS['market-categories'](params()), {+ status: 503,+ code: 'data_unavailable',+ });+ } finally {+ restore();+ }+ });++ it('still passes a genuine caller fault (404) through untouched', async () => {+ const restore = categoriesBuilder(throwing(404, 'no such category'));+ try {+ await expectRejection(MARKET_FETCHERS['market-categories'](params()), {+ status: 404,+ code: undefined,+ });+ } finally {+ restore();+ }+ });+});+// ── Live 402 challenge ──────────────────────────────────────────────────────function fakeRes() {return {diff --git a/tests/market-data-index.test.js b/tests/market-data-index.test.jsnew file mode 100644index 000000000..4a248dbaf--- /dev/null+++ b/tests/market-data-index.test.js@@ -0,0 +1,124 @@+// Free Market Data front door (/api/x402/market): the index an agent reads+// before it pays for anything.+//+// Two contracts are guarded here, both of which drifted silently in the past:+// 1. Completeness. The index promises every paid /api/x402/market-* endpoint.+// It used to list only the registry family, so the two hand-written+// siblings (market-heatmap, market-mood) were unreachable by discovery.+// 2. Price truth. The index used the registry's declared default while the+// live 402 resolves through priceFor(), so an X402_PRICE_MARKET_* override+// made the free index quote a price the endpoint no longer charges.+//+// Offline: no upstream calls, no payment.++import { describe, it, expect } from 'vitest';++// Discovery env must be set BEFORE the paid-endpoint stack loads. Same stub+// set tests/market-data-api.test.js uses.+Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',+ X402_PAY_TO_SOLANA: 'So11111111111111111111111111111111111111112',+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ X402_ASSET_MINT_SOLANA: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ X402_ASSET_ADDRESS_ARBITRUM: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',+ X402_MAX_AMOUNT_REQUIRED: '1000',+ X402_FEE_PAYER_SOLANA: 'So11111111111111111111111111111111111111112',+});++const indexRoute = (await import('../api/x402/market.js')).default;+const { PAID_SERVICES } = await import('../api/_lib/service-catalog/services/index.js');++function fakeRes() {+ return {+ statusCode: 0,+ headers: {},+ body: undefined,+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(body) {+ this.body = body;+ this.writableEnded = true;+ },+ };+}++async function readIndex() {+ const res = fakeRes();+ await indexRoute(+ { method: 'GET', url: '/api/x402/market', headers: { host: 'three.ws' } },+ res,+ );+ expect(res.statusCode).toBe(200);+ return JSON.parse(res.body);+}++// Every live paid endpoint the catalog places on the market-* path. This is the+// same set the index derives from, read independently so a filter bug in the+// route shows up as a mismatch rather than agreeing with itself.+const PAID_MARKET_PATHS = PAID_SERVICES.filter(+ (s) => s.status === 'live' && !s.free && s.path?.startsWith('/api/x402/market-'),+);++describe('the free market index', () => {+ it('lists every live paid /api/x402/market-* endpoint, siblings included', async () => {+ const body = await readIndex();+ const listed = new Set(body.endpoints.map((e) => e.slug));+ for (const s of PAID_MARKET_PATHS) {+ expect(listed.has(s.slug), `${s.slug} missing from the index`).toBe(true);+ }+ expect(body.endpoints.length).toBe(PAID_MARKET_PATHS.length);+ // The regression that motivated this file: both siblings present.+ expect(listed.has('market-heatmap')).toBe(true);+ expect(listed.has('market-mood')).toBe(true);+ });++ it('gives every row a runnable example on its own url', async () => {+ const body = await readIndex();+ for (const e of body.endpoints) {+ expect(e.url, e.slug).toBe(`https://three.ws/api/x402/${e.slug}`);+ expect(e.example.startsWith(e.url), e.slug).toBe(true);+ expect(e.price_usdc, e.slug).toMatch(/^\$\d/);+ expect(typeof e.summary, e.slug).toBe('string');+ // Advertised example params must all be declared params.+ const query = e.example.slice(e.url.length).replace(/^\?/, '');+ for (const key of new URLSearchParams(query).keys()) {+ expect(e.params[key], `${e.slug} example key ${key}`).toBeTruthy();+ }+ }+ });++ it('quotes the overridden price, not the declared default', async () => {+ const key = 'X402_PRICE_MARKET_GAS';+ const before = process.env[key];+ try {+ process.env[key] = '500'; // $0.0005, below the old formatter's floor+ const row = (await readIndex()).endpoints.find((e) => e.slug === 'market-gas');+ expect(row.price_usdc).toBe('$0.0005');+ } finally {+ if (before === undefined) delete process.env[key];+ else process.env[key] = before;+ }+ });++ it('formats whole-dollar and default prices without stray zeros', async () => {+ const key = 'X402_PRICE_MARKET_GAS';+ const before = process.env[key];+ try {+ process.env[key] = '1000000';+ let row = (await readIndex()).endpoints.find((e) => e.slug === 'market-gas');+ expect(row.price_usdc).toBe('$1');+ delete process.env[key];+ row = (await readIndex()).endpoints.find((e) => e.slug === 'market-gas');+ expect(row.price_usdc).toBe('$0.001');+ } finally {+ if (before === undefined) delete process.env[key];+ else process.env[key] = before;+ }+ });+});diff --git a/tests/market-datapoints.test.js b/tests/market-datapoints.test.jsindex 59178fd36..b87e59d5e 100644--- a/tests/market-datapoints.test.js+++ b/tests/market-datapoints.test.js@@ -297,4 +297,17 @@ describe('dynamic datapoint route', () => {expect(res.statusCode).toBe(422);expect(JSON.parse(res.body).error).toBe('invalid_id');});++ it('rejects a bad path in the same error envelope every other api handler uses', async () => {+ // A caller written against any other three.ws endpoint reads+ // error_description; this route used to answer `message` alone.+ const res = await drive('/api/x402/d/global/not-a-metric');+ expect(res.statusCode).toBe(404);+ const body = JSON.parse(res.body);+ expect(body.error).toBe('unknown_metric');+ expect(body.error_description).toContain('unknown metric');+ expect(body.families).toContain('global');+ // An error is never cacheable, whatever the paid path advertises.+ expect(String(res.headers['cache-control'])).toContain('no-store');+ });});diff --git a/tests/market-heatmap-board.test.js b/tests/market-heatmap-board.test.jsnew file mode 100644index 000000000..f4dbb6b44--- /dev/null+++ b/tests/market-heatmap-board.test.js@@ -0,0 +1,90 @@+// Market Heatmap board normalization (/api/x402/market-heatmap): unit tests+// for the two pure pieces a buyer's payload is built from.+//+// rankOr covers the upstream shape that produced a nonsense rank of 0: an+// unranked CoinGecko row sends `market_cap_rank: null`, and Number(null) is 0,+// which passes a plain finite check. breadth covers the advancer/decliner split+// including the dead band and unpriced coins.++import { describe, it, expect } from 'vitest';++// Discovery env must be set BEFORE the paid-endpoint stack loads. Same stub+// set tests/market-data-api.test.js uses.+Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',+ X402_PAY_TO_SOLANA: 'So11111111111111111111111111111111111111112',+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ X402_ASSET_MINT_SOLANA: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ X402_ASSET_ADDRESS_ARBITRUM: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',+ X402_MAX_AMOUNT_REQUIRED: '1000',+ X402_FEE_PAYER_SOLANA: 'So11111111111111111111111111111111111111112',+});++const { rankOr, breadth, OUTPUT_SCHEMA } = await import('../api/x402/market-heatmap.js');++describe('rankOr', () => {+ it('keeps a real 1-based rank', () => {+ expect(rankOr(1, 99)).toBe(1);+ expect(rankOr('42', 99)).toBe(42);+ });++ it('falls back for every shape that is not a rank', () => {+ expect(rankOr(null, 7)).toBe(7); // the CoinGecko unranked row+ expect(rankOr(undefined, 7)).toBe(7);+ expect(rankOr(0, 7)).toBe(7);+ expect(rankOr(-3, 7)).toBe(7);+ expect(rankOr('n/a', 7)).toBe(7);+ });++ it('never emits a fractional rank (the output schema declares an integer)', () => {+ expect(rankOr(12.7, 99)).toBe(12);+ expect(OUTPUT_SCHEMA.properties.coins.items.properties.rank.type).toBe('integer');+ });+});++describe('breadth', () => {+ it('splits advancers, decliners, and flat around the dead band', () => {+ const coins = [+ { change_24h: 3 },+ { change_24h: 0.4 },+ { change_24h: 0.01 }, // inside the dead band+ { change_24h: -0.02 }, // inside the dead band+ { change_24h: -1.6 },+ ];+ expect(breadth(coins)).toEqual({+ advancers: 2,+ decliners: 1,+ flat: 2,+ avg_change_24h: 0.36,+ median_change_24h: 0.01,+ });+ });++ it('averages the even case across the two middle moves', () => {+ const out = breadth([{ change_24h: 1 }, { change_24h: 2 }, { change_24h: 3 }, { change_24h: 6 }]);+ expect(out.median_change_24h).toBe(2.5);+ expect(out.avg_change_24h).toBe(3);+ });++ it('excludes coins the upstream could not price', () => {+ const out = breadth([{ change_24h: 2 }, { change_24h: null }, { change_24h: undefined }]);+ expect(out).toEqual({+ advancers: 1,+ decliners: 0,+ flat: 0,+ avg_change_24h: 2,+ median_change_24h: 2,+ });+ });++ it('reports nulls rather than NaN on an empty board', () => {+ expect(breadth([])).toEqual({+ advancers: 0,+ decliners: 0,+ flat: 0,+ avg_change_24h: null,+ median_change_24h: null,+ });+ });+});