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
feat: datapoint fabric — 480k+ standalone paid x402 endpoints
fudjia7bfc03c0bf61
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 2efed4e99..461f84316 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -31,6 +31,7 @@ bottom.| Unified Crypto API aggregator — storefront + OpenAPI | Registry [api/v1/_providers.js](api/v1/_providers.js) (`providerCatalog()`), front door [api/v1/x/[...slug].js](api/v1/x/%5B...slug%5D.js) `→ /api/v1/x/<provider>/<endpoint>`, discovery `→ GET /api/v1/x`, storefront [pages/crypto-api.html](pages/crypto-api.html) `→ /crypto-api`, OpenAPI 3.1 [api/openapi-json.js](api/openapi-json.js) `→ /openapi.json`, docs § in [docs/api-reference.md](docs/api-reference.md#unified-api--apiv1x-aggregator), dir guide [api/v1/README.md](api/v1/README.md) | Live | Third-party crypto/DeFi/on-chain APIs (CoinGecko, DefiLlama × 2, Jupiter, DexScreener, Solana RPC, OpenAI-compatible) re-offered as one bill: free per-IP tier → BYOK pass-through → three.ws plan → x402 pay-per-call, in that order. Everything (OpenAPI paths, the `/crypto-api` live table, the docs quota table) renders from `providerCatalog()` at request/page-load time — no hand-enumeration, so a new provider descriptor shows up everywhere with zero page edits. Test: [tests/openapi-aggregator.test.js](tests/openapi-aggregator.test.js). Not to be confused with the separate `/api/crypto/*` bundle below (different campaign, different registry). Spec: [prompts/x402-catalog/](prompts/x402-catalog) || Free 3D API + docs | [api/3d/index.js](api/3d/index.js) `→ /api/3d`, [api/3d/openapi.js](api/3d/openapi.js) `→ /api/3d/openapi.json`, docs [public/3d.html](public/3d.html) `→ /3d` (alias `/docs/3d-api`) | Live · docs surface | Front door + OpenAPI 3.1 for the free, keyless 3D API. Catalog assembler [api/_lib/3d-catalog/index.js](api/_lib/3d-catalog/index.js) merges `api/_lib/3d-catalog/*.js` descriptors (currently `generate`, `inspect`) via a static import barrel (production source of truth) plus an additive dev-time directory glob; new descriptor = drop the file AND add its barrel import line; skips malformed, never throws; OpenAPI built from the same catalog via [api/_lib/3d-catalog/openapi.js](api/_lib/3d-catalog/openapi.js). Index does HTML/JSON content negotiation and advertises the paid ladder (Forge Pro, Rigged Avatars). Docs page: hero, live endpoint table, runnable quickstart with a live "Run inspect" console, embedded `<model-viewer>` GLB preview, and the free→paid ladder. Free endpoints: [api/3d/generate.js](api/3d/generate.js) (prompt 12), [api/3d/inspect.js](api/3d/inspect.js) (prompt 13). GPT Store Actions surface: [api/3d/studio.js](api/3d/studio.js) `→ /api/3d/studio` — a store-compliant twin of `generate` that strips the x402/upgrade block, drops internal ids, and runs the [api/_mcp-studio/safety.js](api/_mcp-studio/safety.js) age-13+ content gate before any GPU work; backs the "three.ws 3D Studio" custom GPT ([prompts/store-submissions/_generated/openai-actions.yaml](prompts/store-submissions/_generated/openai-actions.yaml) + [openai-gpt-config.md](prompts/store-submissions/_generated/openai-gpt-config.md), store-submission prompt 12). Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) || Paid Market Data API (x402, 17 endpoints) | Registry [api/_lib/market-data/registry.js](api/_lib/market-data/registry.js), fetchers [api/_lib/market-data/fetch.js](api/_lib/market-data/fetch.js), factory [api/_lib/market-data/endpoint.js](api/_lib/market-data/endpoint.js), routes `api/x402/market-*.js` `→ /api/x402/market-<category>`, free index [api/x402/market.js](api/x402/market.js) `→ /api/x402/market`, catalog projection [api/_lib/service-catalog/services/market-data.js](api/_lib/service-catalog/services/market-data.js), docs [docs/market-data-api.md](docs/market-data-api.md) `→ /docs/market-data-api` | Live | Every free /markets feed (coins, coin profile, price history, categories, exchanges, derivatives, global+Fear&Greed, ETH gas, trending, DeFi TVL, chains, ~15k yield pools, stablecoins, fees/revenue, DEX volumes, hacks) wrapped as pay-per-call x402 endpoints at $0.001 USDC (Solana/Base), plus the $0.005 one-call `market-pulse` bundle. One registry drives the live 402s, the discovery-doc listings, and the free index — zero drift by construction; the fetchers delegate to the SAME exported builders the free pages use (`api/coin/*`, `api/defi/*`), so paid data always matches the site. Params rejected pre-settle (422) and upstream outages (503) never charge the buyer. Tests: [tests/market-data-api.test.js](tests/market-data-api.test.js). |+| Datapoint fabric (x402, 480k+ endpoints) | Registry [api/_lib/market-data/datapoints.js](api/_lib/market-data/datapoints.js), dynamic route [api/x402/d/[...path].js](api/x402/d/%5B...path%5D.js) `→ /api/x402/d/<family>/<id>/<metric>`, free catalog [api/x402/d/index.js](api/x402/d/index.js) `→ /api/x402/d`, discovery slice `buildDatapointItems` in [api/wk.js](api/wk.js), docs § in [docs/market-data-api.md](docs/market-data-api.md#the-datapoint-fabric--480000-standalone-endpoints) | Live | Every individual market datapoint as its OWN standalone paid endpoint — one URL = one value = one $0.0005 USDC x402 micro-payment (override `X402_PRICE_DATAPOINT_<FAMILY>`). 9 families × 68 metrics × live id spaces ≈ 484k addressable endpoints (~17.5k coins × 20, ~15.5k pools × 7, ~6k protocols × 6, chains, stablecoins, exchanges, global/gas/fear-greed) served by ONE dynamic route reading the registry; ids are runtime values, nothing hardcodes a third-party asset. Path that cannot exist → 404/422 with NO 402 issued; unknown id/outage rejects pre-settle. Free catalog enumerates families, metrics, prices, and pages each family's full live id space (200/page) so crawlers can walk the universe; the .well-known discovery doc carries a curated runtime-derived slice (~83 concrete resources). Tests: [tests/market-datapoints.test.js](tests/market-datapoints.test.js). || Unified service catalog (one source, two storefronts) | [api/_lib/service-catalog/index.js](api/_lib/service-catalog/index.js), descriptors [api/_lib/service-catalog/services/](api/_lib/service-catalog/services/index.js) | Live | The canonical written-once record of every service (paid x402 + free crypto/3D bundles + OKX.AI rows). `toBazaarDiscovery()` generates every static `/api/x402/*` entry in the [api/wk.js](api/wk.js) discovery doc (replacing ~1,400 lines of hand-mirrored blocks); `toOkxCatalog()` reproduces the OKX `catalogIndex()` payload exactly, with an `include:'all'` projection ready for listing expansion. New paid service = drop `services/<slug>.js` + add its barrel import row. No-drift guards: [tests/service-catalog.test.js](tests/service-catalog.test.js). Spec: [specs/SERVICE_CATALOG.md](specs/SERVICE_CATALOG.md) || Conversational refinement + remix economy | Iterate: [api/_mcp-studio/tools.js](api/_mcp-studio/tools.js) `refine_model` (free, on `/api/mcp-studio`) + [mcp-server/src/tools/refine-model.js](mcp-server/src/tools/refine-model.js) (paid stdio, $0.25); shared lineage core [mcp-server/src/tools/_lineage.js](mcp-server/src/tools/_lineage.js). Remix (paid track): feed [api/remix-feed.js](api/remix-feed.js) `→ /api/remix-feed` (free browse/publish/lineage), settlement [api/x402/remix-asset.js](api/x402/remix-asset.js) `→ /api/x402/remix-asset` + core [api/_lib/remix-settlement.js](api/_lib/remix-settlement.js) + split math [api/_lib/remix-royalty.js](api/_lib/remix-royalty.js). Docs [docs/remix.md](docs/remix.md), [docs/mcp-studio.md](docs/mcp-studio.md). | Live | Talk to a model to iterate it ("make it metallic") — real anchored re-generation with a revertable/branchable version lineage rendered as a viewer version strip; free on both the OpenAI 3D Studio and the paid MCP server. Creators publish a finished model as remixable (provenance + license + royalty on the existing `forge_creations` rows — no parallel store); another agent pays $0.25 USDC to remix it and a creator-set royalty (≤20%, capped) routes on-chain to the original creator via the audited `transferSolanaUSDC` rail. Split/caps/payout unit-tested ([tests/remix-settlement.test.js](tests/remix-settlement.test.js), [tests/remix-royalty.test.js](tests/remix-royalty.test.js), [tests/refine-lineage.test.js](tests/refine-lineage.test.js)). Free track stays crypto-free. Prompt 09. || Restyle Studio (material/PBR editor + AI restyle + variants) | [pages/restyle.html](pages/restyle.html) `→ /restyle`, [src/restyle.js](src/restyle.js). PBR preset/variant library [packages/viewer-presets/src/materials.js](packages/viewer-presets/src/materials.js) (`@three-ws/viewer-presets`). AI restyle + persistence core [api/_lib/material-studio-store.js](api/_lib/material-studio-store.js), free hosted endpoint [api/material-studio.js](api/material-studio.js) `→ /api/material-studio`; paid agent twin [mcp-server/src/tools/restyle-material.js](mcp-server/src/tools/restyle-material.js) (`restyle_material`, $0.05 stdio MCP), thin core [mcp-server/src/tools/_material-core.js](mcp-server/src/tools/_material-core.js). Shares the `refine_model` lineage core ([mcp-server/src/tools/_lineage.js](mcp-server/src/tools/_lineage.js)) so a restyle/variant is just another kind of version, feeding prompt 09 remix. Docs: [docs/mcp-tools.md](docs/mcp-tools.md). | Live | Re-skin any GLB without regenerating its mesh: live PBR editing (color/metalness/roughness/emissive/texture) with a one-click preset library (14 looks — chrome, gold, glass, wood…), seeded reproducible colorway variants (mulberry32 PRNG — same base+seed → same set), and free-text AI restyle ("make it chrome", "cyberpunk neon") via IBM Granite-proposed PBR factors applied + re-exported server-side. Every AI restyle / saved checkpoint mints a real, `gltf-validator`-checked, durably-stored GLB recorded in an immutable parent→child lineage — non-destructive in the durable sense, not just an in-browser Reset. Roadmap prompt 06. |diff --git a/api/_lib/market-data/datapoints.js b/api/_lib/market-data/datapoints.jsnew file mode 100644index 000000000..88b88ede0--- /dev/null+++ b/api/_lib/market-data/datapoints.js@@ -0,0 +1,440 @@+// Datapoint fabric — the registry behind /api/x402/d/<family>/<id>/<metric>.+//+// The Market Data API's category endpoints sell whole payloads; this fabric+// sells SINGLE datapoints. Every (family, id, metric) triple is its own+// individually addressable, individually priced x402 endpoint:+//+// /api/x402/d/coin/bitcoin/price → { value: 64346, unit: 'usd', … }+// /api/x402/d/protocol/lido/tvl+// /api/x402/d/pool/747c1d2a-…-296708a3dd90/apy+// /api/x402/d/global/btc-dominance+//+// Families × live catalog sizes × metrics ≈ 400,000+ standalone endpoints+// (~17.5k coins × 20 metrics, ~15k pools × 7, ~6k protocols × 6, plus chains,+// stablecoins, exchanges, and the no-id global/gas/fear-greed families) — all+// served by ONE dynamic route (api/x402/d/[...path].js) reading this registry.+// Ids are supplied at runtime by the caller; nothing here hardcodes a specific+// third-party asset.+//+// Sources reuse the same cached builders the category endpoints and /markets+// pages run on. Where a category builder slices for page rendering (top-100+// protocols/chains/stablecoins), the fabric keeps its own slim FULL-set cache+// of the identical upstream feed so every id is addressable, not just the+// leaderboard.+//+// Error contract (same as ../fetch.js — enforced pre-settle, buyer never+// charged): unknown family/metric → 404 at the route (no 402 issued for a+// resource that cannot exist); malformed id → 422; unknown id → 404; upstream+// outage → 503.++import { fetchGlobalMarket } from '../market-fallbacks.js';+import { isPlausibleCoinId } from '../coingecko.js';+import { buildCoinDetail, MINT_RE } from '../../coin/detail.js';+import { buildExchanges } from '../../coin/exchanges.js';+import { fetchFearGreed } from '../../coin/global.js';+import { buildGasReport } from '../../coin/gas.js';+import { loadYieldPools } from '../../defi/yields.js';++const fail = (status, code, message) => {+ throw Object.assign(new Error(message), { status, code });+};++const finite = (n) => (Number.isFinite(n) ? n : null);++// ── Full-set caches (feeds the category builders slice for page rendering) ──++const TTL_MS = 600_000;+const _full = new Map(); // key → { value, expiresAt }++async function fullSet(key, url, slim) {+ const now = Date.now();+ const hit = _full.get(key);+ if (hit && hit.expiresAt > now) return hit.value;+ const resp = await fetch(url, {+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(15_000),+ });+ if (!resp.ok) throw new Error(`${key} upstream ${resp.status}`);+ const value = slim(await resp.json());+ _full.set(key, { value, expiresAt: now + TTL_MS });+ return value;+}++// slug → slim protocol row, over the FULL ~6k-protocol DeFiLlama feed.+// Exported (with the other full-set accessors) for the free enumerator at+// /api/x402/d, which pages through the same cached id space.+export function allProtocols() {+ return fullSet('protocols', 'https://api.llama.fi/protocols', (raw) => {+ if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');+ const bySlug = new Map();+ for (const p of raw) {+ if (typeof p?.slug !== 'string' || !p.slug) continue;+ bySlug.set(p.slug, {+ name: typeof p.name === 'string' ? p.name : p.slug,+ category: typeof p.category === 'string' ? p.category : null,+ tvl: finite(Number(p.tvl)),+ change_1d: finite(Number(p.change_1d)),+ change_7d: finite(Number(p.change_7d)),+ mcap: finite(Number(p.mcap)),+ chain_count: Array.isArray(p.chains) ? p.chains.length : 0,+ });+ }+ return bySlug;+ });+}++// lowercase chain name → slim row + whole-market total for share-pct.+export function allChains() {+ return fullSet('chains', 'https://api.llama.fi/v2/chains', (raw) => {+ if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');+ const byName = new Map();+ let totalTvl = 0;+ for (const c of raw) {+ const tvl = Number(c?.tvl);+ if (typeof c?.name !== 'string' || !Number.isFinite(tvl)) continue;+ totalTvl += Math.max(0, tvl);+ byName.set(c.name.toLowerCase(), {+ name: c.name,+ tvl,+ token_symbol: typeof c.tokenSymbol === 'string' && c.tokenSymbol ? c.tokenSymbol : null,+ });+ }+ for (const row of byName.values()) {+ row.share_pct = totalTvl > 0 ? (Math.max(0, row.tvl) / totalTvl) * 100 : 0;+ }+ return byName;+ });+}++// id AND lowercase symbol → slim stablecoin row, over the full pegged set.+export function allStablecoins() {+ return fullSet(+ 'stablecoins',+ 'https://stablecoins.llama.fi/stablecoins?includePrices=true',+ (body) => {+ const assets = Array.isArray(body?.peggedAssets) ? body.peggedAssets : null;+ if (!assets) throw new Error('unexpected upstream shape');+ const byKey = new Map();+ for (const a of assets) {+ const pegType = typeof a?.pegType === 'string' ? a.pegType : null;+ const circulating = pegType && a.circulating ? Number(a.circulating[pegType]) : NaN;+ if (!Number.isFinite(circulating)) continue;+ const price = Number(a.price);+ const row = {+ name: typeof a.name === 'string' ? a.name : 'Unknown',+ symbol: typeof a.symbol === 'string' ? a.symbol : '',+ price: Number.isFinite(price) ? price : null,+ peg_type: pegType,+ peg_mechanism: typeof a.pegMechanism === 'string' ? a.pegMechanism : null,+ circulating: circulating,+ chain_count: Array.isArray(a.chains) ? a.chains.length : 0,+ };+ if (a.id != null) byKey.set(String(a.id), row);+ if (row.symbol) byKey.set(row.symbol.toLowerCase(), row);+ }+ return byKey;+ },+ );+}++// ── Row resolvers (throw 404 for an unknown id, 503 for an outage) ──────────++async function resolve(label, id, lookup) {+ let row;+ try {+ row = await lookup();+ } catch (err) {+ if (err?.status && err.status < 500) throw err;+ fail(503, 'data_unavailable', `live ${label} data is temporarily unavailable — retry shortly`);+ }+ if (row == null) fail(404, 'not_found', `no ${label} found for "${id}"`);+ return row;+}++// ── The registry ────────────────────────────────────────────────────────────+//+// Each family: { idKind, describeId, validateId(id) → 422 on garbage,+// row(id) → the object metrics extract from, metrics: { slug → {label, unit,+// extract} }, count() → approximate live id count for the enumerator }.++const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);+const m = (label, unit, extract) => ({ label, unit, extract });++export const DATAPOINT_FAMILIES = {+ coin: {+ describeId: 'CoinGecko coin id (e.g. a lowercase slug) or a base58 Solana mint',+ validateId(id) {+ if (!isPlausibleCoinId(id) && !MINT_RE.test(id)) {+ fail(422, 'invalid_id', 'id must be a CoinGecko coin id (lowercase slug) or a base58 Solana mint');+ }+ },+ async row(id) {+ const contract = MINT_RE.test(id) && !isPlausibleCoinId(id) ? id : '';+ return resolve('coin', id, async () => {+ try {+ const { coin } = await buildCoinDetail(contract ? { contract } : { id });+ return coin;+ } catch (err) {+ if (err?.status === 404) return null;+ throw err;+ }+ });+ },+ approxCount: 17_000,+ metrics: {+ price: m('Spot price', 'usd', (c) => num(c.market?.price)),+ 'market-cap': m('Market capitalization', 'usd', (c) => num(c.market?.market_cap)),+ fdv: m('Fully diluted valuation', 'usd', (c) => num(c.market?.fdv)),+ 'volume-24h': m('24h trading volume', 'usd', (c) => num(c.market?.volume_24h)),+ 'change-24h': m('24h price change', 'pct', (c) => num(c.market?.change_pct?.h24)),+ 'change-7d': m('7-day price change', 'pct', (c) => num(c.market?.change_pct?.d7)),+ 'change-30d': m('30-day price change', 'pct', (c) => num(c.market?.change_pct?.d30)),+ 'change-1y': m('1-year price change', 'pct', (c) => num(c.market?.change_pct?.y1)),+ rank: m('Market-cap rank', 'rank', (c) => num(c.rank)),+ ath: m('All-time-high price', 'usd', (c) => num(c.market?.ath)),+ 'ath-change': m('Drawdown from all-time high', 'pct', (c) => num(c.market?.ath_change_pct)),+ atl: m('All-time-low price', 'usd', (c) => num(c.market?.atl)),+ 'high-24h': m('24h high', 'usd', (c) => num(c.market?.high_24h)),+ 'low-24h': m('24h low', 'usd', (c) => num(c.market?.low_24h)),+ 'circulating-supply': m('Circulating supply', 'tokens', (c) => num(c.market?.circulating)),+ 'total-supply': m('Total supply', 'tokens', (c) => num(c.market?.total)),+ 'max-supply': m('Max supply', 'tokens', (c) => num(c.market?.max)),+ 'mcap-fdv-ratio': m('Market-cap / FDV ratio', 'ratio', (c) => num(c.market?.mcap_fdv_ratio)),+ 'sentiment-up': m('Bullish sentiment votes', 'pct', (c) => num(c.sentiment?.up_pct)),+ 'watchlist-users': m('Watchlist portfolio users', 'count', (c) => num(c.sentiment?.watchlist_users)),+ },+ },++ protocol: {+ describeId: 'DeFiLlama protocol slug (e.g. a lowercase-hyphen name)',+ validateId(id) {+ if (!/^[a-z0-9-]{1,100}$/.test(id)) {+ fail(422, 'invalid_id', 'id must be a DeFiLlama protocol slug (lowercase, hyphens)');+ }+ },+ row: (id) => resolve('protocol', id, async () => (await allProtocols()).get(id) ?? null),+ approxCount: 6_000,+ metrics: {+ tvl: m('Total value locked', 'usd', (p) => p.tvl),+ 'change-1d': m('1-day TVL change', 'pct', (p) => p.change_1d),+ 'change-7d': m('7-day TVL change', 'pct', (p) => p.change_7d),+ mcap: m('Token market cap', 'usd', (p) => p.mcap),+ category: m('Protocol category', 'text', (p) => p.category),+ 'chain-count': m('Deployed chain count', 'count', (p) => p.chain_count),+ },+ },++ chain: {+ describeId: 'chain name as DeFiLlama spells it (case-insensitive)',+ validateId(id) {+ if (!/^[a-z0-9 ._-]{1,60}$/i.test(id)) {+ fail(422, 'invalid_id', 'id must be a chain name (letters, digits, spaces, dots, hyphens)');+ }+ },+ row: (id) => resolve('chain', id, async () => (await allChains()).get(id.toLowerCase()) ?? null),+ approxCount: 350,+ metrics: {+ tvl: m('DeFi total value locked', 'usd', (c) => finite(c.tvl)),+ 'share-pct': m('Share of all-chain TVL', 'pct', (c) => finite(c.share_pct)),+ 'token-symbol': m('Native token symbol', 'text', (c) => c.token_symbol),+ },+ },++ pool: {+ describeId: 'DeFiLlama yield-pool uuid',+ validateId(id) {+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {+ fail(422, 'invalid_id', 'id must be a DeFiLlama pool uuid');+ }+ },+ row: (id) =>+ resolve('yield pool', id, async () => {+ const { pools } = await loadYieldPools();+ const key = id.toLowerCase();+ return pools.find((p) => p.pool.toLowerCase() === key) ?? null;+ }),+ approxCount: 15_000,+ metrics: {+ apy: m('Current APY', 'pct', (p) => p.apy),+ 'apy-base': m('Base APY (fee-derived)', 'pct', (p) => p.apy_base),+ 'apy-reward': m('Reward APY (incentives)', 'pct', (p) => p.apy_reward),+ 'apy-mean-30d': m('30-day mean APY', 'pct', (p) => p.apy_mean_30d),+ tvl: m('Pool TVL', 'usd', (p) => finite(p.tvl_usd)),+ 'il-risk': m('Impermanent-loss risk', 'text', (p) => p.il_risk),+ outlook: m('Predicted APY outlook', 'text', (p) => p.outlook),+ },+ },++ stablecoin: {+ describeId: 'DeFiLlama stablecoin id (numeric) or its symbol',+ validateId(id) {+ if (!/^[a-z0-9$+._-]{1,30}$/i.test(id)) {+ fail(422, 'invalid_id', 'id must be a DeFiLlama stablecoin id or symbol');+ }+ },+ row: (id) =>+ resolve('stablecoin', id, async () => {+ const set = await allStablecoins();+ return set.get(id) ?? set.get(id.toLowerCase()) ?? null;+ }),+ approxCount: 400,+ metrics: {+ supply: m('Circulating supply (peg units)', 'peg-units', (s) => finite(s.circulating)),+ price: m('Current price', 'usd', (s) => s.price),+ 'peg-deviation-bps': m('Deviation from $1 peg', 'bps', (s) =>+ s.price == null ? null : Math.round((s.price - 1) * 10_000),+ ),+ 'peg-mechanism': m('Peg mechanism', 'text', (s) => s.peg_mechanism),+ 'chain-count': m('Deployed chain count', 'count', (s) => s.chain_count),+ },+ },++ exchange: {+ describeId: 'CoinGecko exchange id (e.g. a lowercase slug)',+ validateId(id) {+ if (!/^[a-z0-9_-]{1,60}$/.test(id)) {+ fail(422, 'invalid_id', 'id must be a CoinGecko exchange id (lowercase slug)');+ }+ },+ row: (id) =>+ resolve('exchange', id, async () => {+ const { exchanges } = await buildExchanges();+ return exchanges.find((e) => e.id === id) ?? null;+ }),+ approxCount: 100,+ metrics: {+ 'volume-24h': m('24h volume', 'usd', (e) => e.volume_24h_usd),+ 'volume-24h-btc': m('24h volume', 'btc', (e) => e.volume_24h_btc),+ 'trust-score': m('Trust score (0–10)', 'score', (e) => e.trust_score),+ 'trust-rank': m('Trust-score rank', 'rank', (e) => e.trust_score_rank),+ country: m('Registered country', 'text', (e) => e.country),+ },+ },++ global: {+ describeId: null, // no id segment — /api/x402/d/global/<metric>+ row: () => resolve('global market', 'global', () => fetchGlobalMarket()),+ approxCount: 1,+ metrics: {+ 'market-cap': m('Total crypto market cap', 'usd', (g) => num(g.market_cap_usd)),+ 'volume-24h': m('Total 24h volume', 'usd', (g) => num(g.volume_24h_usd)),+ 'market-cap-change-24h': m('24h market-cap change', 'pct', (g) => num(g.market_cap_change_pct_24h)),+ 'active-coins': m('Active tracked coins', 'count', (g) => num(g.active_coins)),+ 'btc-dominance': m('BTC dominance', 'pct', (g) => num(g.dominance?.[0]?.pct)),+ 'eth-dominance': m('ETH dominance', 'pct', (g) => num(g.dominance?.[1]?.pct)),+ },+ },++ 'fear-greed': {+ describeId: null,+ row: () => resolve('fear & greed', 'fear-greed', () => fetchFearGreed()),+ approxCount: 1,+ metrics: {+ index: m('Fear & Greed index (0–100)', 'index', (f) => num(f.value)),+ label: m('Fear & Greed classification', 'text', (f) => f.label),+ },+ },++ gas: {+ describeId: null,+ row: () => resolve('gas', 'gas', () => buildGasReport()),+ approxCount: 1,+ metrics: {+ slow: m('Slow tier gas price', 'gwei', (g) => finite(g.tiers?.[0]?.gas_price_gwei)),+ standard: m('Standard tier gas price', 'gwei', (g) => finite(g.tiers?.[1]?.gas_price_gwei)),+ fast: m('Fast tier gas price', 'gwei', (g) => finite(g.tiers?.[2]?.gas_price_gwei)),+ 'base-fee': m('Current base fee', 'gwei', (g) => finite(g.base_fee_gwei)),+ 'eth-price': m('ETH spot price', 'usd', (g) => g.eth_price_usd),+ },+ },+};++// $0.0005 USDC per datapoint by default — half the category-call price, since+// a datapoint is one scalar. Ops override per family: X402_PRICE_DATAPOINT_<FAMILY>.+export const DATAPOINT_DEFAULT_ATOMICS = '500';++// ── Path parsing ─────────────────────────────────────────────────────────────+//+// /api/x402/d/<family>/<id>/<metric> for id families,+// /api/x402/d/<family>/<metric> for the no-id families.+// Returns { family, familyDef, id, metric, metricDef } or throws+// { status: 404 } for a shape that cannot exist / { status: 422 } for a+// malformed id — both BEFORE any 402 is issued, so nobody is asked to pay for+// a resource that does not exist.++export function parseDatapointPath(segments) {+ const [familySlug, ...rest] = segments;+ const familyDef = DATAPOINT_FAMILIES[familySlug];+ if (!familyDef) {+ fail(404, 'unknown_family', `unknown datapoint family "${familySlug}" — GET /api/x402/d for the catalog`);+ }+ const needsId = familyDef.describeId != null;+ const expected = needsId ? 2 : 1;+ if (rest.length !== expected) {+ fail(+ 404,+ 'bad_path',+ needsId+ ? `expected /api/x402/d/${familySlug}/<id>/<metric>`+ : `expected /api/x402/d/${familySlug}/<metric>`,+ );+ }+ const id = needsId ? decodeURIComponent(rest[0]) : null;+ const metric = rest[needsId ? 1 : 0];+ const metricDef = familyDef.metrics[metric];+ if (!metricDef) {+ fail(+ 404,+ 'unknown_metric',+ `unknown metric "${metric}" for ${familySlug} — valid: ${Object.keys(familyDef.metrics).join(', ')}`,+ );+ }+ if (needsId) familyDef.validateId(id);+ return { family: familySlug, familyDef, id, metric, metricDef };+}++// Fetch + extract one datapoint. The paid handler's whole job.+export async function readDatapoint({ family, familyDef, id, metric, metricDef }) {+ const row = await familyDef.row(id);+ const value = metricDef.extract(row);+ return {+ family,+ ...(id != null ? { id } : {}),+ metric,+ label: metricDef.label,+ unit: metricDef.unit,+ value: value === undefined ? null : value,+ as_of: new Date().toISOString(),+ source: 'three.ws market-data',+ };+}++// Storefront description for one (family, metric) datapoint listing — shared+// by the live 402 (api/x402/d/[...path].js) and the discovery-doc entries+// (api/wk.js) so the two surfaces can never drift.+export function datapointDescription({ family, metric, priceAtomics }) {+ const familyDef = DATAPOINT_FAMILIES[family];+ const metricDef = familyDef.metrics[metric];+ const price = (Number(priceAtomics) / 1_000_000)+ .toFixed(4)+ .replace(/0+$/, '')+ .replace(/\.$/, '');+ const idPart = familyDef.describeId+ ? ` Pass the ${familyDef.describeId} as the path id — supplied at runtime by the caller.`+ : '';+ return (+ `Single datapoint: ${metricDef.label.toLowerCase()} for one ${family} — ` ++ `pay $${price} USDC per call and get back one machine-readable value ` ++ `(unit: ${metricDef.unit}) with a timestamp.${idPart} ` ++ `Part of the three.ws datapoint fabric — 400,000+ addressable endpoints, cataloged free at /api/x402/d.`+ );+}++// Approximate count of addressable datapoint endpoints, for the enumerator.+export function datapointEndpointCount() {+ let total = 0;+ for (const def of Object.values(DATAPOINT_FAMILIES)) {+ total += def.approxCount * Object.keys(def.metrics).length;+ }+ return total;+}diff --git a/api/defi/yields.js b/api/defi/yields.jsindex 47c34410f..bf2f65b04 100644--- a/api/defi/yields.js+++ b/api/defi/yields.js@@ -89,6 +89,12 @@ function buildFacets(pools, key, topN) {.map(([name, { count }]) => ({ name, pool_count: count }));}+// Exported for the paid datapoint fabric (api/_lib/market-data/datapoints.js)+// — per-pool datapoint endpoints resolve a uuid against this cached full set.+export async function loadYieldPools() {+ return loadPools();+}+async function loadPools() {const now = Date.now();if (_pools && _pools.expiresAt > now) return _pools.value;diff --git a/api/wk.js b/api/wk.jsindex 5f9acb7a0..1ddf5aea6 100644--- a/api/wk.js+++ b/api/wk.js@@ -27,6 +27,14 @@ import { STUDIO_CHALLENGE } from './_mcp3d/discovery.js';import { TOOL_CATALOG as STUDIO_TOOL_CATALOG } from './_mcp3d/catalog.js';import { priceFor as studioPriceFor } from './_mcp3d/pricing.js';import { priceFor } from './_lib/pump-pricing.js';+import { priceFor as datapointPriceFor } from './_lib/x402-prices.js';+import {+ DATAPOINT_FAMILIES,+ DATAPOINT_DEFAULT_ATOMICS,+ datapointDescription,+} from './_lib/market-data/datapoints.js';+import { fetchMarketsTable } from './_lib/market-fallbacks.js';+import { buildProtocols } from './defi/protocols.js';import { FORGE_OUTPUT_EXAMPLE } from './_lib/forge-listing.js';import { listBazaarServices, serviceResourceUrl } from './_lib/agent-paid-services.js';import { toBazaarDiscovery } from './_lib/service-catalog/index.js';@@ -493,6 +501,95 @@ async function buildAgentServiceItems(origin) {return items;}+// Datapoint fabric (/api/x402/d/<family>/<id>/<metric>) — 400k+ addressable+// single-datapoint endpoints served by one dynamic route. The discovery doc+// can't (and shouldn't) list them all; it lists a curated slice indexers can+// surface: every no-id metric (global / gas / fear-greed) plus a+// runtime-derived set of concrete high-traffic ids (top coins by market cap ×+// headline metrics, top protocols by TVL × tvl). Ids come from the live+// cached feeds at render time — nothing here hardcodes a third-party asset —+// and any upstream hiccup degrades to the static slice (the fabric itself+// keeps serving every id regardless; /api/x402/d enumerates the full space).+async function buildDatapointItems(origin) {+ const items = [];+ const svc = withService({+ serviceName: 'three.ws Datapoints',+ tags: ['crypto', 'market-data', 'datapoint', 'x402'],+ });++ const push = (family, id, metric, exampleValue) => {+ const familyDef = DATAPOINT_FAMILIES[family];+ const metricDef = familyDef.metrics[metric];+ const priceAtomics = datapointPriceFor(`datapoint-${family}`, DATAPOINT_DEFAULT_ATOMICS);+ const path =+ id != null+ ? `/api/x402/d/${family}/${encodeURIComponent(id)}/${metric}`+ : `/api/x402/d/${family}/${metric}`;+ const url = `${origin}${path}`;+ const accepts = acceptsForPrice(priceAtomics, url);+ items.push({+ path,+ url,+ method: 'GET',+ description: datapointDescription({ family, metric, priceAtomics }),+ mimeType: 'application/json',+ serviceName: svc.serviceName,+ tags: [...svc.tags.slice(0, 4), family].slice(0, 5),+ iconUrl: svc.iconUrl,+ accepts,+ extensions: extensionsForAccepts(accepts, {+ method: 'GET',+ discoverable: true,+ input: {},+ inputSchema: { type: 'object', properties: {} },+ output: {+ example: {+ family,+ ...(id != null ? { id } : {}),+ metric,+ label: metricDef.label,+ unit: metricDef.unit,+ value: exampleValue,+ as_of: '2026-07-11T00:00:00.000Z',+ source: 'three.ws market-data',+ },+ },+ }),+ });+ };++ // Every metric of the no-id families — static, always present.+ for (const family of ['global', 'fear-greed', 'gas']) {+ for (const metric of Object.keys(DATAPOINT_FAMILIES[family].metrics)) {+ push(family, null, metric, metric === 'label' ? 'Greed' : 42.5);+ }+ }++ // Top coins × headline metrics — ids resolved from the live cached table.+ try {+ const { rows } = await fetchMarketsTable({ page: 1, perPage: 20, category: '' });+ for (const row of rows) {+ for (const metric of ['price', 'market-cap', 'change-24h']) {+ push('coin', row.id, metric, metric === 'price' ? row.price : 42.5);+ }+ }+ } catch (err) {+ console.error('[wk/x402-discovery] datapoint coin slice unavailable', err?.message || err);+ }++ // Top protocols by TVL × tvl — same runtime derivation.+ try {+ const { protocols } = await buildProtocols();+ for (const p of protocols.slice(0, 10)) {+ if (p.slug) push('protocol', p.slug, 'tvl', p.tvl);+ }+ } catch (err) {+ console.error('[wk/x402-discovery] datapoint protocol slice unavailable', err?.message || err);+ }++ return items;+}+// ── output.example backfill ──────────────────────────────────────────────────// Indexers (agentic.market / x402scan) render and rank a resource by its// response example. A resource with no `bazaar.info.output.example` still@@ -1446,6 +1543,7 @@ async function handleX402Discovery(req, res) {// Agent-published paid services — dynamic, one entry per active listing.const agentServiceItems = await buildAgentServiceItems(origin);+ const datapointItems = await buildDatapointItems(origin);return json(res,@@ -1542,6 +1640,11 @@ async function handleX402Discovery(req, res) {// Agent-published paid endpoints (monetize_endpoint). Dynamic —// one entry per active agent_paid_services listing....agentServiceItems,+ // Datapoint fabric (/api/x402/d/…): a curated, runtime-derived+ // slice of the 400k+ addressable single-datapoint endpoints, so+ // indexers surface the fabric; the full id space is enumerated+ // free at /api/x402/d.+ ...datapointItems,].filter(Boolean).map(addOutputExample),diff --git a/api/x402/d/[...path].js b/api/x402/d/[...path].jsnew file mode 100644index 000000000..c2ccf7e4a--- /dev/null+++ b/api/x402/d/[...path].js@@ -0,0 +1,127 @@+// GET /api/x402/d/<family>/<id>/<metric> (and /d/<family>/<metric> for the+// no-id families: global, fear-greed, gas) — the datapoint fabric.+//+// Hundreds of thousands of standalone paid endpoints served by this ONE+// route: every (family, id, metric) triple from the registry+// (api/_lib/market-data/datapoints.js) is its own individually addressable,+// individually priced x402 resource. $0.0005 USDC per datapoint by default+// (X402_PRICE_DATAPOINT_<FAMILY> to override per family), USDC on Solana or+// Base. Free catalog: GET /api/x402/d.+//+// Flow: the path is parsed and validated BEFORE any 402 — a resource that+// cannot exist (unknown family/metric, malformed id) answers 404/422 without+// ever asking for payment. A valid path gets the standard paid-endpoint dance+// from a per-(family,metric) instance; the concrete resource URL (with the+// id) is baked into the challenge via resourceUrlBuilder. Unknown ids and+// upstream outages throw AFTER verify but BEFORE settle — never charged.++import { paidEndpoint } from '../../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../../_lib/x402-spec.js';+import { installAccessControl } from '../../_lib/x402/access-control.js';+import { withService } from '../../_lib/x402/bazaar-helpers.js';+import { priceFor } from '../../_lib/x402-prices.js';+import { env } from '../../_lib/env.js';+import {+ DATAPOINT_FAMILIES,+ DATAPOINT_DEFAULT_ATOMICS,+ datapointDescription,+ parseDatapointPath,+ readDatapoint,+} from '../../_lib/market-data/datapoints.js';++const PREFIX = '/api/x402/d/';++// One paidEndpoint instance per (family, metric) — ~50 total, built lazily.+// The id varies per request and reaches the handler through req.url; the+// challenge's resource URL tracks the actual request path.+const _instances = new Map();++function instanceFor(parsed) {+ const key = `${parsed.family}/${parsed.metric}`;+ let inst = _instances.get(key);+ if (inst) return inst;++ const { family, metric, metricDef, familyDef } = parsed;+ const origin = env.APP_ORIGIN || 'https://three.ws';+ const routePattern = familyDef.describeId+ ? `${PREFIX}${family}/{id}/${metric}`+ : `${PREFIX}${family}/${metric}`;+ const priceAtomics = priceFor(`datapoint-${family}`, DATAPOINT_DEFAULT_ATOMICS);+ const description = datapointDescription({ family, metric, priceAtomics });+ const inputSchema = { type: 'object', properties: {} };++ inst = paidEndpoint({+ route: routePattern,+ method: 'GET',+ priceAtomics,+ networks: ['solana', 'base'],+ description,+ resourceUrlBuilder: (req) => `${origin}${(req.url || routePattern).split('?')[0]}`,+ bazaar: {+ description,+ useCases: ['single-value agent reads', 'spreadsheet/oracle feeds', 'micro-billing per datapoint'],+ input: { type: 'query', example: {}, schema: inputSchema },+ output: {+ type: 'json',+ example: {+ family,+ ...(familyDef.describeId ? { id: '<id>' } : {}),+ metric,+ label: metricDef.label,+ unit: metricDef.unit,+ value: 12345.67,+ as_of: '2026-07-11T00:00:00.000Z',+ source: 'three.ws market-data',+ },+ },+ schema: buildBazaarSchema({ method: 'GET', queryParamsSchema: inputSchema }),+ },+ service: withService({+ serviceName: 'three.ws Datapoints',+ tags: ['crypto', 'market-data', 'datapoint', family],+ }),+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),+ async handler({ req }) {+ const segments = (req.url || '')+ .split('?')[0]+ .slice(PREFIX.length)+ .split('/')+ .filter(Boolean);+ return readDatapoint(parseDatapointPath(segments));+ },+ });+ _instances.set(key, inst);+ return inst;+}++function sendJson(res, status, obj) {+ res.statusCode = status;+ if (typeof res.setHeader === 'function') {+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('access-control-allow-origin', '*');+ }+ res.end(JSON.stringify(obj));+}++export default async function handler(req, res) {+ const pathname = (req.url || '').split('?')[0];+ const segments = pathname.startsWith(PREFIX)+ ? pathname.slice(PREFIX.length).split('/').filter(Boolean)+ : [];++ // Validate the path shape BEFORE issuing a 402 — nobody should be asked to+ // pay for a resource that cannot exist.+ let parsed;+ try {+ parsed = parseDatapointPath(segments);+ } catch (err) {+ return sendJson(res, err.status || 404, {+ error: err.code || 'not_found',+ message: err.message,+ catalog: '/api/x402/d',+ families: Object.keys(DATAPOINT_FAMILIES),+ });+ }++ return instanceFor(parsed)(req, res);+}diff --git a/api/x402/d/index.js b/api/x402/d/index.jsnew file mode 100644index 000000000..9eb336630--- /dev/null+++ b/api/x402/d/index.js@@ -0,0 +1,165 @@+// GET /api/x402/d — FREE catalog of the datapoint fabric.+//+// Enumerates every family and metric of the 400,000+ standalone paid+// datapoint endpoints served by /api/x402/d/<family>/<id>/<metric>, with+// prices, id guidance, and runnable example URLs. For the DeFiLlama-backed+// families it can also expand the live id space page by page+// (?family=pool&ids=1&page=2), so a crawler or agent can walk the entire+// endpoint universe without guessing. Discovery costs nothing; each datapoint+// costs a fraction of a cent.++import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { env } from '../../_lib/env.js';+import { priceFor } from '../../_lib/x402-prices.js';+import {+ DATAPOINT_FAMILIES,+ DATAPOINT_DEFAULT_ATOMICS,+ datapointEndpointCount,+ allProtocols,+ allChains,+ allStablecoins,+} from '../../_lib/market-data/datapoints.js';+import { loadYieldPools } from '../../defi/yields.js';+import { buildExchanges } from '../../coin/exchanges.js';++const PAGE_SIZE = 200;++const usd = (atomics) => {+ const n = Number(atomics) / 1_000_000;+ return `$${n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')}`;+};++// Live id enumeration per family, for crawlers that want concrete URLs.+// Each returns the full id list (from the same cached full-set feeds the+// paid route resolves against); coin ids live upstream at CoinGecko scale+// (~17k) and are resolved at runtime instead — use /api/x402/market-coins?q=.+// Each reads the SAME cached full-set feed the paid route resolves against,+// so every id listed here is guaranteed addressable.+const ID_SOURCES = {+ pool: async () => (await loadYieldPools()).pools.map((p) => p.pool),+ exchange: async () => (await buildExchanges()).exchanges.map((e) => e.id),+ protocol: async () => [...(await allProtocols()).keys()],+ chain: async () => [...(await allChains()).values()].map((c) => c.name),+ stablecoin: async () => {+ // The stablecoin map keys ids AND symbols to the same rows — enumerate+ // each row once by its canonical numeric id.+ const seen = new Set();+ const ids = [];+ for (const [key, row] of (await allStablecoins()).entries()) {+ if (seen.has(row)) continue;+ seen.add(row);+ ids.push(/^\d+$/.test(key) ? key : row.symbol || key);+ }+ return ids;+ },+};++function familySummary(origin, slug, def) {+ const price = priceFor(`datapoint-${slug}`, DATAPOINT_DEFAULT_ATOMICS);+ const needsId = def.describeId != null;+ const metricSlugs = Object.keys(def.metrics);+ return {+ family: slug,+ price_usdc: usd(price),+ id: needsId ? def.describeId : null,+ id_count_approx: def.approxCount,+ endpoint_pattern: needsId+ ? `${origin}/api/x402/d/${slug}/{id}/{metric}`+ : `${origin}/api/x402/d/${slug}/{metric}`,+ metrics: Object.fromEntries(+ metricSlugs.map((k) => [k, `${def.metrics[k].label} (${def.metrics[k].unit})`]),+ ),+ endpoint_count_approx: def.approxCount * metricSlugs.length,+ ...(ID_SOURCES[slug] ? { expand_ids: `${origin}/api/x402/d?family=${slug}&ids=1` } : {}),+ };+}++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.apiIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const origin = env.APP_ORIGIN || 'https://three.ws';+ const params = new URL(req.url, 'http://x').searchParams;+ const family = (params.get('family') || '').trim();++ // Id-expansion mode: page through a family's live id space.+ if (family && params.get('ids')) {+ const def = DATAPOINT_FAMILIES[family];+ if (!def) return error(res, 404, 'unknown_family', `unknown family "${family}"`);+ const source = ID_SOURCES[family];+ if (!source) {+ return error(+ res,+ 400,+ 'no_id_expansion',+ family === 'coin'+ ? 'coin ids are resolved at runtime — any CoinGecko id or Solana mint works; find ids via /api/x402/market-coins?q=<text>'+ : `family "${family}" has no id expansion`,+ );+ }+ try {+ const ids = await source();+ const page = Math.max(1, Number.parseInt(params.get('page') || '1', 10) || 1);+ const start = (page - 1) * PAGE_SIZE;+ const metrics = Object.keys(def.metrics);+ return json(+ res,+ 200,+ {+ family,+ page,+ page_size: PAGE_SIZE,+ total_ids: ids.length,+ total_pages: Math.ceil(ids.length / PAGE_SIZE),+ metrics,+ endpoints: ids.slice(start, start + PAGE_SIZE).map((id) => ({+ id,+ urls: metrics.map(+ (metric) => `${origin}/api/x402/d/${family}/${encodeURIComponent(id)}/${metric}`,+ ),+ })),+ },+ { 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1800' },+ );+ } catch {+ return error(res, 502, 'upstream_error', 'id catalog is unavailable right now — retry shortly');+ }+ }++ // Single-family detail.+ if (family) {+ const def = DATAPOINT_FAMILIES[family];+ if (!def) return error(res, 404, 'unknown_family', `unknown family "${family}"`);+ return json(res, 200, familySummary(origin, family, def), {+ 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1800',+ });+ }++ // Front door.+ return json(+ res,+ 200,+ {+ name: 'three.ws Datapoints',+ description:+ 'The datapoint fabric: every market datapoint three.ws aggregates, as its own standalone x402 ' ++ 'endpoint. One URL = one value = one micro-payment. No API key, no subscription — request a ' ++ 'datapoint, get its 402 challenge, pay a fraction of a cent in USDC (Solana or Base), get the value.',+ endpoint_count_approx: datapointEndpointCount(),+ how_to_pay:+ 'GET any datapoint URL without payment to receive its 402 challenge, then retry with an ' ++ 'X-PAYMENT header per the x402 v2 spec — any x402 client SDK automates this.',+ example: `${origin}/api/x402/d/global/btc-dominance`,+ category_api: `${origin}/api/x402/market`,+ docs: `${origin}/docs/market-data-api`,+ families: Object.entries(DATAPOINT_FAMILIES).map(([slug, def]) =>+ familySummary(origin, slug, def),+ ),+ },+ { 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1800' },+ );+});diff --git a/api/x402/market.js b/api/x402/market.jsindex 9a2696e94..df9af4353 100644--- a/api/x402/market.js+++ b/api/x402/market.js@@ -39,6 +39,11 @@ export default wrap(async (req, res) => {'Retry with an X-PAYMENT header per the x402 v2 spec, or use any x402 client SDK.',docs: `${origin}/docs/market-data-api`,discovery: `${origin}/.well-known/x402.json`,+ datapoints: {+ description:+ '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,diff --git a/data/changelog.json b/data/changelog.jsonindex 0d94911f8..cf665c5db 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-11",+ "title": "The datapoint fabric: 480,000+ standalone paid endpoints",+ "summary": "Every individual market datapoint three.ws aggregates is now its own standalone paid endpoint — one URL, one value, one micro-payment of $0.0005 USDC over x402. Bitcoin's spot price, Lido's TVL, one yield pool's APY, USDT's peg deviation in basis points, BTC dominance, the standard gas tier — each of roughly 484,000 combinations of ~17,500 coins, ~15,500 yield pools, ~6,000 protocols, plus chains, stablecoins, exchanges, and the global market gauges, across 68 metrics, is individually addressable and individually buyable by any agent with a wallet. A free catalog at /api/x402/d lists every family and metric with prices and can page through each family's entire live id space, so a crawler can walk the whole endpoint universe. Asking for a datapoint that doesn't exist never triggers a payment request, and a failed fetch never charges the buyer.",+ "tags": [+ "feature"+ ],+ "link": "/docs/market-data-api"+ },{"date": "2026-07-11","title": "The Market Data API: every market feed, now buyable per call",@@ -13141,4 +13150,4 @@"link": "/docs/agent-shell"}]-}\ No newline at end of file+}diff --git a/docs/market-data-api.md b/docs/market-data-api.mdindex 49416dca3..0d99dda91 100644--- a/docs/market-data-api.md+++ b/docs/market-data-api.md@@ -35,6 +35,34 @@ The browser pages (`/coins`, `/yields`, `/gas`, …) stay free for humans, withFull per-endpoint parameter docs are in the free index (`/api/x402/market`) and in each endpoint's discovery listing.+## The datapoint fabric — 480,000+ standalone endpoints++Beyond the 17 category endpoints, **every individual datapoint is its own paid endpoint**: one URL, one value, one micro-payment. The fabric at `/api/x402/d/<family>/<id>/<metric>` makes every (family, id, metric) triple individually addressable — ~17,500 coins × 20 metrics, ~15,500 yield pools × 7, ~6,000 protocols × 6, plus chains, stablecoins, exchanges, and the no-id global/gas/fear-greed families. **$0.0005 USDC per datapoint** (override per family with `X402_PRICE_DATAPOINT_<FAMILY>`).++```bash+# Free catalog: families, metrics, prices, live endpoint count+curl -s https://three.ws/api/x402/d++# Walk a family's entire live id space, 200 ids per page+curl -s "https://three.ws/api/x402/d?family=pool&ids=1&page=2"++# Each datapoint is one paid GET → one machine-readable value+curl -s https://three.ws/api/x402/d/coin/bitcoin/price # → 402 challenge+curl -s https://three.ws/api/x402/d/protocol/lido/tvl+curl -s https://three.ws/api/x402/d/stablecoin/usdt/peg-deviation-bps+curl -s https://three.ws/api/x402/d/global/btc-dominance+```++A paid datapoint response is one value with provenance:++```json+{ "family": "coin", "id": "bitcoin", "metric": "price",+ "label": "Spot price", "unit": "usd", "value": 64149,+ "as_of": "2026-07-11T22:50:00.000Z", "source": "three.ws market-data" }+```++Families: `coin` (id = CoinGecko id or Solana mint), `protocol` (DeFiLlama slug), `chain` (chain name), `pool` (DeFiLlama pool uuid), `stablecoin` (DeFiLlama id or symbol), `exchange` (CoinGecko exchange id), and the id-less `global`, `fear-greed`, `gas`. A path that cannot exist (unknown family or metric, malformed id) answers 404/422 **without** issuing a payment challenge; unknown ids and upstream outages reject after verification but before settlement, so a buyer is never charged for anything but a delivered value. The public discovery doc lists a curated live slice (all global/gas/fear-greed metrics, top coins × headline metrics, top protocols × TVL); the free catalog at `/api/x402/d` enumerates everything else.+## Buying a callAny x402 client works. The raw exchange:diff --git a/tests/market-datapoints.test.js b/tests/market-datapoints.test.jsnew file mode 100644index 000000000..d7545c421--- /dev/null+++ b/tests/market-datapoints.test.js@@ -0,0 +1,239 @@+// Datapoint fabric (/api/x402/d/…) — registry, parsing, extractor, and+// payment-boundary guards. All offline: extractors run against real-shaped+// fixture rows; the 402 checks drive the actual dynamic route with a fake res.++import { describe, it, expect } from 'vitest';++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 {+ DATAPOINT_FAMILIES,+ DATAPOINT_DEFAULT_ATOMICS,+ datapointDescription,+ parseDatapointPath,+ datapointEndpointCount,+} = await import('../api/_lib/market-data/datapoints.js');++function expectThrow(fn, { status, code }) {+ let err;+ try {+ fn();+ } catch (e) {+ err = e;+ }+ expect(err, 'expected a throw').toBeTruthy();+ expect(err.status).toBe(status);+ expect(err.code).toBe(code);+}++// ── Registry invariants ─────────────────────────────────────────────────────+describe('datapoint registry', () => {+ it('spans hundreds of thousands of addressable endpoints', () => {+ expect(datapointEndpointCount()).toBeGreaterThan(300_000);+ });++ it('every family and metric carries complete listing metadata', () => {+ for (const [family, def] of Object.entries(DATAPOINT_FAMILIES)) {+ expect(family).toMatch(/^[a-z-]+$/);+ expect(typeof def.row).toBe('function');+ expect(def.approxCount).toBeGreaterThan(0);+ if (def.describeId != null) expect(typeof def.validateId).toBe('function');+ const metrics = Object.entries(def.metrics);+ expect(metrics.length, `${family} metrics`).toBeGreaterThanOrEqual(2);+ for (const [slug, metricDef] of metrics) {+ expect(slug, `${family}/${slug}`).toMatch(/^[a-z0-9-]+$/);+ expect(metricDef.label.length).toBeGreaterThan(3);+ expect(metricDef.unit.length).toBeGreaterThan(0);+ expect(typeof metricDef.extract).toBe('function');+ // Discovery-listing quality: descriptions must clear the ≥60-char+ // bar every other cataloged service meets.+ const description = datapointDescription({+ family,+ metric: slug,+ priceAtomics: DATAPOINT_DEFAULT_ATOMICS,+ });+ expect(description.length, `${family}/${slug} description`).toBeGreaterThanOrEqual(60);+ }+ }+ });+});++// ── Path parsing / payment boundary ─────────────────────────────────────────+describe('parseDatapointPath', () => {+ it('parses id-family and no-id-family paths', () => {+ const coin = parseDatapointPath(['coin', 'bitcoin', 'price']);+ expect(coin.family).toBe('coin');+ expect(coin.id).toBe('bitcoin');+ expect(coin.metric).toBe('price');+ const global = parseDatapointPath(['global', 'btc-dominance']);+ expect(global.id).toBeNull();+ expect(global.metric).toBe('btc-dominance');+ });++ it('url-decodes ids (chain names with spaces)', () => {+ const parsed = parseDatapointPath(['chain', 'Arbitrum%20Nova', 'tvl']);+ expect(parsed.id).toBe('Arbitrum Nova');+ });++ it('404s an unknown family, metric, or path shape — never a 402 for a non-resource', () => {+ expectThrow(() => parseDatapointPath(['weather', 'nyc', 'temp']), {+ status: 404,+ code: 'unknown_family',+ });+ expectThrow(() => parseDatapointPath(['coin', 'bitcoin', 'vibes']), {+ status: 404,+ code: 'unknown_metric',+ });+ expectThrow(() => parseDatapointPath(['coin', 'bitcoin']), { status: 404, code: 'bad_path' });+ expectThrow(() => parseDatapointPath(['global', 'x', 'btc-dominance']), {+ status: 404,+ code: 'bad_path',+ });+ });++ it('422s a malformed id per family', () => {+ expectThrow(() => parseDatapointPath(['coin', 'NOT A SLUG!', 'price']), {+ status: 422,+ code: 'invalid_id',+ });+ expectThrow(() => parseDatapointPath(['pool', 'not-a-uuid', 'apy']), {+ status: 422,+ code: 'invalid_id',+ });+ expectThrow(() => parseDatapointPath(['protocol', 'Bad Slug', 'tvl']), {+ status: 422,+ code: 'invalid_id',+ });+ });+});++// ── Extractors against real-shaped rows ─────────────────────────────────────+describe('metric extractors', () => {+ it('coin metrics read the buildCoinDetail shape', () => {+ const coin = {+ rank: 1,+ market: {+ price: 64346, market_cap: 1.2e12, fdv: 1.3e12, volume_24h: 3.8e10,+ change_pct: { h24: 1.42, d7: 4.87, d30: 9.1, y1: 55.2 },+ ath: 126789, ath_change_pct: -49.2, atl: 67.81,+ high_24h: 65000, low_24h: 63000,+ circulating: 19_700_000, total: 21_000_000, max: 21_000_000,+ mcap_fdv_ratio: 0.94,+ },+ sentiment: { up_pct: 82.5, watchlist_users: 1_600_000 },+ };+ const metrics = DATAPOINT_FAMILIES.coin.metrics;+ expect(metrics.price.extract(coin)).toBe(64346);+ expect(metrics['change-7d'].extract(coin)).toBe(4.87);+ expect(metrics['max-supply'].extract(coin)).toBe(21_000_000);+ expect(metrics['sentiment-up'].extract(coin)).toBe(82.5);+ });++ it('stablecoin peg deviation converts price to basis points', () => {+ const metrics = DATAPOINT_FAMILIES.stablecoin.metrics;+ expect(metrics['peg-deviation-bps'].extract({ price: 0.9992 })).toBe(-8);+ expect(metrics['peg-deviation-bps'].extract({ price: 1.0031 })).toBe(31);+ expect(metrics['peg-deviation-bps'].extract({ price: null })).toBeNull();+ });++ it('gas metrics read the buildGasReport tier order', () => {+ const gas = {+ base_fee_gwei: 0.077,+ eth_price_usd: 3251.7,+ tiers: [+ { key: 'slow', gas_price_gwei: 0.08 },+ { key: 'standard', gas_price_gwei: 0.1 },+ { key: 'fast', gas_price_gwei: 0.15 },+ ],+ };+ const metrics = DATAPOINT_FAMILIES.gas.metrics;+ expect(metrics.slow.extract(gas)).toBe(0.08);+ expect(metrics.standard.extract(gas)).toBe(0.1);+ expect(metrics.fast.extract(gas)).toBe(0.15);+ expect(metrics['eth-price'].extract(gas)).toBe(3251.7);+ });++ it('global dominance metrics read the failover shape', () => {+ const g = {+ market_cap_usd: 3.9e12, volume_24h_usd: 1.5e11,+ market_cap_change_pct_24h: 0.7, active_coins: 17505,+ dominance: [{ symbol: 'BTC', pct: 56.2 }, { symbol: 'ETH', pct: 12.1 }],+ };+ const metrics = DATAPOINT_FAMILIES.global.metrics;+ expect(metrics['btc-dominance'].extract(g)).toBe(56.2);+ expect(metrics['eth-dominance'].extract(g)).toBe(12.1);+ expect(metrics['active-coins'].extract(g)).toBe(17505);+ });+});++// ── Live 402 boundary on the dynamic route ──────────────────────────────────+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;+ },+ };+}++const route = (await import('../api/x402/d/[...path].js')).default;++async function drive(url) {+ const res = fakeRes();+ await route({ method: 'GET', url, headers: { host: 'three.ws' } }, res);+ return res;+}++describe('dynamic datapoint route', () => {+ it('issues a 402 whose resource URL is the concrete datapoint', async () => {+ const res = await drive('/api/x402/d/global/btc-dominance');+ expect(res.statusCode).toBe(402);+ const body = JSON.parse(res.body);+ expect(body.resource.url).toBe('https://three.ws/api/x402/d/global/btc-dominance');+ const usdc = body.accepts.filter((a) =>+ [process.env.X402_ASSET_MINT_SOLANA, process.env.X402_ASSET_ADDRESS_BASE].includes(a.asset),+ );+ expect(usdc.length).toBeGreaterThan(0);+ expect(usdc.every((a) => (a.amount ?? a.maxAmountRequired) === DATAPOINT_DEFAULT_ATOMICS)).toBe(true);+ });++ it('two ids of one (family, metric) advertise their own resource URLs', async () => {+ const a = JSON.parse((await drive('/api/x402/d/coin/bitcoin/price')).body);+ const b = JSON.parse((await drive('/api/x402/d/coin/ethereum/price')).body);+ expect(a.resource.url).toContain('/coin/bitcoin/price');+ expect(b.resource.url).toContain('/coin/ethereum/price');+ });++ it('404s garbage paths without issuing a payment challenge', async () => {+ const res = await drive('/api/x402/d/weather/nyc/temp');+ expect(res.statusCode).toBe(404);+ const body = JSON.parse(res.body);+ expect(body.error).toBe('unknown_family');+ expect(body.catalog).toBe('/api/x402/d');+ });++ it('422s a malformed id before payment', async () => {+ const res = await drive('/api/x402/d/pool/not-a-uuid/apy');+ expect(res.statusCode).toBe(422);+ expect(JSON.parse(res.body).error).toBe('invalid_id');+ });+});diff --git a/tests/service-catalog.test.js b/tests/service-catalog.test.jsindex d7becac8f..738726162 100644--- a/tests/service-catalog.test.js+++ b/tests/service-catalog.test.js@@ -173,7 +173,11 @@ describe('no drift: live discovery doc ⇄ catalog', () => {.filter((r) => !catalogPaths.has(r.path))// agent-published listings are dynamic rows from agent_paid_services,// cataloged per-listing by design.- .filter((r) => !r.path.startsWith('/api/x402/service/'));+ .filter((r) => !r.path.startsWith('/api/x402/service/'))+ // datapoint-fabric entries are a runtime-derived slice of the 400k++ // dynamic (family, id, metric) endpoints — registry-driven, not+ // service-catalog descriptors (see api/_lib/market-data/datapoints.js).+ .filter((r) => !r.path.startsWith('/api/x402/d/'));expect(rogue.map((r) => r.path)).toEqual([]);});});diff --git a/tests/x402-ring-catalog.test.js b/tests/x402-ring-catalog.test.jsindex 42fef8978..736b87162 100644--- a/tests/x402-ring-catalog.test.js+++ b/tests/x402-ring-catalog.test.js@@ -137,7 +137,11 @@ function paidEndpointSites() {// api/_lib/aggregator.js builds the dynamic /api/v1/x/<provider>/<endpoint>// API-aggregator proxy family per descriptor — a separate product surface, not// a fixed ring endpoint.-const SITE_ALLOWLIST = new Set(['api/_lib/aggregator.js']);+// api/x402/d/[...path].js is the datapoint fabric — 400k+ dynamic+// (family, id, metric) endpoints from one route; ids are runtime values, so+// no fixed catalog path can resolve to it. Its payment rail is the same+// paidEndpoint wrapper the rotated market-data family already settles hourly.+const SITE_ALLOWLIST = new Set(['api/_lib/aggregator.js', 'api/x402/d/[...path].js']);describe('ring-catalog covers 100% of paid endpoints', () => {it('every paidEndpoint( construction site is in the catalog', () => {