Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: add x402 directory registration scripts and guest agent functionality

fudjiaf5e76c1f61a3
diff --git a/api/_lib/market-data/endpoint.js b/api/_lib/market-data/endpoint.js
new file mode 100644
index 000000000..3e602ec00
--- /dev/null
+++ b/api/_lib/market-data/endpoint.js
@@ -0,0 +1,60 @@
+// Market Data API endpoint factory — builds each live /api/x402/market-*
+// paidEndpoint from its registry entry (./registry.js) and fetcher (./fetch.js).
+//
+// The thin route files in api/x402/market-*.js are one line each:
+// export default marketEndpoint('market-coins');
+//
+// The 402 challenge, bazaar discovery block, pricing (env-overridable via
+// X402_PRICE_MARKET_<CATEGORY>), and access-control bypass all follow the
+// standard paid-endpoint rail (api/_lib/x402-paid-endpoint.js) — identical to
+// token-intel and the other cataloged services, so facilitators see one
+// consistent contract across the whole storefront.
+
+import { paidEndpoint } from '../x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../x402-spec.js';
+import { installAccessControl } from '../x402/access-control.js';
+import { withService } from '../x402/bazaar-helpers.js';
+import { priceFor } from '../x402-prices.js';
+import { MARKET_CATEGORY_BY_SLUG, MARKET_SERVICE_NAME } from './registry.js';
+import { MARKET_FETCHERS } from './fetch.js';
+
+// Registry and fetchers must cover exactly the same slugs — a mismatch is a
+// wiring bug that should fail at module load (deploy time), not at request time.
+for (const slug of MARKET_CATEGORY_BY_SLUG.keys()) {
+ if (typeof MARKET_FETCHERS[slug] !== 'function') {
+ throw new Error(`market-data: registry entry "${slug}" has no fetcher`);
+ }
+}
+for (const slug of Object.keys(MARKET_FETCHERS)) {
+ if (!MARKET_CATEGORY_BY_SLUG.has(slug)) {
+ throw new Error(`market-data: fetcher "${slug}" has no registry entry`);
+ }
+}
+
+export function marketEndpoint(slug) {
+ const entry = MARKET_CATEGORY_BY_SLUG.get(slug);
+ if (!entry) throw new Error(`market-data: unknown category "${slug}"`);
+ const fetcher = MARKET_FETCHERS[slug];
+ const route = `/api/x402/${slug}`;
+
+ return paidEndpoint({
+ route,
+ method: 'GET',
+ priceAtomics: priceFor(slug, entry.priceAtomics),
+ networks: ['solana', 'base'],
+ description: entry.description,
+ bazaar: {
+ description: entry.description,
+ useCases: entry.useCases,
+ input: { type: 'query', example: entry.inputExample, schema: entry.inputSchema },
+ output: { type: 'json', example: entry.outputExample },
+ schema: buildBazaarSchema({ method: 'GET', queryParamsSchema: entry.inputSchema }),
+ },
+ service: withService({ serviceName: MARKET_SERVICE_NAME, tags: entry.tags }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ async handler({ req }) {
+ const params = new URL(req.url, 'http://x').searchParams;
+ return fetcher(params);
+ },
+ });
+}
diff --git a/api/_lib/market-data/fetch.js b/api/_lib/market-data/fetch.js
new file mode 100644
index 000000000..ca2d253a6
--- /dev/null
+++ b/api/_lib/market-data/fetch.js
@@ -0,0 +1,267 @@
+// Market Data API fetchers — one per registry slug (see ./registry.js).
+//
+// Each fetcher takes the request's URLSearchParams and returns the JSON body
+// the paid endpoint sells. They delegate to the SAME exported builders the
+// free /markets pages run on (api/coin/*, api/defi/*) — one implementation,
+// two surfaces, zero drift. Builders keep their own in-memory caches, so a
+// paid call is usually served warm.
+//
+// Error contract (enforced by api/_lib/x402-paid-endpoint.js ordering —
+// verify → handler → settle — so a failed call never charges the buyer):
+// • invalid params → throw { status: 422, code: 'invalid_<param>' }
+// • upstream outage → throw { status: 503, code: 'data_unavailable' }
+
+import { fetchGlobalMarket, fetchMarketsTable } from '../market-fallbacks.js';
+import { isPlausibleCoinId } from '../coingecko.js';
+import { searchCoins } from '../../coin/markets.js';
+import { buildCoinDetail, MINT_RE } from '../../coin/detail.js';
+import { buildPriceChart, VALID_DAYS } from '../../coin/ohlc.js';
+import { buildCategories } from '../../coin/categories.js';
+import { buildExchanges } from '../../coin/exchanges.js';
+import { buildDerivativeTickers, buildDerivativeExchanges } from '../../coin/derivatives.js';
+import { fetchFearGreed } from '../../coin/global.js';
+import { buildGasReport } from '../../coin/gas.js';
+import { buildTrending } from '../../coin/trending.js';
+import { buildProtocols } from '../../defi/protocols.js';
+import { buildChains } from '../../defi/chains.js';
+import { queryYieldPools, queryYieldChart } from '../../defi/yields.js';
+import { buildStablecoins } from '../../defi/stablecoins.js';
+import { buildFees } from '../../defi/fees.js';
+import { buildDexVolumes } from '../../defi/dex-volumes.js';
+import { queryHacks } from '../../defi/hacks.js';
+
+const fail = (status, code, message) => {
+ throw Object.assign(new Error(message), { status, code });
+};
+
+const invalid = (code, message) => fail(422, code, message);
+
+// 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.
+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`);
+ }
+}
+
+function clampInt(raw, { def, min, max }) {
+ const n = Number.parseInt(raw ?? '', 10);
+ if (!Number.isFinite(n)) return def;
+ return Math.max(min, Math.min(max, n));
+}
+
+function parseBool(v) {
+ if (v == null) return undefined;
+ const s = String(v).toLowerCase();
+ if (s === 'true' || s === '1') return true;
+ if (s === 'false' || s === '0') return false;
+ return undefined;
+}
+
+export const MARKET_FETCHERS = {
+ 'market-coins': async (params) => {
+ const q = (params.get('q') || '').trim();
+ if (q) {
+ if (q.length > 64) invalid('invalid_query', 'q must be 64 characters or fewer');
+ return upstream('coin search', () => searchCoins(q));
+ }
+ const category = (params.get('category') || '').trim().toLowerCase();
+ if (category && !/^[a-z0-9-]{1,80}$/.test(category)) {
+ invalid('invalid_category', 'category must be a CoinGecko category id (lowercase slug)');
+ }
+ const page = clampInt(params.get('page'), { def: 1, min: 1, max: 20 });
+ const perPage = clampInt(params.get('per_page'), { def: 100, min: 10, max: 250 });
+ const { rows } = await upstream('coin market', () =>
+ fetchMarketsTable({ page, perPage, category }),
+ );
+ return { coins: rows, page, per_page: perPage, category: category || null };
+ },
+
+ 'market-coin': async (params) => {
+ const contract = (params.get('contract') || '').trim();
+ const id = (params.get('id') || '').trim().toLowerCase();
+ if (contract && !MINT_RE.test(contract)) {
+ invalid('invalid_contract', 'contract must be a base58 Solana address (32–44 chars)');
+ }
+ if (!contract && !isPlausibleCoinId(id)) {
+ invalid('invalid_id', 'id must be a CoinGecko coin id (lowercase slug)');
+ }
+ try {
+ return await buildCoinDetail({ id, contract });
+ } catch (err) {
+ if (err?.status === 404) fail(404, 'not_found', `no coin found for "${contract || id}"`);
+ fail(503, 'data_unavailable', 'live coin data is temporarily unavailable — retry shortly');
+ }
+ },
+
+ 'market-chart': async (params) => {
+ const id = (params.get('id') || '').trim().toLowerCase();
+ if (!isPlausibleCoinId(id)) {
+ invalid('invalid_id', 'id must be a CoinGecko coin id (lowercase slug)');
+ }
+ const days = Number.parseInt(params.get('days') || '30', 10);
+ if (!VALID_DAYS.has(days)) invalid('invalid_days', 'days must be one of 1, 7, 30, 90, 365');
+ let payload;
+ try {
+ payload = await buildPriceChart(id, days);
+ } catch (err) {
+ if (err?.status === 404) fail(404, 'not_found', `no coin with id "${id}"`);
+ fail(503, 'data_unavailable', 'live chart data is temporarily unavailable — retry shortly');
+ }
+ if (!payload.data.length) {
+ fail(503, 'data_unavailable', 'no price history for this coin right now — retry shortly');
+ }
+ return payload;
+ },
+
+ 'market-categories': () => upstream('sector', () => buildCategories()),
+
+ 'market-exchanges': () => upstream('exchange', () => buildExchanges()),
+
+ 'market-derivatives': async (params) => {
+ const view = (params.get('view') || '').trim().toLowerCase();
+ if (view && view !== 'exchanges') {
+ invalid('invalid_view', "view must be 'exchanges' or omitted");
+ }
+ return upstream('derivatives', () =>
+ view === 'exchanges' ? buildDerivativeExchanges() : buildDerivativeTickers(),
+ );
+ },
+
+ 'market-global': async () => {
+ const [globalResult, fngResult] = await Promise.allSettled([
+ fetchGlobalMarket(),
+ fetchFearGreed(),
+ ]);
+ const market = globalResult.status === 'fulfilled' ? globalResult.value : null;
+ const fear_greed = fngResult.status === 'fulfilled' ? fngResult.value : null;
+ if (!market && !fear_greed) {
+ fail(503, 'data_unavailable', 'live global market data is temporarily unavailable — retry shortly');
+ }
+ return { market, fear_greed };
+ },
+
+ 'market-gas': () => upstream('gas', () => buildGasReport()),
+
+ 'market-trending': () => upstream('trending', () => buildTrending()),
+
+ 'market-defi': () => upstream('DeFi protocol', () => buildProtocols()),
+
+ 'market-chains': () => upstream('chain TVL', () => buildChains()),
+
+ 'market-yields': async (params) => {
+ const pool = (params.get('pool') || '').trim();
+ if (pool) {
+ try {
+ return await queryYieldChart(pool);
+ } catch (err) {
+ if (err?.status === 400) invalid('invalid_pool', err.message);
+ if (err?.status === 404) fail(404, 'pool_not_found', err.message);
+ fail(503, 'data_unavailable', 'live yield history is temporarily unavailable — retry shortly');
+ }
+ }
+ return upstream('yield pool', () =>
+ queryYieldPools({
+ chain: (params.get('chain') || '').trim().toLowerCase(),
+ project: (params.get('project') || '').trim().toLowerCase(),
+ stablecoin: parseBool(params.get('stablecoin')),
+ search: (params.get('search') || '').trim().toLowerCase(),
+ minTvl: Math.max(0, Number(params.get('minTvl')) || 0),
+ sort: params.get('sort') === 'apy' ? 'apy' : 'tvl',
+ limit: clampInt(params.get('limit'), { def: 100, min: 1, max: 200 }),
+ offset: clampInt(params.get('offset'), { def: 0, min: 0, max: 1_000_000 }),
+ }),
+ );
+ },
+
+ 'market-stablecoins': () => upstream('stablecoin', () => buildStablecoins()),
+
+ 'market-fees': async (params) => {
+ const type = params.get('type') === 'revenue' ? 'revenue' : 'fees';
+ return upstream('protocol fee', () => buildFees(type));
+ },
+
+ 'market-dex-volumes': () => upstream('DEX volume', () => buildDexVolumes()),
+
+ 'market-hacks': async (params) => {
+ return upstream('exploit', () =>
+ queryHacks({
+ search: (params.get('search') || '').trim().toLowerCase(),
+ limit: clampInt(params.get('limit'), { def: 100, min: 1, max: 200 }),
+ offset: clampInt(params.get('offset'), { def: 0, min: 0, max: Number.MAX_SAFE_INTEGER }),
+ }),
+ );
+ },
+
+ // The flagship bundle. Sections resolve independently (allSettled) so one
+ // upstream hiccup nulls its section instead of failing the whole call; only
+ // a total blackout refuses (and therefore never charges) the buyer.
+ 'market-pulse': async () => {
+ const [global, fng, coins, trending, gas, defi, stables, dex, fees] =
+ await Promise.allSettled([
+ fetchGlobalMarket(),
+ fetchFearGreed(),
+ fetchMarketsTable({ page: 1, perPage: 10, category: '' }),
+ buildTrending(),
+ buildGasReport(),
+ buildProtocols(),
+ buildStablecoins(),
+ buildDexVolumes(),
+ buildFees('fees'),
+ ]);
+ const ok = (r) => (r.status === 'fulfilled' ? r.value : null);
+
+ const topCoins = ok(coins)?.rows?.map(({ sparkline, ...row }) => row) ?? null;
+ const gasReport = ok(gas);
+ const standardTier = gasReport?.tiers?.find((t) => t.key === 'standard') ?? null;
+ const defiReport = ok(defi);
+ const stableReport = ok(stables);
+ const dexReport = ok(dex);
+ const feesReport = ok(fees);
+ const trendingReport = ok(trending);
+
+ const sections = {
+ global: ok(global),
+ fear_greed: ok(fng),
+ top_coins: topCoins,
+ trending: trendingReport
+ ? { coins: trendingReport.coins.slice(0, 7), categories: trendingReport.categories.slice(0, 5) }
+ : null,
+ gas: gasReport
+ ? {
+ standard_gwei: standardTier?.gas_price_gwei ?? null,
+ base_fee_gwei: gasReport.base_fee_gwei,
+ eth_price_usd: gasReport.eth_price_usd,
+ }
+ : null,
+ defi: defiReport
+ ? {
+ total_tvl: defiReport.total_tvl,
+ protocol_count: defiReport.protocol_count,
+ top_protocols: defiReport.protocols.slice(0, 10).map((p) => ({
+ slug: p.slug, name: p.name, category: p.category, tvl: p.tvl, change_7d: p.change_7d,
+ })),
+ }
+ : null,
+ stablecoins: stableReport
+ ? {
+ total_mcap: stableReport.total_mcap,
+ top: stableReport.stablecoins.slice(0, 5).map((s) => ({
+ symbol: s.symbol, name: s.name, price: s.price, circulating_usd: s.circulating_usd,
+ })),
+ }
+ : null,
+ dex: dexReport ? { total24h: dexReport.total24h, total7d: dexReport.total7d } : null,
+ fees: feesReport ? { total24h: feesReport.total24h, total7d: feesReport.total7d } : null,
+ };
+
+ if (Object.values(sections).every((v) => v == null)) {
+ fail(503, 'data_unavailable', 'live market data is temporarily unavailable — retry shortly');
+ }
+ return { ...sections, ts: new Date().toISOString() };
+ },
+};
diff --git a/api/_lib/market-data/registry.js b/api/_lib/market-data/registry.js
new file mode 100644
index 000000000..fb5949c8c
--- /dev/null
+++ b/api/_lib/market-data/registry.js
@@ -0,0 +1,396 @@
+// Market Data API registry — the single source of truth for the paid x402
+// market-data endpoint family (/api/x402/market-*).
+//
+// One entry per category. Everything derives from here so nothing drifts:
+// • api/_lib/service-catalog/services/market-data.js — projects each entry
+// into a paid-service descriptor for the unified catalog (and from there
+// the /.well-known/x402.json discovery doc + OKX storefront).
+// • api/_lib/market-data/endpoint.js — builds each live paidEndpoint (the
+// 402 challenge, bazaar block, and handler) from the same entry.
+// • api/x402/market.js — the free front-door index that lists the bundle.
+//
+// This file is PURE METADATA (no fetch imports) — the service-catalog barrel
+// loads it inside api/wk.js, so it must stay dependency-free. The fetch
+// implementations live in ./fetch.js, keyed by the same slug; endpoint.js
+// asserts at module load that every entry has a fetcher.
+//
+// The data behind every category is the exact payload the three.ws /markets
+// pages run on (api/coin/*, api/defi/* exported builders) — battle-tested
+// normalization, in-memory caching, and upstream failover included. The paid
+// surface exists for agents: machine-discoverable via the bazaar, no per-IP
+// rate limits, one USDC micro-payment per call on Solana or Base.
+
+export const MARKET_SERVICE_NAME = 'three.ws Market Data';
+
+// $0.001 USDC per category call; the pulse bundle aggregates seven categories
+// in one response and prices at $0.005. Ops override per endpoint via
+// X402_PRICE_MARKET_<CATEGORY> (see api/_lib/x402-prices.js).
+const LIST_PRICE = '1000';
+const PULSE_PRICE = '5000';
+
+const str = (description) => ({ type: 'string', description });
+
+export const MARKET_CATEGORIES = Object.freeze([
+ {
+ slug: 'market-coins',
+ title: 'Coin Markets',
+ useCase:
+ 'Ranked coin market table — price, market cap, 24h volume, 24h/7d change, and a 7-day sparkline for up to 250 coins per call, with sector scoping and coin-id search.',
+ description:
+ 'Ranked cryptocurrency market table for agents — pay $0.001 USDC per call. Returns price, market cap, 24h volume, 24h/7d percentage change, rank, logo, and a downsampled 7-day sparkline per coin (up to 250 per page). Scope to one sector with ?category=<coingecko-category-id>, page with ?page=&per_page=, or resolve names/tickers to coin ids with ?q=<text>. CoinGecko primary with CoinLore failover — the same feed behind three.ws/coins.',
+ tags: ['crypto', 'market-data', 'prices', 'coins'],
+ useCases: ['portfolio pricing', 'market screening', 'coin id resolution'],
+ priceAtomics: LIST_PRICE,
+ inputExample: { page: '1', per_page: '100' },
+ inputSchema: {
+ type: 'object',
+ properties: {
+ page: str('Page number, 1–20. Default 1.'),
+ per_page: str('Rows per page, 10–250. Default 100.'),
+ category: str('Optional CoinGecko category id (e.g. artificial-intelligence) to scope the table to one sector.'),
+ q: str('Search mode: resolve a name/ticker to CoinGecko coin ids (returns top-10 matches instead of the table).'),
+ },
+ },
+ outputExample: {
+ coins: [
+ {
+ id: 'bitcoin', symbol: 'BTC', name: 'Bitcoin', rank: 1,
+ price: 108234.12, change_24h: 1.42, change_7d: 4.87,
+ market_cap: 2140000000000, volume_24h: 38200000000,
+ sparkline: [106900.1, 107544.8, 108234.12],
+ },
+ ],
+ page: 1, per_page: 100, category: null,
+ },
+ },
+ {
+ slug: 'market-coin',
+ title: 'Coin Profile',
+ useCase:
+ 'Full profile for one coin by CoinGecko id or Solana contract — market stats, ATH/ATL, supply, links, developer and community metrics, sentiment, plain-text description.',
+ description:
+ 'Rich single-coin profile for agents — pay $0.001 USDC per call. Pass ?id=<coingecko-id> (e.g. bitcoin) or ?contract=<solana-mint>. Returns live market stats (price, cap, FDV, volume, 1h→1y change windows, ATH/ATL, supply), official links, per-chain contract addresses, developer activity, community size, sentiment votes, and a sanitized plain-text description. The id or contract is supplied at runtime — generic coin-agnostic plumbing, same data behind the three.ws/coin pages.',
+ tags: ['crypto', 'market-data', 'coin', 'due-diligence'],
+ useCases: ['token due-diligence', 'fundamental snapshot', 'agent research'],
+ priceAtomics: LIST_PRICE,
+ inputExample: { id: 'bitcoin' },
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: str('CoinGecko coin id (lowercase slug, e.g. bitcoin). Required unless contract is set.'),
+ contract: str('Solana token mint (base58) — alternative lookup key to id.'),
+ },
+ },
+ outputExample: {
+ coin: {
+ id: 'bitcoin', symbol: 'BTC', name: 'Bitcoin', rank: 1,
+ market: { price: 108234.12, market_cap: 2140000000000, ath: 126789.55 },
+ links: { homepage: 'https://bitcoin.org' },
+ },
+ },
+ },
+ {
+ slug: 'market-chart',
+ title: 'Price History',
+ useCase:
+ 'Historical USD price series for any coin — [timestamp, price] pairs over 1, 7, 30, 90, or 365 days, granularity auto-chosen per window.',
+ description:
+ 'Historical price series for agents — pay $0.001 USDC per call. Pass ?id=<coingecko-id>&days=<1|7|30|90|365>. Returns a compact [[timestamp_ms, price_usd], …] array with upstream-chosen granularity (5-minutely for 1 day, hourly to 90 days, daily beyond). The coin id is supplied at runtime — the same series behind the three.ws/coin charts.',
+ tags: ['crypto', 'market-data', 'chart', 'history'],
+ useCases: ['backtesting', 'trend analysis', 'chart rendering'],
+ priceAtomics: LIST_PRICE,
+ inputExample: { id: 'bitcoin', days: '30' },
+ inputSchema: {
+ type: 'object',
+ required: ['id'],
+ properties: {
+ id: str('CoinGecko coin id (lowercase slug, e.g. bitcoin).'),
+ days: str('Window: 1, 7, 30, 90, or 365. Default 30.'),
+ },
+ },
+ outputExample: { data: [[1751846400000, 107544.8], [1751932800000, 108234.12]], days: 30 },
+ },
+ {
+ slug: 'market-categories',
+ title: 'Sector Leaderboard',
+ useCase:
+ 'Every CoinGecko sector ranked by market cap — AI, L1, memes, DeFi and hundreds more, with 24h cap change, volume, and top-3 coin logos.',
+ description:
+ 'Crypto sector leaderboard for agents — pay $0.001 USDC per call. Returns every CoinGecko category (AI, layer-1, memecoins, DeFi, RWA, …) ranked by market cap, each with 24h market-cap change, 24h volume, and its top-3 coins. Feed a category id into the market-coins endpoint to drill into one sector. Same data behind three.ws/categories.',
+ tags: ['crypto', 'market-data', 'sectors', 'narratives'],
+ useCases: ['narrative rotation tracking', 'sector screening'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ categories: [
+ { id: 'artificial-intelligence', name: 'Artificial Intelligence', market_cap: 48200000000, market_cap_change_24h: 2.1, volume_24h: 3900000000 },
+ ],
+ },
+ },
+ {
+ slug: 'market-exchanges',
+ title: 'Exchange Rankings',
+ useCase:
+ 'Top 100 spot exchanges ranked by trust score, with 24h volume in BTC and USD, country, and year established.',
+ description:
+ 'Spot exchange rankings for agents — pay $0.001 USDC per call. Returns the top 100 crypto exchanges ranked by CoinGecko trust score, each with 24h trading volume in BTC and USD (converted at the live BTC price), trust rank, country, year established, and homepage. Same data behind three.ws/exchanges.',
+ tags: ['crypto', 'market-data', 'exchanges', 'volume'],
+ useCases: ['venue selection', 'liquidity comparison'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ exchanges: [
+ { id: 'binance', name: 'Binance', trust_score: 10, trust_score_rank: 1, volume_24h_usd: 21400000000, country: 'Cayman Islands' },
+ ],
+ btc_usd: 108234.12,
+ },
+ },
+ {
+ slug: 'market-derivatives',
+ title: 'Derivatives Markets',
+ useCase:
+ 'Perpetual futures tickers — price, funding rate, open interest, 24h volume across venues — or the derivatives-exchange leaderboard by open interest.',
+ description:
+ 'Derivatives market data for agents — pay $0.001 USDC per call. Default mode returns the top 100 perpetual futures contracts by 24h volume with price, 24h change, funding rate, and open interest. Pass ?view=exchanges for the derivatives-venue leaderboard ranked by BTC open interest (perp/futures pair counts included). Same data behind three.ws/derivatives.',
+ tags: ['crypto', 'market-data', 'derivatives', 'funding'],
+ useCases: ['funding-rate scanning', 'open-interest tracking'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: {
+ type: 'object',
+ properties: {
+ view: str("Set to 'exchanges' for the derivatives-venue leaderboard; omit for perp tickers."),
+ },
+ },
+ outputExample: {
+ tickers: [
+ { market: 'Binance (Futures)', symbol: 'BTCUSDT', price: 108250.5, funding_rate: 0.0042, open_interest: 8120000000, volume_24h: 19800000000 },
+ ],
+ },
+ },
+ {
+ slug: 'market-global',
+ title: 'Global Market Snapshot',
+ useCase:
+ 'Whole-market stats in one call — total market cap, 24h volume, BTC/ETH dominance, active coins, plus the Fear & Greed index.',
+ description:
+ 'Global crypto market snapshot for agents — pay $0.001 USDC per call. Returns total market cap, 24h volume, top-2 dominance shares, active coin count (CoinGecko → CoinPaprika → CoinLore failover), and the alternative.me Fear & Greed index with its label. The one-call market-regime check. Same data behind the three.ws/coins stats bar and /fear-greed.',
+ tags: ['crypto', 'market-data', 'sentiment', 'macro'],
+ useCases: ['market-regime detection', 'risk dashboards'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ market: { total_market_cap: 3920000000000, total_volume_24h: 148000000000, btc_dominance: 54.6 },
+ fear_greed: { value: 72, label: 'Greed' },
+ },
+ },
+ {
+ slug: 'market-gas',
+ title: 'Ethereum Gas Oracle',
+ useCase:
+ 'Live ETH gas in three tiers (slow/standard/fast) computed from on-chain fee history, with USD cost estimates for transfers, swaps, and mints.',
+ description:
+ 'Live Ethereum gas oracle for agents — pay $0.001 USDC per call. Computes slow/standard/fast tiers from eth_feeHistory over the last ~20 blocks (base fee + 25th/50th/90th priority-fee percentiles, median-smoothed) across failover public RPCs — no third-party gas API. Each tier carries USD cost estimates for an ETH transfer, token transfer, DEX swap, and NFT mint at the live ETH price. Same oracle behind three.ws/gas.',
+ tags: ['ethereum', 'gas', 'fees', 'onchain'],
+ useCases: ['transaction timing', 'cost estimation'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ tiers: [
+ { key: 'standard', gas_price_gwei: 6.4, actions: [{ key: 'swap', label: 'DEX swap', gas: 150000, usd: 3.12 }] },
+ ],
+ eth_price_usd: 3251.7,
+ },
+ },
+ {
+ slug: 'market-trending',
+ title: 'Trending Assets',
+ useCase:
+ "The last 24h's most-searched coins, categories, and NFT collections — early attention signals before they show up in price.",
+ description:
+ 'Trending crypto assets for agents — pay $0.001 USDC per call. Returns the most-searched coins on CoinGecko over the last 24 hours (with price, 24h change, market cap, and trending rank), the trending categories, and the trending NFT collections (floor price and 24h floor change). Attention flows before price — this is the early signal. Same data behind three.ws/markets/trending.',
+ tags: ['crypto', 'market-data', 'trending', 'attention'],
+ useCases: ['momentum discovery', 'narrative detection'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ coins: [{ id: 'sui', symbol: 'SUI', rank: 12, score: 0, price_usd: 4.82, change_24h_pct: 11.3 }],
+ categories: [{ slug: 'ai-agents', name: 'AI Agents', mcap_change_1h_pct: 1.9 }],
+ },
+ },
+ {
+ slug: 'market-defi',
+ title: 'DeFi Protocol TVL',
+ useCase:
+ 'Top 100 DeFi protocols ranked by TVL with 1d/7d change, chains, category, and market cap, plus whole-market TVL totals (CEX reserves excluded).',
+ description:
+ 'DeFi protocol rankings for agents — pay $0.001 USDC per call. Returns the top 100 DeFi protocols by TVL from DeFiLlama with 1d/7d TVL change, deployed chains, category, token symbol, and market cap — plus whole-market total TVL and protocol count with centralized-exchange reserves excluded so the totals mean actual DeFi. Same data behind three.ws/defi.',
+ tags: ['defi', 'tvl', 'protocols', 'market-data'],
+ useCases: ['protocol screening', 'TVL momentum tracking'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ total_tvl: 208000000000,
+ protocol_count: 4213,
+ protocols: [{ slug: 'aave-v3', name: 'AAVE V3', category: 'Lending', tvl: 28100000000, change_7d: 3.4, chain_count: 14 }],
+ },
+ },
+ {
+ slug: 'market-chains',
+ title: 'Chain TVL Leaderboard',
+ useCase:
+ 'Every chain ranked by DeFi TVL with native token symbol and share of total locked value — the cross-chain capital map.',
+ description:
+ 'Cross-chain TVL leaderboard for agents — pay $0.001 USDC per call. Returns the top 100 blockchains ranked by DeFi TVL from DeFiLlama, each with its native token symbol and percentage share of total locked value, plus the whole-market TVL and chain count. Where the capital actually lives, one call. Same data behind three.ws/chains.',
+ tags: ['defi', 'tvl', 'chains', 'market-data'],
+ useCases: ['chain selection', 'capital-flow tracking'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ total_tvl: 208000000000,
+ chains: [{ name: 'Ethereum', tvl: 112000000000, token_symbol: 'ETH', share_pct: 53.8 }],
+ },
+ },
+ {
+ slug: 'market-yields',
+ title: 'DeFi Yield Explorer',
+ useCase:
+ 'Query ~15,000 DeFi yield pools — filter by chain, project, stablecoin-only, or TVL floor, sort by APY or TVL, or pull one pool\'s APY/TVL history.',
+ description:
+ 'DeFi yield-pool explorer for agents — pay $0.001 USDC per call. Queries ~15,000 pools from DeFiLlama: filter with ?chain=&project=&stablecoin=&search=&minTvl=, sort by tvl or apy (APY sort is dust-guarded to pools ≥ $10k TVL so fake five-digit APYs never outrank real venues), page with limit/offset. Each pool carries APY split (base/reward), 30-day mean, IL risk, exposure, and predicted outlook. Pass ?pool=<uuid> for one pool\'s APY/TVL history. Same engine behind three.ws/yields.',
+ tags: ['defi', 'yield', 'apy', 'pools'],
+ useCases: ['yield hunting', 'stablecoin farming', 'APY history'],
+ priceAtomics: LIST_PRICE,
+ inputExample: { chain: 'solana', stablecoin: 'true', sort: 'apy' },
+ inputSchema: {
+ type: 'object',
+ properties: {
+ chain: str('Filter to one chain (case-insensitive, e.g. solana).'),
+ project: str('Filter to one protocol slug (e.g. aave-v3).'),
+ stablecoin: str("'true' for stablecoin pools only, 'false' to exclude them."),
+ search: str('Substring match over symbol, project, and chain.'),
+ minTvl: str('Minimum pool TVL in USD.'),
+ sort: str("'tvl' (default) or 'apy' (dust-guarded to pools ≥ $10k TVL)."),
+ limit: str('Rows per page, 1–200. Default 100.'),
+ offset: str('Pagination offset. Default 0.'),
+ pool: str('Chart mode: a DeFiLlama pool uuid — returns that pool\'s APY/TVL history instead of the list.'),
+ },
+ },
+ outputExample: {
+ pools: [
+ { pool: '747c1d2a-c668-4682-b9f9-296708a3dd90', chain: 'Ethereum', project: 'lido', symbol: 'STETH', tvl_usd: 24100000000, apy: 2.9, stablecoin: false },
+ ],
+ total: 15234, stats: { median_apy: 4.1 },
+ },
+ },
+ {
+ slug: 'market-stablecoins',
+ title: 'Stablecoin Monitor',
+ useCase:
+ 'Top 100 stablecoins by circulating supply with live price for peg health, peg mechanism, and chain deployments, plus total stablecoin market cap.',
+ description:
+ 'Stablecoin market monitor for agents — pay $0.001 USDC per call. Returns the top 100 pegged assets by on-chain circulating supply from DeFiLlama, each with live price (peg-health check), peg type and mechanism, and the chains it lives on — plus the total stablecoin market cap across every tracked asset. Same data behind three.ws/stablecoins.',
+ tags: ['stablecoins', 'defi', 'peg', 'market-data'],
+ useCases: ['peg monitoring', 'stablecoin supply tracking'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ total_mcap: 254000000000,
+ stablecoins: [{ id: '1', name: 'Tether', symbol: 'USDT', price: 0.9998, peg_mechanism: 'fiat-backed', circulating_usd: 156000000000, chain_count: 94 }],
+ },
+ },
+ {
+ slug: 'market-fees',
+ title: 'Protocol Fees & Revenue',
+ useCase:
+ 'Which protocols actually earn — top 100 by 24h fees or revenue with 1d/7d/30d totals and change, plus the whole-market daily chart.',
+ description:
+ 'Protocol fee and revenue rankings for agents — pay $0.001 USDC per call. Returns the top 100 protocols by 24h fees from DeFiLlama with 24h/7d/30d totals and momentum. Default ?type=fees is what users pay to use each protocol; ?type=revenue is the slice the protocol keeps — the closest thing on-chain to an earnings report. Includes whole-market totals and the aggregate daily chart. Same data behind three.ws/fees.',
+ tags: ['defi', 'fees', 'revenue', 'fundamentals'],
+ useCases: ['fundamental screening', 'real-yield analysis'],
+ priceAtomics: LIST_PRICE,
+ inputExample: { type: 'fees' },
+ inputSchema: {
+ type: 'object',
+ properties: {
+ type: str("'fees' (default — what users pay) or 'revenue' (what the protocol keeps)."),
+ },
+ },
+ outputExample: {
+ type: 'fees', total24h: 61000000,
+ protocols: [{ name: 'Tether', slug: 'tether', total24h: 18400000, total30d: 512000000 }],
+ },
+ },
+ {
+ slug: 'market-dex-volumes',
+ title: 'DEX Volume Rankings',
+ useCase:
+ 'Top 100 DEXs by 24h trading volume with 7d totals, market share, and the aggregate daily volume chart.',
+ description:
+ 'DEX trading-volume rankings for agents — pay $0.001 USDC per call. Returns the top 100 decentralized exchanges by 24h volume from DeFiLlama, each with 7d volume, week-over-week change, deployed chains, and its share of whole-market 24h volume — plus market totals and the aggregate daily chart. Same data behind three.ws/dex-volumes.',
+ tags: ['defi', 'dex', 'volume', 'market-data'],
+ useCases: ['venue routing', 'DEX market-share tracking'],
+ priceAtomics: LIST_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ total24h: 9800000000,
+ protocols: [{ name: 'Uniswap V3', slug: 'uniswap-v3', total24h: 1820000000, share_pct: 18.6 }],
+ },
+ },
+ {
+ slug: 'market-hacks',
+ title: 'Exploit Database',
+ useCase:
+ 'Every recorded DeFi hack — amount stolen, technique, classification, chains, funds returned — searchable, with all-time and 12-month loss stats.',
+ description:
+ 'DeFi exploit database for agents — pay $0.001 USDC per call. Returns DeFiLlama\'s full hack history newest-first: amount stolen in USD, attack technique and classification, affected chains, bridge-hack flag, target type, post-mortem link, and funds returned. Search with ?search=<text> over name/technique/classification, page with limit/offset. Headline stats cover all-time and trailing-12-month losses and the bridge-hack share. Same data behind three.ws/hacks.',
+ tags: ['security', 'defi', 'hacks', 'risk'],
+ useCases: ['protocol risk assessment', 'security research'],
+ priceAtomics: LIST_PRICE,
+ inputExample: { search: 'bridge' },
+ inputSchema: {
+ type: 'object',
+ properties: {
+ search: str('Case-insensitive match over incident name, technique, and classification.'),
+ limit: str('Rows per page, 1–200. Default 100.'),
+ offset: str('Pagination offset. Default 0.'),
+ },
+ },
+ outputExample: {
+ stats: { total_stolen_all_time: 12400000000, incidents_12mo: 61 },
+ hacks: [{ name: 'Ronin Network', amount_usd: 624000000, technique: 'Compromised keys', chains: ['Ronin'], bridge: true }],
+ },
+ },
+ {
+ slug: 'market-pulse',
+ title: 'Market Pulse',
+ useCase:
+ 'The whole market in one paid call — global stats, Fear & Greed, top-10 coins, trending, ETH gas, DeFi TVL, stablecoin supply, DEX volume, and protocol fees.',
+ description:
+ 'The flagship one-call market bundle for agents — pay $0.005 USDC for what would take eight separate calls: global market cap/volume/dominance, the Fear & Greed index, the top-10 coins with 24h/7d change, trending searches, the live ETH gas standard tier, DeFi total TVL with the top-10 protocols, total stablecoin supply, whole-market 24h DEX volume, and 24h protocol fees. Sections degrade independently — one upstream hiccup nulls its section instead of failing the call. The cheapest complete market context an agent can buy.',
+ tags: ['crypto', 'market-data', 'bundle', 'macro'],
+ useCases: ['agent market context', 'one-call briefing', 'trading loops'],
+ priceAtomics: PULSE_PRICE,
+ inputExample: {},
+ inputSchema: { type: 'object', properties: {} },
+ outputExample: {
+ global: { total_market_cap: 3920000000000, btc_dominance: 54.6 },
+ fear_greed: { value: 72, label: 'Greed' },
+ top_coins: [{ id: 'bitcoin', symbol: 'BTC', price: 108234.12, change_24h: 1.42 }],
+ gas: { standard_gwei: 6.4, eth_price_usd: 3251.7 },
+ defi: { total_tvl: 208000000000 },
+ stablecoins: { total_mcap: 254000000000 },
+ },
+ },
+]);
+
+export const MARKET_CATEGORY_BY_SLUG = new Map(MARKET_CATEGORIES.map((c) => [c.slug, c]));
diff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.js
index 0f1be7e82..31a4427ce 100644
--- a/api/_lib/service-catalog/services/index.js
+++ b/api/_lib/service-catalog/services/index.js
@@ -27,6 +27,17 @@ import assetDownload from './asset-download.js';
import remixAsset from './remix-asset.js';
import skillCall from './skill-call.js';
import tokenIntel from './token-intel.js';
+import defiRadar from './defi-radar.js';
+import yieldScan from './yield-scan.js';
+import stablecoinHealth from './stablecoin-health.js';
+import hackCheck from './hack-check.js';
+import marketHeatmap from './market-heatmap.js';
+import gasOracle from './gas-oracle.js';
+import marketMood from './market-mood.js';
+import newsPulse from './news-pulse.js';
+// Registry-derived family (17 endpoints, /api/x402/market-*): one row per
+// category, projected from api/_lib/market-data/registry.js — see that file.
+import { MARKET_DATA_SERVICES } from './market-data.js';
import cosmeticPurchase from './cosmetic-purchase.js';
import animationDownload from './animation-download.js';
import clubCover from './club-cover.js';
@@ -78,6 +89,15 @@ export const PAID_SERVICES = Object.freeze([
remixAsset,
skillCall,
tokenIntel,
+ defiRadar,
+ yieldScan,
+ stablecoinHealth,
+ hackCheck,
+ marketHeatmap,
+ gasOracle,
+ marketMood,
+ newsPulse,
+ ...MARKET_DATA_SERVICES,
cosmeticPurchase,
animationDownload,
clubCover,
diff --git a/api/_lib/service-catalog/services/market-data.js b/api/_lib/service-catalog/services/market-data.js
new file mode 100644
index 000000000..7956c1547
--- /dev/null
+++ b/api/_lib/service-catalog/services/market-data.js
@@ -0,0 +1,32 @@
+// Service-catalog descriptors for the paid Market Data API family
+// (/api/x402/market-*). Unlike the sibling one-file-per-service descriptors,
+// this family is REGISTRY-DERIVED: api/_lib/market-data/registry.js is the
+// single written-once source for every category's slug, price, description,
+// and schemas — the live endpoints (api/_lib/market-data/endpoint.js) build
+// from the same entries, so the catalog cannot drift from the 402s.
+// Contract: specs/SERVICE_CATALOG.md. Edit the registry, not this projection.
+
+import {
+ MARKET_CATEGORIES,
+ MARKET_SERVICE_NAME,
+} from '../../market-data/registry.js';
+
+export const MARKET_DATA_SERVICES = MARKET_CATEGORIES.map((c) => ({
+ slug: c.slug,
+ title: c.title,
+ category: 'market-data',
+ useCase: c.useCase,
+ path: `/api/x402/${c.slug}`,
+ method: 'GET',
+ free: false,
+ status: 'live',
+ priceAtomics: c.priceAtomics,
+ acceptsBuilder: 'standard',
+ serviceName: MARKET_SERVICE_NAME,
+ tags: c.tags,
+ description: c.description,
+ input: c.inputExample,
+ inputSchema: c.inputSchema,
+ outputExample: c.outputExample,
+ storefronts: ['x402scan'],
+}));
diff --git a/api/_lib/x402/ring-catalog.js b/api/_lib/x402/ring-catalog.js
index ef3e1a7fa..19512adaa 100644
--- a/api/_lib/x402/ring-catalog.js
+++ b/api/_lib/x402/ring-catalog.js
@@ -252,6 +252,132 @@ export const RING_CATALOG = [
weight: 1,
businessEffect: 'Returns a token market + risk signal for the mint (DexScreener, read-only).',
},
+ {
+ slug: 'defi-radar',
+ sourceFile: 'api/x402/defi-radar.js',
+ path: '/api/x402/defi-radar',
+ method: 'GET',
+ query: { limit: '5' },
+ body: NO_BODY,
+ priceAtomicDefault: 5_000,
+ priceSlug: 'defi-radar',
+ tier: 'intel',
+ kind: 'intel',
+ network: null,
+ autobuy: true,
+ weight: 1,
+ businessEffect: 'Returns the composite DeFi snapshot: TVL movers + fee + DEX leaderboards (DeFiLlama, read-only).',
+ },
+ {
+ slug: 'yield-scan',
+ sourceFile: 'api/x402/yield-scan.js',
+ path: '/api/x402/yield-scan',
+ method: 'GET',
+ query: { limit: '5' },
+ body: NO_BODY,
+ priceAtomicDefault: 5_000,
+ priceSlug: 'yield-scan',
+ tier: 'intel',
+ kind: 'intel',
+ network: null,
+ autobuy: true,
+ weight: 1,
+ businessEffect: 'Screens live DeFi yield pools with APY breakdown + risk flags (DeFiLlama yields, read-only).',
+ },
+ {
+ slug: 'stablecoin-health',
+ sourceFile: 'api/x402/stablecoin-health.js',
+ path: '/api/x402/stablecoin-health',
+ method: 'GET',
+ query: { limit: '5' },
+ body: NO_BODY,
+ priceAtomicDefault: 5_000,
+ priceSlug: 'stablecoin-health',
+ tier: 'intel',
+ kind: 'intel',
+ network: null,
+ autobuy: true,
+ weight: 1,
+ businessEffect: 'Returns per-stablecoin peg deviation + supply-flow report with depeg alerts (DeFiLlama, read-only).',
+ },
+ {
+ slug: 'hack-check',
+ sourceFile: 'api/x402/hack-check.js',
+ path: '/api/x402/hack-check',
+ method: 'GET',
+ query: { limit: '3' },
+ body: NO_BODY,
+ priceAtomicDefault: 2_000,
+ priceSlug: 'hack-check',
+ tier: 'intel',
+ kind: 'intel',
+ network: null,
+ autobuy: true,
+ weight: 1,
+ businessEffect: 'Runs a protocol name against the DeFi exploit database, returns verdict + incidents (read-only).',
+ },
+ {
+ slug: 'market-heatmap',
+ sourceFile: 'api/x402/market-heatmap.js',
+ path: '/api/x402/market-heatmap',
+ method: 'GET',
+ query: { limit: '10' },
+ body: NO_BODY,
+ priceAtomicDefault: 2_000,
+ priceSlug: 'market-heatmap',
+ tier: 'intel',
+ kind: 'intel',
+ network: null,
+ autobuy: true,
+ weight: 1,
+ businessEffect: 'Returns the top-coins momentum board + breadth stats (CoinGecko→CoinPaprika failover, read-only).',
+ },
+ {
+ slug: 'gas-oracle',
+ sourceFile: 'api/x402/gas-oracle.js',
+ path: '/api/x402/gas-oracle',
+ method: 'GET',
+ body: NO_BODY,
+ priceAtomicDefault: 1_000,
+ priceSlug: 'gas-oracle',
+ tier: 'intel',
+ kind: 'intel',
+ network: null,
+ autobuy: true,
+ weight: 1,
+ businessEffect: 'Returns live fee tiers for Ethereum + Base and Solana priority-fee percentiles (public RPCs, read-only).',
+ },
+ {
+ slug: 'market-mood',
+ sourceFile: 'api/x402/market-mood.js',
+ path: '/api/x402/market-mood',
+ method: 'GET',
+ body: NO_BODY,
+ priceAtomicDefault: 2_000,
+ priceSlug: 'market-mood',
+ tier: 'intel',
+ kind: 'intel',
+ network: null,
+ autobuy: true,
+ weight: 1,
+ businessEffect: 'Returns the Fear&Greed × news-sentiment composite mood score with divergence flag (read-only).',
+ },
+ {
+ slug: 'news-pulse',
+ sourceFile: 'api/x402/news-pulse.js',
+ path: '/api/x402/news-pulse',
+ method: 'GET',
+ query: { ticker: 'THREE', hours: '24' },
+ body: NO_BODY,
+ priceAtomicDefault: 2_000,
+ priceSlug: 'news-pulse',
+ tier: 'intel',
+ kind: 'intel',
+ network: null,
+ autobuy: true,
+ weight: 1,
+ businessEffect: 'Measures live news coverage for one ticker: mentions, velocity, sentiment, headlines (read-only).',
+ },
{
slug: 'agent-reputation',
sourceFile: 'api/x402/agent-reputation.js',
diff --git a/api/coin/categories.js b/api/coin/categories.js
index 51bc13e11..65464d19e 100644
--- a/api/coin/categories.js
+++ b/api/coin/categories.js
@@ -26,6 +26,17 @@ function shapeCategory(c) {
};
}
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-categories endpoint sells the same sector leaderboard this page renders.
+export async function buildCategories() {
+ const raw = await geckoFetch('/coins/categories?order=market_cap_desc', {
+ ttlMs: 300_000,
+ timeoutMs: 10_000,
+ });
+ if (!Array.isArray(raw)) throw new Error('unexpected upstream payload');
+ return { categories: raw.filter((c) => c && typeof c.id === 'string').map(shapeCategory) };
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -34,16 +45,10 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
try {
- const raw = await geckoFetch('/coins/categories?order=market_cap_desc', {
- ttlMs: 300_000,
- timeoutMs: 10_000,
- });
- if (!Array.isArray(raw)) throw new Error('unexpected upstream payload');
- const categories = raw.filter((c) => c && typeof c.id === 'string').map(shapeCategory);
return json(
res,
200,
- { categories },
+ await buildCategories(),
{
'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1800',
},
diff --git a/api/coin/detail.js b/api/coin/detail.js
index 3b518807c..e0133dbbf 100644
--- a/api/coin/detail.js
+++ b/api/coin/detail.js
@@ -122,6 +122,21 @@ function shape(c) {
};
}
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-coin endpoint sells the same rich coin profile this page renders.
+// Callers must validate id/contract first; upstream errors carry err.status.
+export async function buildCoinDetail({ id, contract }) {
+ const raw = contract
+ ? await geckoFetch(`/coins/solana/contract/${contract}`, { ttlMs: 60_000 })
+ : await geckoFetch(
+ `/coins/${id}?localization=false&tickers=false&market_data=true&community_data=true&developer_data=true&sparkline=false`,
+ { ttlMs: 60_000 },
+ );
+ return { coin: shape(raw) };
+}
+
+export { MINT_RE };
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -140,13 +155,7 @@ export default wrap(async (req, res) => {
}
try {
- const raw = contract
- ? await geckoFetch(`/coins/solana/contract/${contract}`, { ttlMs: 60_000 })
- : await geckoFetch(
- `/coins/${id}?localization=false&tickers=false&market_data=true&community_data=true&developer_data=true&sparkline=false`,
- { ttlMs: 60_000 },
- );
- return json(res, 200, { coin: shape(raw) }, {
+ return json(res, 200, await buildCoinDetail({ id, contract }), {
'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300',
});
} catch (err) {
diff --git a/api/coin/markets.js b/api/coin/markets.js
index 664263ee4..b5d137b1d 100644
--- a/api/coin/markets.js
+++ b/api/coin/markets.js
@@ -15,6 +15,21 @@ import { fetchMarketsTable } from '../_lib/market-fallbacks.js';
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-coins endpoint offers the same type-ahead id resolver this page uses.
+export async function searchCoins(q) {
+ const raw = await geckoFetch(`/search?query=${encodeURIComponent(q)}`, { ttlMs: 300_000 });
+ return {
+ coins: (raw?.coins || []).slice(0, 10).map((c) => ({
+ id: c.id,
+ name: c.name,
+ symbol: (c.symbol || '').toUpperCase(),
+ thumb: c.thumb || null,
+ rank: num(c.market_cap_rank),
+ })),
+ };
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -28,15 +43,7 @@ export default wrap(async (req, res) => {
try {
if (q) {
if (q.length > 64) return error(res, 400, 'bad_query', 'search query too long');
- const raw = await geckoFetch(`/search?query=${encodeURIComponent(q)}`, { ttlMs: 300_000 });
- const coins = (raw?.coins || []).slice(0, 10).map((c) => ({
- id: c.id,
- name: c.name,
- symbol: (c.symbol || '').toUpperCase(),
- thumb: c.thumb || null,
- rank: num(c.market_cap_rank),
- }));
- return json(res, 200, { coins }, {
+ return json(res, 200, await searchCoins(q), {
'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
});
}
diff --git a/api/coin/ohlc.js b/api/coin/ohlc.js
index fa9bbad8d..137c6cf6e 100644
--- a/api/coin/ohlc.js
+++ b/api/coin/ohlc.js
@@ -9,7 +9,21 @@ import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { geckoFetch, isPlausibleCoinId } from '../_lib/coingecko.js';
-const VALID_DAYS = new Set([1, 7, 30, 90, 365]);
+export const VALID_DAYS = new Set([1, 7, 30, 90, 365]);
+
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-chart endpoint sells the same price series this page renders.
+// Callers must validate id/days first; a 404 from upstream carries err.status.
+export async function buildPriceChart(id, days) {
+ const raw = await geckoFetch(`/coins/${id}/market_chart?vs_currency=usd&days=${days}`, {
+ ttlMs: 120_000,
+ timeoutMs: 10_000,
+ });
+ const data = (raw?.prices || [])
+ .filter((p) => Array.isArray(p) && Number.isFinite(p[0]) && Number.isFinite(p[1]))
+ .map(([t, v]) => [Math.round(t), v]);
+ return { data, days };
+}
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
@@ -29,13 +43,7 @@ export default wrap(async (req, res) => {
}
try {
- const raw = await geckoFetch(`/coins/${id}/market_chart?vs_currency=usd&days=${days}`, {
- ttlMs: 120_000,
- timeoutMs: 10_000,
- });
- const data = (raw?.prices || [])
- .filter((p) => Array.isArray(p) && Number.isFinite(p[0]) && Number.isFinite(p[1]))
- .map(([t, v]) => [Math.round(t), v]);
+ const { data } = await buildPriceChart(id, days);
if (!data.length) return error(res, 502, 'no_data', 'no price history for this coin');
return json(res, 200, { data, days }, {
'cache-control': 'public, max-age=60, s-maxage=120, stale-while-revalidate=600',
diff --git a/api/coin/trending.js b/api/coin/trending.js
index a1118c8b0..e04eb2b7c 100644
--- a/api/coin/trending.js
+++ b/api/coin/trending.js
@@ -97,6 +97,13 @@ function shape(raw) {
return { coins, categories, nfts };
}
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-trending endpoint sells the same trending lists this page renders.
+export async function buildTrending() {
+ const raw = await geckoFetch('/search/trending', { ttlMs: 120_000, timeoutMs: 10_000 });
+ return shape(raw);
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -105,8 +112,7 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
try {
- const raw = await geckoFetch('/search/trending', { ttlMs: 120_000, timeoutMs: 10_000 });
- return json(res, 200, shape(raw), {
+ return json(res, 200, await buildTrending(), {
'cache-control': 'public, max-age=60, s-maxage=120, stale-while-revalidate=600',
});
} catch {
diff --git a/api/defi/chains.js b/api/defi/chains.js
index f2fbc9a08..0dde7f804 100644
--- a/api/defi/chains.js
+++ b/api/defi/chains.js
@@ -14,7 +14,9 @@ const TTL_MS = 300_000;
let _cache = null; // { value, expiresAt }
-async function build() {
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-chains endpoint sells the same cross-chain TVL board this page renders.
+export async function buildChains() {
const now = Date.now();
if (_cache && _cache.expiresAt > now) return _cache.value;
@@ -65,7 +67,7 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
try {
- const payload = await build();
+ const payload = await buildChains();
return json(res, 200, payload, {
'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
});
diff --git a/api/defi/dex-volumes.js b/api/defi/dex-volumes.js
index ab8804d98..90f1df8ba 100644
--- a/api/defi/dex-volumes.js
+++ b/api/defi/dex-volumes.js
@@ -34,7 +34,9 @@ function normalizeChart(raw) {
return out;
}
-async function build() {
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-dex-volumes endpoint sells the same DEX rankings this page renders.
+export async function buildDexVolumes() {
const now = Date.now();
if (_cache && _cache.expiresAt > now) return _cache.value;
@@ -95,7 +97,7 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
try {
- const payload = await build();
+ const payload = await buildDexVolumes();
return json(res, 200, payload, {
'cache-control': 'public, max-age=120, s-maxage=600, stale-while-revalidate=600',
});
diff --git a/api/defi/fees.js b/api/defi/fees.js
index c2f00a1b5..5ed5f3285 100644
--- a/api/defi/fees.js
+++ b/api/defi/fees.js
@@ -40,7 +40,9 @@ function normalizeChart(raw) {
return out;
}
-async function build(type) {
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-fees endpoint sells the same fees/revenue rankings this page renders.
+export async function buildFees(type) {
const now = Date.now();
const hit = _cache.get(type);
if (hit && hit.expiresAt > now) return hit.value;
@@ -101,7 +103,7 @@ export default wrap(async (req, res) => {
const type = url.searchParams.get('type') === 'revenue' ? 'revenue' : 'fees';
try {
- const payload = await build(type);
+ const payload = await buildFees(type);
return json(res, 200, payload, {
'cache-control': 'public, max-age=120, s-maxage=600, stale-while-revalidate=600',
});
diff --git a/api/defi/hacks.js b/api/defi/hacks.js
index 42ae6cd98..0fb9996e4 100644
--- a/api/defi/hacks.js
+++ b/api/defi/hacks.js
@@ -109,6 +109,32 @@ function clampInt(raw, fallback, min, max) {
return Math.min(max, Math.max(min, n));
}
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-hacks endpoint sells the same exploit database this page renders.
+export async function queryHacks({ search = '', limit = DEFAULT_LIMIT, offset = 0 } = {}) {
+ const dataset = await loadDataset();
+
+ let filtered = dataset.hacks;
+ if (search) {
+ filtered = filtered.filter((h) => {
+ const hay = `${h.name} ${h.technique || ''} ${h.classification || ''}`.toLowerCase();
+ return hay.includes(search);
+ });
+ }
+
+ return {
+ stats: {
+ total_stolen_all_time: dataset.stats.total_stolen_all_time,
+ total_stolen_12mo: dataset.stats.total_stolen_12mo,
+ incidents_12mo: dataset.stats.incidents_12mo,
+ bridge_hack_share_pct: finiteOrNull(dataset.stats.bridge_hack_share_pct) ?? 0,
+ },
+ hacks: filtered.slice(offset, offset + limit),
+ count: filtered.length,
+ updated_at: dataset.updated_at,
+ };
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -127,32 +153,10 @@ export default wrap(async (req, res) => {
const offset = clampInt(url.searchParams.get('offset'), 0, 0, Number.MAX_SAFE_INTEGER);
try {
- const dataset = await loadDataset();
-
- let filtered = dataset.hacks;
- if (search) {
- filtered = filtered.filter((h) => {
- const hay = `${h.name} ${h.technique || ''} ${h.classification || ''}`.toLowerCase();
- return hay.includes(search);
- });
- }
-
- const page = filtered.slice(offset, offset + limit);
-
return json(
res,
200,
- {
- stats: {
- total_stolen_all_time: dataset.stats.total_stolen_all_time,
- total_stolen_12mo: dataset.stats.total_stolen_12mo,
- incidents_12mo: dataset.stats.incidents_12mo,
- bridge_hack_share_pct: finiteOrNull(dataset.stats.bridge_hack_share_pct) ?? 0,
- },
- hacks: page,
- count: filtered.length,
- updated_at: dataset.updated_at,
- },
+ await queryHacks({ search, limit, offset }),
{
'cache-control':
'public, max-age=120, s-maxage=600, stale-while-revalidate=1200',
diff --git a/api/defi/protocols.js b/api/defi/protocols.js
index bc8bac888..57d0dc0ae 100644
--- a/api/defi/protocols.js
+++ b/api/defi/protocols.js
@@ -16,7 +16,9 @@ let _cache = null; // { value, expiresAt }
const finite = (n) => (Number.isFinite(n) ? n : null);
-async function build() {
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-defi endpoint sells the same TVL leaderboard this page renders.
+export async function buildProtocols() {
const now = Date.now();
if (_cache && _cache.expiresAt > now) return _cache.value;
@@ -83,7 +85,7 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
try {
- const payload = await build();
+ const payload = await buildProtocols();
return json(res, 200, payload, {
'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
});
diff --git a/api/defi/stablecoins.js b/api/defi/stablecoins.js
index 905189cca..38c278d5a 100644
--- a/api/defi/stablecoins.js
+++ b/api/defi/stablecoins.js
@@ -62,7 +62,9 @@ function shape(assets) {
};
}
-async function build() {
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-stablecoins endpoint sells the same peg board this page renders.
+export async function buildStablecoins() {
const now = Date.now();
if (_cache && _cache.expiresAt > now) return _cache.value;
@@ -89,7 +91,7 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
try {
- const payload = await build();
+ const payload = await buildStablecoins();
return json(res, 200, payload, {
'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
});
diff --git a/api/defi/yields.js b/api/defi/yields.js
index 1a6541289..47c34410f 100644
--- a/api/defi/yields.js
+++ b/api/defi/yields.js
@@ -159,16 +159,18 @@ function clampInt(v, { def, min, max }) {
return Math.max(min, Math.min(max, n));
}
-async function listMode(req, res, params) {
- const chain = (params.get('chain') || '').trim().toLowerCase();
- const project = (params.get('project') || '').trim().toLowerCase();
- const stablecoin = parseBool(params.get('stablecoin'));
- const search = (params.get('search') || '').trim().toLowerCase();
- const minTvl = Math.max(0, Number(params.get('minTvl')) || 0);
- const sort = params.get('sort') === 'apy' ? 'apy' : 'tvl';
- const limit = clampInt(params.get('limit'), { def: DEFAULT_LIMIT, min: 1, max: MAX_LIMIT });
- const offset = clampInt(params.get('offset'), { def: 0, min: 0, max: 1_000_000 });
-
+// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// market-yields endpoint sells the same filtered pool explorer this page renders.
+export async function queryYieldPools({
+ chain = '',
+ project = '',
+ stablecoin,
+ search = '',
+ minTvl = 0,
+ sort = 'tvl',
+ limit = DEFAULT_LIMIT,
+ offset = 0,
+} = {}) {
const { pools, facets, stats, updated_at } = await loadPools();
let rows = pools.filter((p) => {
@@ -189,21 +191,32 @@ async function listMode(req, res, params) {
}
// sort === 'tvl' needs no work — the cache is already TVL desc.
- return json(
- res,
- 200,
- {
- pools: rows.slice(offset, offset + limit),
- total: rows.length,
- limit,
- offset,
- sort,
- facets,
- stats,
- updated_at,
- },
- { 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600' },
- );
+ return {
+ pools: rows.slice(offset, offset + limit),
+ total: rows.length,
+ limit,
+ offset,
+ sort,
+ facets,
+ stats,
+ updated_at,
+ };
+}
+
+async function listMode(req, res, params) {
+ const payload = await queryYieldPools({
+ chain: (params.get('chain') || '').trim().toLowerCase(),
+ project: (params.get('project') || '').trim().toLowerCase(),
+ stablecoin: parseBool(params.get('stablecoin')),
+ search: (params.get('search') || '').trim().toLowerCase(),
+ minTvl: Math.max(0, Number(params.get('minTvl')) || 0),
+ sort: params.get('sort') === 'apy' ? 'apy' : 'tvl',
+ limit: clampInt(params.get('limit'), { def: DEFAULT_LIMIT, min: 1, max: MAX_LIMIT }),
+ offset: clampInt(params.get('offset'), { def: 0, min: 0, max: 1_000_000 }),
+ });
+ return json(res, 200, payload, {
+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
+ });
}
// ── Chart mode ──────────────────────────────────────────────────────────────
@@ -254,13 +267,32 @@ async function loadChart(pool) {
return value;
}
-async function chartMode(req, res, pool) {
- if (!UUID_RE.test(pool)) {
- return error(res, 400, 'invalid_pool', 'pool must be a DeFiLlama pool uuid');
+// Exported for the paid Market Data API — validates + loads a single pool's
+// APY/TVL history; throws {status, code} instead of writing to a response.
+export async function queryYieldChart(pool) {
+ if (!UUID_RE.test(pool || '')) {
+ throw Object.assign(new Error('pool must be a DeFiLlama pool uuid'), {
+ status: 400,
+ code: 'invalid_pool',
+ });
}
const value = await loadChart(pool.toLowerCase());
if (!value) {
- return error(res, 404, 'pool_not_found', 'no APY/TVL history for this pool id');
+ throw Object.assign(new Error('no APY/TVL history for this pool id'), {
+ status: 404,
+ code: 'pool_not_found',
+ });
+ }
+ return value;
+}
+
+async function chartMode(req, res, pool) {
+ let value;
+ try {
+ value = await queryYieldChart(pool);
+ } catch (err) {
+ if (err?.status && err.status < 500) return error(res, err.status, err.code, err.message);
+ throw err;
}
return json(res, 200, value, {
'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1200',
diff --git a/api/x402/defi-radar.js b/api/x402/defi-radar.js
new file mode 100644
index 000000000..6d7f143a7
--- /dev/null
+++ b/api/x402/defi-radar.js
@@ -0,0 +1,202 @@
+// GET /api/x402/defi-radar?limit=10
+//
+// DeFi Radar — $0.005 USDC per call on Solana or Base. One call returns the
+// whole DeFi market at a glance: total TVL with the biggest 24 h gainers and
+// losers, the top fee-earning protocols, and the top DEXes by 24 h volume —
+// three DeFiLlama dimensions composed into one agent-ready snapshot.
+//
+// Data is live: api.llama.fi /protocols, /overview/fees and /overview/dexs
+// (all keyless), cached 5 min in-memory. No mock path — if any dimension is
+// unavailable the handler throws BEFORE settlement so the buyer is never
+// charged for a partial radar.
+
+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 listing from '../_lib/service-catalog/services/defi-radar.js';
+
+const ROUTE = '/api/x402/defi-radar';
+
+// Single source of truth: the service-catalog descriptor is the storefront
+// listing copy — importing it keeps the live 402 challenge from drifting from
+// what /.well-known/x402.json advertises (same pattern as token-intel.js).
+const DESCRIPTION = listing.description;
+
+const TTL_MS = 300_000;
+const MIN_MOVER_TVL_USD = 10_000_000; // a "top gainer" on $40k TVL is noise
+
+let _cache = null; // { value, expiresAt }
+
+const finite = (n) => (Number.isFinite(n) ? n : null);
+
+async function fetchLlama(path) {
+ const r = await fetch(`https://api.llama.fi${path}`, {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!r.ok) throw new Error(`llama ${path} ${r.status}`);
+ return r.json();
+}
+
+// Fetch + normalize all three dimensions once, cache the full-size boards; the
+// per-request `limit` slices the cached whole.
+async function loadRadar() {
+ const now = Date.now();
+ if (_cache && _cache.expiresAt > now) return _cache.value;
+
+ const [protocols, fees, dexs] = await Promise.all([
+ fetchLlama('/protocols'),
+ fetchLlama('/overview/fees?excludeTotalDataChartBreakdown=true&dataType=dailyFees'),
+ fetchLlama('/overview/dexs?excludeTotalDataChartBreakdown=true'),
+ ]);
+ if (!Array.isArray(protocols) || !Array.isArray(fees?.protocols) || !Array.isArray(dexs?.protocols)) {
+ throw new Error('unexpected upstream shape');
+ }
+
+ const rows = protocols
+ .filter((p) => Number.isFinite(Number(p?.tvl)) && Number(p.tvl) > 0 && typeof p?.name === 'string')
+ .map((p) => ({
+ name: p.name,
+ tvl_usd: Number(p.tvl),
+ change_1d: finite(Number(p.change_1d)),
+ change_7d: finite(Number(p.change_7d)),
+ category: typeof p.category === 'string' ? p.category : null,
+ chains: Array.isArray(p.chains) ? p.chains.filter((c) => typeof c === 'string').slice(0, 8) : [],
+ }));
+
+ const totalTvl = rows.reduce((s, p) => s + p.tvl_usd, 0);
+ const byTvl = [...rows].sort((a, b) => b.tvl_usd - a.tvl_usd);
+ const movers = rows.filter((p) => p.tvl_usd >= MIN_MOVER_TVL_USD && p.change_1d != null);
+ const gainers = [...movers].sort((a, b) => b.change_1d - a.change_1d)
+ .map((p) => ({ name: p.name, tvl_usd: p.tvl_usd, change_1d: p.change_1d }));
+ const losers = [...movers].sort((a, b) => a.change_1d - b.change_1d)
+ .map((p) => ({ name: p.name, tvl_usd: p.tvl_usd, change_1d: p.change_1d }));
+
+ const feeRows = fees.protocols
+ .filter((p) => Number.isFinite(Number(p?.total24h)))
+ .sort((a, b) => Number(b.total24h) - Number(a.total24h))
+ .map((p) => ({
+ name: typeof p.displayName === 'string' && p.displayName ? p.displayName : String(p.name || 'Unknown'),
+ total_24h_usd: Number(p.total24h),
+ total_7d_usd: finite(Number(p.total7d)),
+ category: typeof p.category === 'string' ? p.category : null,
+ }));
+
+ const dexRows = dexs.protocols
+ .filter((p) => Number.isFinite(Number(p?.total24h)))
+ .sort((a, b) => Number(b.total24h) - Number(a.total24h))
+ .map((p) => ({
+ name: typeof p.displayName === 'string' && p.displayName ? p.displayName : String(p.name || 'Unknown'),
+ total_24h_usd: Number(p.total24h),
+ change_1d: finite(Number(p.change_1d)),
+ }));
+
+ const value = {
+ tvl: { total_usd: totalTvl, top: byTvl, gainers, losers },
+ fees: { total_24h_usd: finite(Number(fees.total24h)), top: feeRows },
+ dex: { total_24h_usd: finite(Number(dexs.total24h)), top: dexRows },
+ };
+ _cache = { value, expiresAt: now + TTL_MS };
+ return value;
+}
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ ...listing.inputSchema,
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['tvl', 'fees', 'dex', 'ts'],
+ properties: {
+ tvl: {
+ type: 'object',
+ required: ['total_usd', 'top', 'gainers', 'losers'],
+ properties: {
+ total_usd: { type: 'number' },
+ top: { type: 'array', items: { type: 'object' } },
+ gainers: { type: 'array', items: { type: 'object' } },
+ losers: { type: 'array', items: { type: 'object' } },
+ },
+ },
+ fees: {
+ type: 'object',
+ required: ['total_24h_usd', 'top'],
+ properties: {
+ total_24h_usd: { type: ['number', 'null'] },
+ top: { type: 'array', items: { type: 'object' } },
+ },
+ },
+ dex: {
+ type: 'object',
+ required: ['total_24h_usd', 'top'],
+ properties: {
+ total_24h_usd: { type: ['number', 'null'] },
+ top: { type: 'array', items: { type: 'object' } },
+ },
+ },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['defi market overview', 'tvl movers', 'protocol fee leaderboard'],
+ input: {
+ type: 'query',
+ example: listing.input,
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: listing.outputExample,
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('defi-radar', '5000'), // $0.005 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: listing.serviceName,
+ tags: listing.tags,
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const raw = Number(new URL(req.url, 'http://x').searchParams.get('limit') || '10');
+ const limit = Math.min(25, Math.max(1, Number.isFinite(raw) ? Math.floor(raw) : 10));
+
+ let radar = null;
+ try { radar = await loadRadar(); } catch { /* refund below */ }
+ if (!radar) {
+ throw Object.assign(new Error('DeFi market data is temporarily unavailable'), {
+ status: 503,
+ code: 'data_unavailable',
+ });
+ }
+
+ return {
+ tvl: {
+ total_usd: radar.tvl.total_usd,
+ top: radar.tvl.top.slice(0, limit),
+ gainers: radar.tvl.gainers.slice(0, limit),
+ losers: radar.tvl.losers.slice(0, limit),
+ },
+ fees: { total_24h_usd: radar.fees.total_24h_usd, top: radar.fees.top.slice(0, limit) },
+ dex: { total_24h_usd: radar.dex.total_24h_usd, top: radar.dex.top.slice(0, limit) },
+ ts: new Date().toISOString(),
+ };
+ },
+});
diff --git a/api/x402/gas-oracle.js b/api/x402/gas-oracle.js
new file mode 100644
index 000000000..4c3633d80
--- /dev/null
+++ b/api/x402/gas-oracle.js
@@ -0,0 +1,261 @@
+// GET /api/x402/gas-oracle
+//
+// Multi-Chain Gas Oracle — $0.001 USDC per call on Solana or Base. Live
+// transaction-fee intelligence across the chains agents actually settle on:
+// Ethereum and Base each return slow / standard / fast tiers computed from
+// real eth_feeHistory percentiles over the last 20 blocks (no third-party
+// gas API), and Solana returns recent priority-fee percentiles plus the base
+// signature fee.
+//
+// Computed directly from public RPC quorums with per-chain failover. A chain
+// whose RPCs are all unreachable reports null while the rest of the report
+// stays live (documented in the output schema); if EVERY chain fails the
+// handler throws BEFORE settlement so the buyer is 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 listing from '../_lib/service-catalog/services/gas-oracle.js';
+
+const ROUTE = '/api/x402/gas-oracle';
+const DESCRIPTION = listing.description;
+
+const TTL_MS = 15_000;
+
+// Keyless public JSON-RPC endpoints per chain, tried in order (same failover
+// approach as the free ETH-only /api/coin/gas page endpoint).
+const EVM_RPCS = {
+ ethereum: [
+ 'https://ethereum-rpc.publicnode.com',
+ 'https://eth.llamarpc.com',
+ 'https://rpc.ankr.com/eth',
+ 'https://cloudflare-eth.com',
+ ],
+ base: [
+ 'https://mainnet.base.org',
+ 'https://base-rpc.publicnode.com',
+ 'https://base.llamarpc.com',
+ ],
+};
+
+const SOLANA_RPCS = [
+ 'https://solana-rpc.publicnode.com',
+ 'https://api.mainnet-beta.solana.com',
+];
+
+let _cache = null; // { value, expiresAt }
+
+const hexToNum = (h) => (typeof h === 'string' ? parseInt(h, 16) : Number(h));
+const weiToGwei = (wei) => wei / 1e9;
+
+function median(arr) {
+ if (!arr.length) return 0;
+ const s = [...arr].sort((a, b) => a - b);
+ const m = Math.floor(s.length / 2);
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
+}
+
+function percentile(sorted, p) {
+ if (!sorted.length) return 0;
+ const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));
+ return sorted[idx];
+}
+
+async function rpc(url, methodName, 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: methodName, params }),
+ signal: AbortSignal.timeout(6000),
+ });
+ if (!resp.ok) throw new Error(`rpc ${resp.status}`);
+ const body = await resp.json();
+ if (body.error) throw new Error(body.error.message || 'rpc error');
+ return body.result;
+}
+
+// slow/standard/fast tiers from a 20-block eth_feeHistory: pending base fee +
+// the median 25th/50th/90th priority-fee percentile across sampled blocks.
+async function evmGas(chain) {
+ let lastErr;
+ for (const url of EVM_RPCS[chain]) {
+ try {
+ const fh = await rpc(url, 'eth_feeHistory', ['0x14', 'latest', [25, 50, 90]]);
+ if (!fh?.baseFeePerGas?.length || !fh?.reward?.length) continue;
+
+ const baseFees = fh.baseFeePerGas.map(hexToNum).filter(Number.isFinite);
+ const baseFee = baseFees[baseFees.length - 1];
+ const cols = [[], [], []];
+ for (const row of fh.reward) {
+ if (!Array.isArray(row)) continue;
+ row.forEach((v, i) => {
+ const n = hexToNum(v);
+ if (Number.isFinite(n) && i < 3) cols[i].push(n);
+ });
+ }
+ const priorities = cols.map(median);
+ return {
+ base_fee_gwei: weiToGwei(baseFee),
+ tiers: ['slow', 'standard', 'fast'].map((key, i) => ({
+ key,
+ priority_fee_gwei: weiToGwei(priorities[i]),
+ gas_price_gwei: weiToGwei(baseFee + priorities[i]),
+ })),
+ };
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw lastErr || new Error(`all ${chain} RPCs failed`);
+}
+
+// Solana fee posture: recent prioritization fees (micro-lamports per compute
+// unit) as p25/p50/p90 across the sampled slots, plus the fixed base
+// signature fee.
+async function solanaGas() {
+ let lastErr;
+ for (const url of SOLANA_RPCS) {
+ try {
+ const fees = await rpc(url, 'getRecentPrioritizationFees', [[]]);
+ if (!Array.isArray(fees) || !fees.length) continue;
+ const values = fees
+ .map((f) => Number(f?.prioritizationFee))
+ .filter((n) => Number.isFinite(n) && n >= 0)
+ .sort((a, b) => a - b);
+ if (!values.length) continue;
+ return {
+ priority_fee_micro_lamports: {
+ p25: percentile(values, 25),
+ p50: percentile(values, 50),
+ p90: percentile(values, 90),
+ },
+ base_fee_lamports: 5000,
+ sampled_slots: values.length,
+ };
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw lastErr || new Error('all Solana RPCs failed');
+}
+
+async function loadGas() {
+ const now = Date.now();
+ if (_cache && _cache.expiresAt > now) return _cache.value;
+
+ const [eth, base, sol] = await Promise.allSettled([
+ evmGas('ethereum'),
+ evmGas('base'),
+ solanaGas(),
+ ]);
+ const value = {
+ ethereum: eth.status === 'fulfilled' ? eth.value : null,
+ base: base.status === 'fulfilled' ? base.value : null,
+ solana: sol.status === 'fulfilled' ? sol.value : null,
+ };
+ if (!value.ethereum && !value.base && !value.solana) {
+ throw new Error('all chains failed');
+ }
+ _cache = { value, expiresAt: now + TTL_MS };
+ return value;
+}
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ ...listing.inputSchema,
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['ethereum', 'base', 'solana', 'ts'],
+ properties: {
+ ethereum: {
+ type: ['object', 'null'],
+ description: 'null only when every Ethereum RPC in the failover set is unreachable.',
+ properties: {
+ base_fee_gwei: { type: 'number' },
+ tiers: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['key', 'priority_fee_gwei', 'gas_price_gwei'],
+ properties: {
+ key: { type: 'string', enum: ['slow', 'standard', 'fast'] },
+ priority_fee_gwei: { type: 'number' },
+ gas_price_gwei: { type: 'number' },
+ },
+ },
+ },
+ },
+ },
+ base: {
+ type: ['object', 'null'],
+ description: 'Same shape as ethereum; null only when every Base RPC is unreachable.',
+ },
+ solana: {
+ type: ['object', 'null'],
+ properties: {
+ priority_fee_micro_lamports: {
+ type: 'object',
+ required: ['p25', 'p50', 'p90'],
+ properties: {
+ p25: { type: 'number' },
+ p50: { type: 'number' },
+ p90: { type: 'number' },
+ },
+ },
+ base_fee_lamports: { type: 'integer' },
+ sampled_slots: { type: 'integer' },
+ },
+ },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['fee estimation', 'settlement timing', 'multi-chain gas monitoring'],
+ input: {
+ type: 'query',
+ example: listing.input,
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: listing.outputExample,
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('gas-oracle', '1000'), // $0.001 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: listing.serviceName,
+ tags: listing.tags,
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler() {
+ let gas = null;
+ try { gas = await loadGas(); } catch { /* refund below */ }
+ if (!gas) {
+ throw Object.assign(new Error('gas data is temporarily unavailable on every chain'), {
+ status: 503,
+ code: 'data_unavailable',
+ });
+ }
+ return { ...gas, ts: new Date().toISOString() };
+ },
+});
diff --git a/api/x402/hack-check.js b/api/x402/hack-check.js
new file mode 100644
index 000000000..0774cbbce
--- /dev/null
+++ b/api/x402/hack-check.js
@@ -0,0 +1,210 @@
+// GET /api/x402/hack-check?protocol=&limit=
+//
+// Exploit History Check — $0.002 USDC per call on Solana or Base. Runs a
+// protocol name against the full historical DeFi exploit database and returns
+// a clean / incident-history verdict with every matching incident (date,
+// amount, technique, chains, recovered funds) plus market-wide loss stats.
+// Omit ?protocol= for the latest incidents market-wide.
+//
+// Data is live: api.llama.fi/hacks (keyless), cached 10 min in-memory — the
+// same upstream the free /api/defi/hacks page endpoint renders; this paid
+// surface adds the per-protocol verdict agents act on. A truthful zero-match
+// answer is a valid billable result; upstream outages throw BEFORE settlement.
+
+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 listing from '../_lib/service-catalog/services/hack-check.js';
+
+const ROUTE = '/api/x402/hack-check';
+const DESCRIPTION = listing.description;
+
+const TTL_MS = 600_000;
+const YEAR_MS = 365 * 24 * 60 * 60 * 1000;
+
+let _cache = null; // { hacks, stats, expiresAt }
+
+function normalizeChains(chain) {
+ if (Array.isArray(chain)) return chain.filter((c) => typeof c === 'string' && c.length);
+ if (typeof chain === 'string' && chain.length) return [chain];
+ return [];
+}
+
+async function loadDataset() {
+ const now = Date.now();
+ if (_cache && _cache.expiresAt > now) return _cache;
+
+ const r = await fetch('https://api.llama.fi/hacks', {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!r.ok) throw new Error(`llama hacks ${r.status}`);
+ const raw = await r.json();
+ if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');
+
+ const hacks = [];
+ for (const h of raw) {
+ const dateSec = Number(h?.date);
+ if (!Number.isFinite(dateSec)) continue;
+ const amount = Number(h?.amount);
+ const returned = Number(h?.returnedFunds);
+ hacks.push({
+ date: new Date(dateSec * 1000).toISOString(),
+ _dateMs: dateSec * 1000,
+ name: typeof h.name === 'string' && h.name.length ? h.name : 'Unknown',
+ amount_usd: Number.isFinite(amount) && amount >= 0 ? amount : null,
+ technique: typeof h.technique === 'string' ? h.technique : null,
+ classification: typeof h.classification === 'string' ? h.classification : null,
+ chains: normalizeChains(h.chain),
+ bridge: h.bridgeHack === true,
+ returned_usd: Number.isFinite(returned) && returned > 0 ? returned : null,
+ source: typeof h.source === 'string' && /^https?:\/\//i.test(h.source) ? h.source : null,
+ });
+ }
+ hacks.sort((a, b) => b._dateMs - a._dateMs);
+
+ const cutoff = now - YEAR_MS;
+ let totalAllTime = 0;
+ let total12mo = 0;
+ let incidents12mo = 0;
+ let bridgeAllTime = 0;
+ for (const h of hacks) {
+ const amt = h.amount_usd || 0;
+ totalAllTime += amt;
+ if (h.bridge) bridgeAllTime += amt;
+ if (h._dateMs >= cutoff) {
+ total12mo += amt;
+ incidents12mo += 1;
+ }
+ }
+
+ _cache = {
+ hacks,
+ stats: {
+ total_stolen_all_time: totalAllTime,
+ total_stolen_12mo: total12mo,
+ incidents_12mo: incidents12mo,
+ bridge_hack_share_pct: totalAllTime > 0 ? (bridgeAllTime / totalAllTime) * 100 : 0,
+ },
+ expiresAt: now + TTL_MS,
+ };
+ return _cache;
+}
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ ...listing.inputSchema,
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['query', 'verdict', 'matches', 'total_lost_usd', 'incidents', 'stats', 'ts'],
+ properties: {
+ query: { type: ['string', 'null'] },
+ verdict: { type: 'string', enum: ['clean', 'incident-history', 'market-wide'] },
+ matches: { type: 'integer' },
+ total_lost_usd: { type: 'number' },
+ incidents: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['date', 'name', 'amount_usd'],
+ properties: {
+ date: { type: 'string', format: 'date-time' },
+ name: { type: 'string' },
+ amount_usd: { type: ['number', 'null'] },
+ technique: { type: ['string', 'null'] },
+ classification: { type: ['string', 'null'] },
+ chains: { type: 'array', items: { type: 'string' } },
+ bridge: { type: 'boolean' },
+ returned_usd: { type: ['number', 'null'] },
+ source: { type: ['string', 'null'] },
+ },
+ },
+ },
+ stats: {
+ type: 'object',
+ required: ['total_stolen_all_time', 'total_stolen_12mo', 'incidents_12mo', 'bridge_hack_share_pct'],
+ properties: {
+ total_stolen_all_time: { type: 'number' },
+ total_stolen_12mo: { type: 'number' },
+ incidents_12mo: { type: 'integer' },
+ bridge_hack_share_pct: { type: 'number' },
+ },
+ },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['protocol due-diligence', 'exploit history lookup', 'integration risk check'],
+ input: {
+ type: 'query',
+ example: listing.input,
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: listing.outputExample,
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('hack-check', '2000'), // $0.002 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: listing.serviceName,
+ tags: listing.tags,
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const protocol = (params.get('protocol') || '').trim().slice(0, 80) || null;
+ const limitRaw = Number(params.get('limit') || '10');
+ const limit = Math.min(50, Math.max(1, Number.isFinite(limitRaw) ? Math.floor(limitRaw) : 10));
+
+ let data = null;
+ try { data = await loadDataset(); } catch { /* refund below */ }
+ if (!data || !data.hacks.length) {
+ throw Object.assign(new Error('exploit database is temporarily unavailable'), {
+ status: 503,
+ code: 'data_unavailable',
+ });
+ }
+
+ let matched = data.hacks;
+ let verdict = 'market-wide';
+ if (protocol) {
+ const needle = protocol.toLowerCase();
+ matched = data.hacks.filter((h) => h.name.toLowerCase().includes(needle));
+ verdict = matched.length ? 'incident-history' : 'clean';
+ }
+
+ const totalLost = matched.reduce((s, h) => s + (h.amount_usd || 0), 0);
+ const incidents = matched.slice(0, limit).map(({ _dateMs, ...h }) => h);
+
+ return {
+ query: protocol,
+ verdict,
+ matches: matched.length,
+ total_lost_usd: totalLost,
+ incidents,
+ stats: data.stats,
+ ts: new Date().toISOString(),
+ };
+ },
+});
diff --git a/api/x402/market-categories.js b/api/x402/market-categories.js
new file mode 100644
index 000000000..98fbb8eae
--- /dev/null
+++ b/api/x402/market-categories.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-categories');
diff --git a/api/x402/market-chains.js b/api/x402/market-chains.js
new file mode 100644
index 000000000..4c1cf22e9
--- /dev/null
+++ b/api/x402/market-chains.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-chains');
diff --git a/api/x402/market-chart.js b/api/x402/market-chart.js
new file mode 100644
index 000000000..5b027ffd6
--- /dev/null
+++ b/api/x402/market-chart.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-chart');
diff --git a/api/x402/market-coin.js b/api/x402/market-coin.js
new file mode 100644
index 000000000..2c3d2e9a3
--- /dev/null
+++ b/api/x402/market-coin.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-coin');
diff --git a/api/x402/market-coins.js b/api/x402/market-coins.js
new file mode 100644
index 000000000..f77554b45
--- /dev/null
+++ b/api/x402/market-coins.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-coins');
diff --git a/api/x402/market-defi.js b/api/x402/market-defi.js
new file mode 100644
index 000000000..aa2eae4f7
--- /dev/null
+++ b/api/x402/market-defi.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-defi');
diff --git a/api/x402/market-derivatives.js b/api/x402/market-derivatives.js
new file mode 100644
index 000000000..4f8392c65
--- /dev/null
+++ b/api/x402/market-derivatives.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-derivatives');
diff --git a/api/x402/market-dex-volumes.js b/api/x402/market-dex-volumes.js
new file mode 100644
index 000000000..d09207b95
--- /dev/null
+++ b/api/x402/market-dex-volumes.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-dex-volumes');
diff --git a/api/x402/market-exchanges.js b/api/x402/market-exchanges.js
new file mode 100644
index 000000000..824b63d91
--- /dev/null
+++ b/api/x402/market-exchanges.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-exchanges');
diff --git a/api/x402/market-fees.js b/api/x402/market-fees.js
new file mode 100644
index 000000000..12d4bf70e
--- /dev/null
+++ b/api/x402/market-fees.js
@@ -0,0 +1,6 @@
+// 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';
+
+export default marketEndpoint('market-fees');
diff --git a/api/x402/market-gas.js b/api/x402/market-gas.js
new file mode 100644
index 000000000..af49c1e5c
--- /dev/null
+++ b/api/x402/market-gas.js
@@ -0,0 +1,6 @@
+// GET /api/x402/market-gas — 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';
+
+export default marketEndpoint('market-gas');
diff --git a/api/x402/market-global.js b/api/x402/market-global.js
new file mode 100644
index 000000000..1926d0940
--- /dev/null
+++ b/api/x402/market-global.js
@@ -0,0 +1,6 @@
+// GET /api/x402/market-global — 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';
+
+export default marketEndpoint('market-global');
diff --git a/api/x402/market-hacks.js b/api/x402/market-hacks.js
new file mode 100644
index 000000000..882538c48
--- /dev/null
+++ b/api/x402/market-hacks.js
@@ -0,0 +1,6 @@
+// GET /api/x402/market-hacks — 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';
+
+export default marketEndpoint('market-hacks');
diff --git a/api/x402/market-heatmap.js b/api/x402/market-heatmap.js
new file mode 100644
index 000000000..200d29875
--- /dev/null
+++ b/api/x402/market-heatmap.js
@@ -0,0 +1,219 @@
+// GET /api/x402/market-heatmap?limit=50
+//
+// Market Heatmap — $0.002 USDC per call on Solana or Base. Returns the top
+// coins by market cap with 1 h / 24 h / 7 d momentum plus market-breadth
+// statistics (advancers vs decliners, average and median move) in one
+// normalized snapshot.
+//
+// Dual live sources with automatic failover: CoinGecko /coins/markets first
+// (richest fields), CoinPaprika /tickers second (keyless, generous quota) —
+// so one upstream rate-limit never breaks a paid call. Cached 60 s in-memory.
+// No mock path — if both sources fail the handler throws BEFORE settlement
+// so the buyer is 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 listing from '../_lib/service-catalog/services/market-heatmap.js';
+
+const ROUTE = '/api/x402/market-heatmap';
+const DESCRIPTION = listing.description;
+
+const TTL_MS = 60_000;
+const MAX_LIMIT = 100;
+
+let _cache = null; // { coins, source, expiresAt }
+
+const finite = (n) => (Number.isFinite(n) ? n : null);
+
+async function fetchCoinGecko() {
+ const url =
+ 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc' +
+ `&per_page=${MAX_LIMIT}&page=1&sparkline=false&price_change_percentage=1h%2C24h%2C7d`;
+ const r = await fetch(url, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!r.ok) throw new Error(`coingecko ${r.status}`);
+ 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,
+ symbol: typeof c.symbol === 'string' ? c.symbol.toUpperCase() : null,
+ name: typeof c.name === 'string' ? c.name : null,
+ price_usd: finite(Number(c.current_price)),
+ change_1h: finite(Number(c.price_change_percentage_1h_in_currency)),
+ change_24h: finite(Number(c.price_change_percentage_24h_in_currency ?? c.price_change_percentage_24h)),
+ change_7d: finite(Number(c.price_change_percentage_7d_in_currency)),
+ market_cap_usd: finite(Number(c.market_cap)),
+ volume_24h_usd: finite(Number(c.total_volume)),
+ }));
+}
+
+async function fetchCoinPaprika() {
+ const r = await fetch('https://api.coinpaprika.com/v1/tickers?quotes=USD', {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!r.ok) throw new Error(`coinpaprika ${r.status}`);
+ const raw = await r.json();
+ if (!Array.isArray(raw) || !raw.length) throw new Error('coinpaprika empty');
+ return raw
+ .filter((c) => Number.isFinite(Number(c?.rank)) && Number(c.rank) > 0 && c?.quotes?.USD)
+ .sort((a, b) => Number(a.rank) - Number(b.rank))
+ .slice(0, MAX_LIMIT)
+ .map((c) => {
+ const q = c.quotes.USD;
+ return {
+ rank: Number(c.rank),
+ symbol: typeof c.symbol === 'string' ? c.symbol.toUpperCase() : null,
+ name: typeof c.name === 'string' ? c.name : null,
+ price_usd: finite(Number(q.price)),
+ change_1h: finite(Number(q.percent_change_1h)),
+ change_24h: finite(Number(q.percent_change_24h)),
+ change_7d: finite(Number(q.percent_change_7d)),
+ market_cap_usd: finite(Number(q.market_cap)),
+ volume_24h_usd: finite(Number(q.volume_24h)),
+ };
+ });
+}
+
+async function loadBoard() {
+ const now = Date.now();
+ if (_cache && _cache.expiresAt > now) return _cache;
+
+ let coins = null;
+ let source = null;
+ try {
+ coins = await fetchCoinGecko();
+ source = 'coingecko';
+ } catch {
+ coins = await fetchCoinPaprika(); // throws through to the caller if it also fails
+ source = 'coinpaprika';
+ }
+
+ _cache = { coins, source, expiresAt: now + TTL_MS };
+ return _cache;
+}
+
+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;
+ const flat = moves.length - advancers - decliners;
+ const avg = moves.length ? moves.reduce((s, n) => s + n, 0) / moves.length : null;
+ let median = null;
+ if (moves.length) {
+ const s = [...moves].sort((a, b) => a - b);
+ const m = Math.floor(s.length / 2);
+ median = s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
+ }
+ return {
+ advancers,
+ decliners,
+ flat,
+ avg_change_24h: avg != null ? Number(avg.toFixed(2)) : null,
+ median_change_24h: median != null ? Number(median.toFixed(2)) : null,
+ };
+}
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ ...listing.inputSchema,
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['breadth', 'coins', 'source', 'ts'],
+ properties: {
+ breadth: {
+ type: 'object',
+ required: ['advancers', 'decliners', 'flat', 'avg_change_24h', 'median_change_24h'],
+ properties: {
+ advancers: { type: 'integer' },
+ decliners: { type: 'integer' },
+ flat: { type: 'integer' },
+ avg_change_24h: { type: ['number', 'null'] },
+ median_change_24h: { type: ['number', 'null'] },
+ },
+ },
+ coins: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['rank', 'symbol', 'price_usd', 'change_24h', 'market_cap_usd'],
+ properties: {
+ rank: { type: 'integer' },
+ symbol: { type: ['string', 'null'] },
+ name: { type: ['string', 'null'] },
+ price_usd: { type: ['number', 'null'] },
+ change_1h: { type: ['number', 'null'] },
+ change_24h: { type: ['number', 'null'] },
+ change_7d: { type: ['number', 'null'] },
+ market_cap_usd: { type: ['number', 'null'] },
+ volume_24h_usd: { type: ['number', 'null'] },
+ },
+ },
+ },
+ source: { type: 'string', enum: ['coingecko', 'coinpaprika'] },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['market overview', 'momentum screening', 'breadth analysis'],
+ input: {
+ type: 'query',
+ example: listing.input,
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: listing.outputExample,
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('market-heatmap', '2000'), // $0.002 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: listing.serviceName,
+ tags: listing.tags,
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const raw = Number(new URL(req.url, 'http://x').searchParams.get('limit') || '50');
+ const limit = Math.min(MAX_LIMIT, Math.max(1, Number.isFinite(raw) ? Math.floor(raw) : 50));
+
+ let board = null;
+ try { board = await loadBoard(); } catch { /* refund below */ }
+ if (!board || !board.coins.length) {
+ throw Object.assign(new Error('market data is temporarily unavailable'), {
+ status: 503,
+ code: 'data_unavailable',
+ });
+ }
+
+ const coins = board.coins.slice(0, limit);
+ return {
+ breadth: breadth(coins),
+ coins,
+ source: board.source,
+ ts: new Date().toISOString(),
+ };
+ },
+});
diff --git a/api/x402/market-mood.js b/api/x402/market-mood.js
new file mode 100644
index 000000000..c97c51008
--- /dev/null
+++ b/api/x402/market-mood.js
@@ -0,0 +1,246 @@
+// GET /api/x402/market-mood
+//
+// Market Mood Index — $0.002 USDC per call on Solana or Base. A composite
+// market-mood reading no single index gives you: blends the Crypto Fear &
+// Greed index (positioning) with live lexicon sentiment scored across the
+// newest headlines from the three.ws 192-feed news engine (narrative) into
+// one 0–100 mood score — and reports when the two components disagree,
+// which is the divergence signal.
+//
+// Data is live: alternative.me /fng (the standard free Fear & Greed source,
+// same upstream as the free /api/coin/fear-greed page endpoint) plus the
+// in-repo news engine (api/_lib/news.js). Both components must be live or
+// the handler throws BEFORE settlement — a mood score with a dead component
+// would be fabricated, and the buyer is never charged for one.
+
+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 { getNews } from '../_lib/news.js';
+import listing from '../_lib/service-catalog/services/market-mood.js';
+
+const ROUTE = '/api/x402/market-mood';
+const DESCRIPTION = listing.description;
+
+const TTL_MS = 300_000;
+const NEWS_SAMPLE = 120;
+const FNG_WEIGHT = 0.6; // positioning
+const NEWS_WEIGHT = 0.4; // narrative
+const DRIVER_COUNT = 3;
+
+let _cache = null; // { value, expiresAt }
+
+function classify(v) {
+ if (v <= 25) return 'Extreme Fear';
+ if (v <= 45) return 'Fear';
+ if (v <= 55) return 'Neutral';
+ if (v <= 75) return 'Greed';
+ return 'Extreme Greed';
+}
+
+async function fetchFearGreed() {
+ const r = await fetch('https://api.alternative.me/fng/?limit=2', {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!r.ok) throw new Error(`fng ${r.status}`);
+ const raw = await r.json();
+ const rows = Array.isArray(raw?.data) ? raw.data : [];
+ const today = Number(rows[0]?.value);
+ if (!Number.isFinite(today)) throw new Error('fng empty');
+ const yesterday = Number(rows[1]?.value);
+ return {
+ value: today,
+ label: classify(today),
+ change_24h: Number.isFinite(yesterday) ? today - yesterday : null,
+ };
+}
+
+// Aggregate lexicon sentiment over the newest headlines. Articles arrive with
+// a pre-scored { score, label } from api/_lib/news.js; this rolls them up into
+// one confidence-agnostic narrative reading plus the strongest drivers.
+async function fetchNewsMood() {
+ const { articles } = await getNews({ limit: NEWS_SAMPLE });
+ if (!Array.isArray(articles) || !articles.length) throw new Error('news feed empty');
+
+ let sum = 0;
+ let positive = 0;
+ let negative = 0;
+ let neutral = 0;
+ for (const a of articles) {
+ const s = Number(a?.sentiment?.score) || 0;
+ sum += s;
+ if (s > 0.1) positive++;
+ else if (s < -0.1) negative++;
+ else neutral++;
+ }
+ const score = sum / articles.length;
+
+ const driver = (a) => ({
+ title: a.title,
+ source: a.source || null,
+ link: a.link || null,
+ });
+ const scored = articles.filter((a) => Number.isFinite(Number(a?.sentiment?.score)));
+ const bullish = [...scored]
+ .sort((a, b) => b.sentiment.score - a.sentiment.score)
+ .filter((a) => a.sentiment.score > 0.1)
+ .slice(0, DRIVER_COUNT)
+ .map(driver);
+ const bearish = [...scored]
+ .sort((a, b) => a.sentiment.score - b.sentiment.score)
+ .filter((a) => a.sentiment.score < -0.1)
+ .slice(0, DRIVER_COUNT)
+ .map(driver);
+
+ return {
+ score: Number(score.toFixed(3)),
+ label: score > 0.1 ? 'positive' : score < -0.1 ? 'negative' : 'neutral',
+ articles_scored: articles.length,
+ positive,
+ negative,
+ neutral,
+ drivers: { bullish, bearish },
+ };
+}
+
+async function loadMood() {
+ const now = Date.now();
+ if (_cache && _cache.expiresAt > now) return _cache.value;
+
+ // Both components are required — Promise.all rejects if either is down and
+ // the caller refunds. A one-legged "composite" would be a fabricated signal.
+ const [fng, news] = await Promise.all([fetchFearGreed(), fetchNewsMood()]);
+
+ // News score is -1..1; map to 0..100 and blend with Fear & Greed.
+ const newsIndex = ((news.score + 1) / 2) * 100;
+ const mood = Math.round(FNG_WEIGHT * fng.value + NEWS_WEIGHT * newsIndex);
+
+ // Divergence: positioning and narrative pointing different directions is the
+ // actionable part of a composite — surface it explicitly.
+ const fngBullish = fng.value > 55;
+ const fngBearish = fng.value < 45;
+ const newsBullish = news.label === 'positive';
+ const newsBearish = news.label === 'negative';
+ const divergence =
+ (fngBullish && newsBearish) || (fngBearish && newsBullish) ? 'diverging' : 'aligned';
+
+ const value = {
+ mood,
+ label: classify(mood),
+ divergence,
+ components: {
+ fear_greed: { value: fng.value, label: fng.label, change_24h: fng.change_24h },
+ news: {
+ score: news.score,
+ label: news.label,
+ articles_scored: news.articles_scored,
+ positive: news.positive,
+ negative: news.negative,
+ neutral: news.neutral,
+ },
+ },
+ drivers: news.drivers,
+ };
+ _cache = { value, expiresAt: now + TTL_MS };
+ return value;
+}
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ ...listing.inputSchema,
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['mood', 'label', 'divergence', 'components', 'drivers', 'ts'],
+ properties: {
+ mood: { type: 'integer', minimum: 0, maximum: 100 },
+ label: { type: 'string', enum: ['Extreme Fear', 'Fear', 'Neutral', 'Greed', 'Extreme Greed'] },
+ divergence: { type: 'string', enum: ['aligned', 'diverging'] },
+ components: {
+ type: 'object',
+ required: ['fear_greed', 'news'],
+ properties: {
+ fear_greed: {
+ type: 'object',
+ required: ['value', 'label', 'change_24h'],
+ properties: {
+ value: { type: 'number' },
+ label: { type: 'string' },
+ change_24h: { type: ['number', 'null'] },
+ },
+ },
+ news: {
+ type: 'object',
+ required: ['score', 'label', 'articles_scored', 'positive', 'negative', 'neutral'],
+ properties: {
+ score: { type: 'number', minimum: -1, maximum: 1 },
+ label: { type: 'string', enum: ['positive', 'negative', 'neutral'] },
+ articles_scored: { type: 'integer' },
+ positive: { type: 'integer' },
+ negative: { type: 'integer' },
+ neutral: { type: 'integer' },
+ },
+ },
+ },
+ },
+ drivers: {
+ type: 'object',
+ required: ['bullish', 'bearish'],
+ properties: {
+ bullish: { type: 'array', items: { type: 'object' } },
+ bearish: { type: 'array', items: { type: 'object' } },
+ },
+ },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['market sentiment', 'fear-greed composite', 'narrative divergence'],
+ input: {
+ type: 'query',
+ example: listing.input,
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: listing.outputExample,
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('market-mood', '2000'), // $0.002 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: listing.serviceName,
+ tags: listing.tags,
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler() {
+ let mood = null;
+ try { mood = await loadMood(); } catch { /* refund below */ }
+ if (!mood) {
+ throw Object.assign(new Error('mood components are temporarily unavailable'), {
+ status: 503,
+ code: 'data_unavailable',
+ });
+ }
+ return { ...mood, ts: new Date().toISOString() };
+ },
+});
diff --git a/api/x402/market-pulse.js b/api/x402/market-pulse.js
new file mode 100644
index 000000000..8f0ad5a15
--- /dev/null
+++ b/api/x402/market-pulse.js
@@ -0,0 +1,6 @@
+// GET /api/x402/market-pulse — 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';
+
+export default marketEndpoint('market-pulse');
diff --git a/api/x402/market-stablecoins.js b/api/x402/market-stablecoins.js
new file mode 100644
index 000000000..dfce9985c
--- /dev/null
+++ b/api/x402/market-stablecoins.js
@@ -0,0 +1,6 @@
+// GET /api/x402/market-stablecoins — 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';
+
+export default marketEndpoint('market-stablecoins');
diff --git a/api/x402/market-trending.js b/api/x402/market-trending.js
new file mode 100644
index 000000000..1cac630e1
--- /dev/null
+++ b/api/x402/market-trending.js
@@ -0,0 +1,6 @@
+// GET /api/x402/market-trending — 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';
+
+export default marketEndpoint('market-trending');
diff --git a/api/x402/market-yields.js b/api/x402/market-yields.js
new file mode 100644
index 000000000..55d6355a9
--- /dev/null
+++ b/api/x402/market-yields.js
@@ -0,0 +1,6 @@
+// GET /api/x402/market-yields — 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';
+
+export default marketEndpoint('market-yields');
diff --git a/api/x402/market.js b/api/x402/market.js
new file mode 100644
index 000000000..9a2696e94
--- /dev/null
+++ b/api/x402/market.js
@@ -0,0 +1,60 @@
+// 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
+// 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,
+// data costs a micro-payment.
+
+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';
+
+const usd = (atomics) => {
+ const n = Number(atomics) / 1_000_000;
+ return `$${n.toFixed(n < 0.01 ? 3 : 2).replace(/0+$/, '').replace(/\.$/, '')}`;
+};
+
+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';
+ return json(
+ res,
+ 200,
+ {
+ name: MARKET_SERVICE_NAME,
+ description:
+ 'Pay-per-call crypto market data for agents — the same live feeds behind the three.ws /markets pages, ' +
+ 'sold as x402 endpoints (HTTP 402, USDC on Solana or Base). No API key, no subscription, no rate-limit ' +
+ 'negotiation: request an endpoint, get a 402 challenge, pay ~$0.001 USDC, get the data.',
+ how_to_pay:
+ 'GET any endpoint below without payment to receive its 402 challenge (price, networks, pay-to). ' +
+ '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`,
+ 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()}`
+ : ''
+ }`,
+ })),
+ },
+ { 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1800' },
+ );
+});
diff --git a/api/x402/news-pulse.js b/api/x402/news-pulse.js
new file mode 100644
index 000000000..365a739e0
--- /dev/null
+++ b/api/x402/news-pulse.js
@@ -0,0 +1,209 @@
+// GET /api/x402/news-pulse?ticker=BTC&hours=24
+//
+// Ticker News Pulse — $0.002 USDC per call on Solana or Base. Measures how
+// loudly the news cycle is talking about one ticker right now: mention count
+// across the live output of the three.ws 192-feed news engine, unique outlets,
+// sentiment split, coverage velocity vs the immediately preceding window, and
+// the top headlines with links.
+//
+// Data is live: the in-repo news engine (api/_lib/news.js) — the same 192
+// publisher feeds behind the free three.ws news API; articles arrive with
+// tickers and lexicon sentiment pre-extracted. Zero mentions is a truthful,
+// billable answer (silence is a signal). A dead feed engine throws BEFORE
+// settlement so the buyer is 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 { getNews } from '../_lib/news.js';
+import listing from '../_lib/service-catalog/services/news-pulse.js';
+
+const ROUTE = '/api/x402/news-pulse';
+const DESCRIPTION = listing.description;
+
+// Wide page so both the current and the preceding comparison window are
+// covered from one engine call; the engine itself caches per-source feeds.
+const SAMPLE_LIMIT = 400;
+const HEADLINE_COUNT = 5;
+const HOUR_MS = 3_600_000;
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ ...listing.inputSchema,
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['ticker', 'window_hours', 'mentions', 'unique_sources', 'velocity', 'sentiment', 'headlines', 'ts'],
+ properties: {
+ ticker: { type: 'string' },
+ window_hours: { type: 'integer', minimum: 1, maximum: 72 },
+ mentions: { type: 'integer' },
+ unique_sources: { type: 'integer' },
+ velocity: {
+ type: 'object',
+ required: ['previous_window_mentions', 'change_pct', 'trend'],
+ properties: {
+ previous_window_mentions: { type: 'integer' },
+ change_pct: { type: ['number', 'null'] },
+ trend: { type: 'string', enum: ['accelerating', 'steady', 'cooling', 'quiet'] },
+ },
+ },
+ sentiment: {
+ type: 'object',
+ required: ['score', 'positive', 'negative', 'neutral'],
+ properties: {
+ score: { type: ['number', 'null'] },
+ positive: { type: 'integer' },
+ negative: { type: 'integer' },
+ neutral: { type: 'integer' },
+ },
+ },
+ headlines: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['title', 'source', 'link', 'pub_date', 'sentiment'],
+ properties: {
+ title: { type: 'string' },
+ source: { type: ['string', 'null'] },
+ link: { type: ['string', 'null'] },
+ pub_date: { type: ['string', 'null'], format: 'date-time' },
+ sentiment: { type: 'string' },
+ },
+ },
+ },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['narrative tracking', 'coverage velocity', 'ticker sentiment'],
+ input: {
+ type: 'query',
+ example: listing.input,
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: listing.outputExample,
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('news-pulse', '2000'), // $0.002 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: listing.serviceName,
+ tags: listing.tags,
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const rawTicker = (params.get('ticker') || '').trim().replace(/^\$/, '').toUpperCase();
+ if (!/^[A-Z0-9]{2,10}$/.test(rawTicker)) {
+ // Validation failure is thrown (not settled) so the buyer is not charged
+ // for a malformed request — the wrapper maps this to a 422 before settle.
+ throw Object.assign(new Error('ticker must be 2–10 alphanumeric characters, e.g. BTC'), {
+ status: 422,
+ code: 'invalid_ticker',
+ });
+ }
+ const hoursRaw = Number(params.get('hours') || '24');
+ const hours = Math.min(72, Math.max(1, Number.isFinite(hoursRaw) ? Math.floor(hoursRaw) : 24));
+
+ let articles = null;
+ let sourcesOk = 0;
+ try {
+ const page = await getNews({ limit: SAMPLE_LIMIT });
+ articles = Array.isArray(page?.articles) ? page.articles : null;
+ sourcesOk = Number(page?.sources_ok) || 0;
+ } catch { /* refund below */ }
+ // An empty engine (no articles from any source) is an outage, not a quiet
+ // ticker — quietness is measured against a live feed, so refund instead.
+ if (!articles || !articles.length || !sourcesOk) {
+ throw Object.assign(new Error('the news feed engine is temporarily unavailable'), {
+ status: 503,
+ code: 'data_unavailable',
+ });
+ }
+
+ const now = Date.now();
+ const windowStart = now - hours * HOUR_MS;
+ const prevStart = now - 2 * hours * HOUR_MS;
+
+ const mentionsTicker = (a) => Array.isArray(a.tickers) && a.tickers.includes(rawTicker);
+ const inWindow = [];
+ const inPrev = [];
+ for (const a of articles) {
+ if (!mentionsTicker(a)) continue;
+ const t = Date.parse(a.pub_date || '');
+ if (!Number.isFinite(t)) continue;
+ if (t >= windowStart) inWindow.push(a);
+ else if (t >= prevStart) inPrev.push(a);
+ }
+
+ let sum = 0;
+ let positive = 0;
+ let negative = 0;
+ let neutral = 0;
+ for (const a of inWindow) {
+ const s = Number(a?.sentiment?.score) || 0;
+ sum += s;
+ if (s > 0.1) positive++;
+ else if (s < -0.1) negative++;
+ else neutral++;
+ }
+
+ const changePct = inPrev.length
+ ? ((inWindow.length - inPrev.length) / inPrev.length) * 100
+ : null;
+ const trend = !inWindow.length && !inPrev.length ? 'quiet'
+ : changePct == null ? (inWindow.length ? 'accelerating' : 'quiet')
+ : changePct > 20 ? 'accelerating'
+ : changePct < -20 ? 'cooling'
+ : 'steady';
+
+ const headlines = inWindow.slice(0, HEADLINE_COUNT).map((a) => ({
+ title: a.title,
+ source: a.source || null,
+ link: a.link || null,
+ pub_date: a.pub_date || null,
+ sentiment: a.sentiment?.label || 'neutral',
+ }));
+
+ return {
+ ticker: rawTicker,
+ window_hours: hours,
+ mentions: inWindow.length,
+ unique_sources: new Set(inWindow.map((a) => a.source_key || a.source)).size,
+ velocity: {
+ previous_window_mentions: inPrev.length,
+ change_pct: changePct != null ? Number(changePct.toFixed(1)) : null,
+ trend,
+ },
+ sentiment: {
+ score: inWindow.length ? Number((sum / inWindow.length).toFixed(3)) : null,
+ positive,
+ negative,
+ neutral,
+ },
+ headlines,
+ ts: new Date().toISOString(),
+ };
+ },
+});
diff --git a/api/x402/stablecoin-health.js b/api/x402/stablecoin-health.js
new file mode 100644
index 000000000..ab5c2a48d
--- /dev/null
+++ b/api/x402/stablecoin-health.js
@@ -0,0 +1,200 @@
+// GET /api/x402/stablecoin-health?symbol=&limit=
+//
+// Stablecoin Peg Monitor — $0.005 USDC per call on Solana or Base. Scores
+// every USD-pegged stablecoin on live peg deviation (bps) with an
+// on-peg / drifting / depegged verdict, circulating supply, and
+// 24 h / 7 d / 30 d supply flow — the signal that front-runs visible depegs.
+//
+// Data is live: stablecoins.llama.fi (keyless), cached 5 min in-memory.
+// No mock path — if the feed is unavailable the handler throws BEFORE
+// settlement so the buyer is 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 listing from '../_lib/service-catalog/services/stablecoin-health.js';
+
+const ROUTE = '/api/x402/stablecoin-health';
+const DESCRIPTION = listing.description;
+
+const TTL_MS = 300_000;
+const DRIFT_BPS = 25;
+const DEPEG_BPS = 100;
+
+let _cache = null; // { coins, totalCirculating, expiresAt }
+
+const finite = (n) => (Number.isFinite(n) ? n : null);
+
+function pctChange(now, prev) {
+ if (!Number.isFinite(now) || !Number.isFinite(prev) || prev <= 0) return null;
+ return ((now - prev) / prev) * 100;
+}
+
+function pegStatus(deviationBps) {
+ if (deviationBps == null) return 'unknown';
+ const abs = Math.abs(deviationBps);
+ if (abs >= DEPEG_BPS) return 'depegged';
+ if (abs >= DRIFT_BPS) return 'drifting';
+ return 'on-peg';
+}
+
+async function loadStablecoins() {
+ const now = Date.now();
+ if (_cache && _cache.expiresAt > now) return _cache;
+
+ const r = await fetch('https://stablecoins.llama.fi/stablecoins?includePrices=true', {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!r.ok) throw new Error(`llama stablecoins ${r.status}`);
+ const raw = await r.json();
+ if (!Array.isArray(raw?.peggedAssets)) throw new Error('unexpected upstream shape');
+
+ let totalCirculating = 0;
+ const coins = [];
+ for (const a of raw.peggedAssets) {
+ // USD-pegged assets only — the bps deviation math below is against $1.
+ if (a?.pegType !== 'peggedUSD') continue;
+ const circulating = Number(a?.circulating?.peggedUSD);
+ if (!Number.isFinite(circulating) || circulating <= 0) continue;
+ totalCirculating += circulating;
+ const price = finite(Number(a.price));
+ const deviationBps = price != null ? Math.round((price - 1) * 10_000) : null;
+ coins.push({
+ symbol: typeof a.symbol === 'string' ? a.symbol : null,
+ name: typeof a.name === 'string' ? a.name : null,
+ price,
+ deviation_bps: deviationBps,
+ status: pegStatus(deviationBps),
+ mechanism: typeof a.pegMechanism === 'string' ? a.pegMechanism : null,
+ circulating_usd: circulating,
+ change_24h_pct: finite(pctChange(circulating, Number(a?.circulatingPrevDay?.peggedUSD))),
+ change_7d_pct: finite(pctChange(circulating, Number(a?.circulatingPrevWeek?.peggedUSD))),
+ change_30d_pct: finite(pctChange(circulating, Number(a?.circulatingPrevMonth?.peggedUSD))),
+ chains: a.chainCirculating && typeof a.chainCirculating === 'object'
+ ? Object.keys(a.chainCirculating).length
+ : 0,
+ });
+ }
+ coins.sort((a, b) => b.circulating_usd - a.circulating_usd);
+
+ _cache = { coins, totalCirculating, expiresAt: now + TTL_MS };
+ return _cache;
+}
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ ...listing.inputSchema,
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['total_circulating_usd', 'depegged', 'coins', 'ts'],
+ properties: {
+ total_circulating_usd: { type: 'number' },
+ depegged: {
+ type: 'array',
+ description: 'Coins currently ≥100 bps off peg, regardless of the page filter.',
+ items: { type: 'object' },
+ },
+ coins: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['symbol', 'price', 'deviation_bps', 'status', 'circulating_usd'],
+ properties: {
+ symbol: { type: ['string', 'null'] },
+ name: { type: ['string', 'null'] },
+ price: { type: ['number', 'null'] },
+ deviation_bps: { type: ['integer', 'null'] },
+ status: { type: 'string', enum: ['on-peg', 'drifting', 'depegged', 'unknown'] },
+ mechanism: { type: ['string', 'null'] },
+ circulating_usd: { type: 'number' },
+ change_24h_pct: { type: ['number', 'null'] },
+ change_7d_pct: { type: ['number', 'null'] },
+ change_30d_pct: { type: ['number', 'null'] },
+ chains: { type: 'integer' },
+ },
+ },
+ },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['stablecoin peg monitoring', 'depeg alerts', 'supply flow tracking'],
+ input: {
+ type: 'query',
+ example: listing.input,
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: listing.outputExample,
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('stablecoin-health', '5000'), // $0.005 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: listing.serviceName,
+ tags: listing.tags,
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const symbol = (params.get('symbol') || '').trim().toUpperCase() || null;
+ const limitRaw = Number(params.get('limit') || '25');
+ const limit = Math.min(100, Math.max(1, Number.isFinite(limitRaw) ? Math.floor(limitRaw) : 25));
+
+ let data = null;
+ try { data = await loadStablecoins(); } catch { /* refund below */ }
+ if (!data || !data.coins.length) {
+ throw Object.assign(new Error('stablecoin data is temporarily unavailable'), {
+ status: 503,
+ code: 'data_unavailable',
+ });
+ }
+
+ let coins = data.coins;
+ if (symbol) coins = coins.filter((c) => c.symbol && c.symbol.toUpperCase() === symbol);
+ if (symbol && !coins.length) {
+ // A named coin that isn't in the dataset is a bad request, not a billable
+ // empty answer — thrown before settlement so the buyer isn't charged.
+ throw Object.assign(new Error(`no USD-pegged stablecoin with symbol ${symbol}`), {
+ status: 422,
+ code: 'unknown_symbol',
+ });
+ }
+
+ // The alert list always spans the whole dataset so a filtered call still
+ // surfaces an active depeg elsewhere in the market.
+ const depegged = data.coins
+ .filter((c) => c.status === 'depegged')
+ .map(({ symbol: s, name, price, deviation_bps, circulating_usd }) => ({
+ symbol: s, name, price, deviation_bps, circulating_usd,
+ }));
+
+ return {
+ total_circulating_usd: data.totalCirculating,
+ depegged,
+ coins: coins.slice(0, limit),
+ ts: new Date().toISOString(),
+ };
+ },
+});
diff --git a/api/x402/yield-scan.js b/api/x402/yield-scan.js
new file mode 100644
index 000000000..94fa993fe
--- /dev/null
+++ b/api/x402/yield-scan.js
@@ -0,0 +1,183 @@
+// GET /api/x402/yield-scan?chain=&stable=&minTvlUsd=&sort=&limit=
+//
+// Yield Scanner — $0.005 USDC per call on Solana or Base. Screens 15,000+
+// live DeFi yield pools in one request: filter by chain, TVL floor, and
+// stablecoin-only exposure; every returned pool carries the APY breakdown
+// and derived risk flags (impermanent loss, APY volatility, apy-spike,
+// upstream outlier marker).
+//
+// Data is live: yields.llama.fi /pools (keyless), cached 10 min in-memory.
+// No mock path — if the pool feed is unavailable the handler throws BEFORE
+// settlement so the buyer is never charged for an empty scan.
+
+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 listing from '../_lib/service-catalog/services/yield-scan.js';
+
+const ROUTE = '/api/x402/yield-scan';
+const DESCRIPTION = listing.description;
+
+const TTL_MS = 600_000;
+const APY_SPIKE_RATIO = 3; // current APY > 3× its 30-day mean → likely transient
+const HIGH_SIGMA = 1; // upstream sigma above this → volatile APY
+
+let _cache = null; // { pools, expiresAt }
+
+const finite = (n) => (Number.isFinite(n) ? n : null);
+
+async function loadPools() {
+ const now = Date.now();
+ if (_cache && _cache.expiresAt > now) return _cache.pools;
+
+ const r = await fetch('https://yields.llama.fi/pools', {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!r.ok) throw new Error(`llama yields ${r.status}`);
+ const raw = await r.json();
+ if (!Array.isArray(raw?.data)) throw new Error('unexpected upstream shape');
+
+ const pools = raw.data
+ .filter((p) => Number.isFinite(Number(p?.tvlUsd)) && Number.isFinite(Number(p?.apy)))
+ .map((p) => ({
+ pool: String(p.pool || ''),
+ project: typeof p.project === 'string' ? p.project : null,
+ symbol: typeof p.symbol === 'string' ? p.symbol : null,
+ chain: typeof p.chain === 'string' ? p.chain : null,
+ tvl_usd: Number(p.tvlUsd),
+ apy: Number(p.apy),
+ apy_base: finite(Number(p.apyBase)),
+ apy_reward: finite(Number(p.apyReward)),
+ apy_mean_30d: finite(Number(p.apyMean30d)),
+ stablecoin: p.stablecoin === true,
+ il_risk: typeof p.ilRisk === 'string' ? p.ilRisk : null,
+ sigma: finite(Number(p.sigma)),
+ exposure: typeof p.exposure === 'string' ? p.exposure : null,
+ prediction: typeof p.predictions?.predictedClass === 'string' ? p.predictions.predictedClass : null,
+ outlier: p.outlier === true,
+ }));
+ _cache = { pools, expiresAt: now + TTL_MS };
+ return pools;
+}
+
+function riskFlags(p) {
+ const flags = [];
+ if (p.il_risk === 'yes') flags.push('impermanent-loss');
+ if (p.sigma != null && p.sigma > HIGH_SIGMA) flags.push('volatile-apy');
+ if (p.apy_mean_30d != null && p.apy_mean_30d > 0 && p.apy > p.apy_mean_30d * APY_SPIKE_RATIO) flags.push('apy-spike');
+ if (p.outlier) flags.push('upstream-outlier');
+ return flags;
+}
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ ...listing.inputSchema,
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['count', 'filters', 'pools', 'ts'],
+ properties: {
+ count: { type: 'integer' },
+ filters: { type: 'object' },
+ pools: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['pool', 'project', 'chain', 'tvl_usd', 'apy', 'risk_flags'],
+ properties: {
+ pool: { type: 'string' },
+ project: { type: ['string', 'null'] },
+ symbol: { type: ['string', 'null'] },
+ chain: { type: ['string', 'null'] },
+ tvl_usd: { type: 'number' },
+ apy: { type: 'number' },
+ apy_base: { type: ['number', 'null'] },
+ apy_reward: { type: ['number', 'null'] },
+ apy_mean_30d: { type: ['number', 'null'] },
+ stablecoin: { type: 'boolean' },
+ il_risk: { type: ['string', 'null'] },
+ sigma: { type: ['number', 'null'] },
+ exposure: { type: ['string', 'null'] },
+ prediction: { type: ['string', 'null'] },
+ risk_flags: { type: 'array', items: { type: 'string' } },
+ },
+ },
+ },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['yield screening', 'stablecoin farming', 'apy risk flags'],
+ input: {
+ type: 'query',
+ example: listing.input,
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: listing.outputExample,
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('yield-scan', '5000'), // $0.005 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: listing.serviceName,
+ tags: listing.tags,
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const chain = (params.get('chain') || '').trim().toLowerCase() || null;
+ const stable = params.get('stable') === 'true' ? true : params.get('stable') === 'false' ? false : null;
+ const minTvlRaw = Number(params.get('minTvlUsd') || '100000');
+ const minTvlUsd = Number.isFinite(minTvlRaw) && minTvlRaw >= 0 ? minTvlRaw : 100_000;
+ const sort = params.get('sort') === 'tvl' ? 'tvl' : 'apy';
+ const limitRaw = Number(params.get('limit') || '20');
+ const limit = Math.min(50, Math.max(1, Number.isFinite(limitRaw) ? Math.floor(limitRaw) : 20));
+
+ let pools = null;
+ try { pools = await loadPools(); } catch { /* refund below */ }
+ if (!pools) {
+ throw Object.assign(new Error('yield pool data is temporarily unavailable'), {
+ status: 503,
+ code: 'data_unavailable',
+ });
+ }
+
+ let filtered = pools.filter((p) => p.tvl_usd >= minTvlUsd);
+ if (chain) filtered = filtered.filter((p) => p.chain && p.chain.toLowerCase() === chain);
+ if (stable !== null) filtered = filtered.filter((p) => p.stablecoin === stable);
+ filtered.sort(sort === 'tvl' ? (a, b) => b.tvl_usd - a.tvl_usd : (a, b) => b.apy - a.apy);
+
+ const page = filtered.slice(0, limit).map((p) => {
+ const { outlier, ...rest } = p;
+ return { ...rest, risk_flags: riskFlags(p) };
+ });
+
+ return {
+ count: filtered.length,
+ filters: { chain, stable, min_tvl_usd: minTvlUsd, sort },
+ pools: page,
+ ts: new Date().toISOString(),
+ };
+ },
+});
diff --git a/data/x402-directory-registrations.json b/data/x402-directory-registrations.json
new file mode 100644
index 000000000..9569784db
--- /dev/null
+++ b/data/x402-directory-registrations.json
@@ -0,0 +1,52 @@
+{
+ "402index": {
+ "https://three.ws/api/x402/model-check": {
+ "ok": true,
+ "status": 201,
+ "at": "2026-07-11T21:25:17.404Z",
+ "response": "{\"message\":\"Service registered and live\",\"service\":{\"id\":\"6befeb09-a8f1-491e-b577-451aa4f3c042\",\"name\":\"three.ws model-check\",\"description\":\"Model Check — an agent handed a 3D asset URL verifies it before using or paying for it: $0.001 USDC per call returns structural stats (vertex/triangle counts, "
+ },
+ "https://three.ws/api/x402/agent-reputation": {
+ "ok": false,
+ "status": 422,
+ "at": "2026-07-11T21:25:18.935Z",
+ "response": "{\"error\":\"x402 verification failed\",\"detail\":\"Endpoint returned 402 but no valid x402 challenge was detected.\",\"probe\":{\"httpStatus\":402,\"headersPresent\":{\"WWW-Authenticate\":false,\"PAYMENT-REQUIRED\":false},\"bodySnippet\":null,\"detectedProtocols\":[]}}"
+ },
+ "https://three.ws/api/x402/agent-bouncer": {
+ "ok": false,
+ "status": 422,
+ "at": "2026-07-11T21:25:19.848Z",
+ "response": "{\"error\":\"x402 verification failed\",\"detail\":\"Endpoint returned 402 but no valid x402 challenge was detected.\",\"probe\":{\"httpStatus\":402,\"headersPresent\":{\"WWW-Authenticate\":false,\"PAYMENT-REQUIRED\":false},\"bodySnippet\":null,\"detectedProtocols\":[]}}"
+ },
+ "https://three.ws/api/x402/onchain-identity-verify": {
+ "ok": true,
+ "status": 201,
+ "at": "2026-07-11T21:25:21.728Z",
+ "response": "{\"message\":\"Service registered and pending review. Verify your domain for instant approval.\",\"service\":{\"id\":\"1a705352-cec8-4b98-b343-08b329fda645\",\"name\":\"three.ws onchain-identity-verify\",\"description\":\"Cross-platform On-Chain Identity Verifier — prove any claim that an identity controls an addres"
+ },
+ "https://three.ws/api/x402/pump-launch": {
+ "ok": true,
+ "status": 201,
+ "at": "2026-07-11T21:25:24.709Z",
+ "response": "{\"message\":\"Service registered and pending review. Verify your domain for instant approval.\",\"service\":{\"id\":\"615b3e87-4716-49d7-8db1-3bda1a89e5aa\",\"name\":\"three.ws pump-launch\",\"description\":\"Pump Launcher — launch a pump.fun token autonomously in one paid call: no SOL, no wallet, no account.\",\"url"
+ },
+ "https://three.ws/api/x402/forge": {
+ "ok": true,
+ "status": 201,
+ "at": "2026-07-11T21:25:26.124Z",
+ "response": "{\"message\":\"Service registered and pending review. Verify your domain for instant approval.\",\"service\":{\"id\":\"20ca300a-a9e9-4ee5-80ae-ff732d65096a\",\"name\":\"three.ws forge\",\"description\":\"Forge — production text/image→3D for agents that need real assets, not drafts: game assets, NFT art, scene props,"
+ },
+ "https://three.ws/api/x402/mint-to-mesh": {
+ "ok": true,
+ "status": 201,
+ "at": "2026-07-11T21:25:27.677Z",
+ "response": "{\"message\":\"Service registered and pending review. Verify your domain for instant approval.\",\"service\":{\"id\":\"e7637454-a63b-47a0-9b79-902005e4bd18\",\"name\":\"three.ws mint-to-mesh\",\"description\":\"Mint to Mesh — pass any Solana SPL token mint, get back a binary glTF (GLB) cube themed and colored from t"
+ },
+ "https://three.ws/api/x402/mint-to-mesh-batch": {
+ "ok": true,
+ "status": 201,
+ "at": "2026-07-11T21:25:29.065Z",
+ "response": "{\"message\":\"Service registered and live\",\"service\":{\"id\":\"1b32e918-ec64-44dd-a952-060ac7eca156\",\"name\":\"three.ws mint-to-mesh-batch\",\"description\":\"Mint to Mesh (Batch) — resolve 1–10 Solana SPL mints to themed glTF (GLB) cubes in a single paid call instead of paying for N round-trips.\",\"url\":\"https"
+ }
+ }
+}
diff --git a/docs/market-data-api.md b/docs/market-data-api.md
new file mode 100644
index 000000000..49416dca3
--- /dev/null
+++ b/docs/market-data-api.md
@@ -0,0 +1,77 @@
+# Market Data API — pay-per-call crypto data over x402
+
+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
+- **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
+
+## Why pay when the pages are free?
+
+The browser pages (`/coins`, `/yields`, `/gas`, …) stay free for humans, with per-IP rate limits sized for browsing. The paid endpoints exist for **agents**: machine discovery through the bazaar, no per-IP rate-limit negotiation, a stable machine contract (input schema + output example published in the discovery doc), and a payment path that works without a human creating an account. Both surfaces run the *same* battle-tested fetch/normalize/cache code (`api/_lib/market-data/` delegates to the exported builders in `api/coin/*` and `api/defi/*`), so the paid data can never drift from what the site shows.
+
+## Endpoints
+
+| Endpoint | Price | What you get |
+| --- | --- | --- |
+| `GET /api/x402/market-coins` | $0.001 | Ranked coin table (price, cap, volume, 24h/7d change, sparkline), up to 250/page; `?category=` sector scoping; `?q=` id search |
+| `GET /api/x402/market-coin` | $0.001 | Full profile for one coin by `?id=` or `?contract=` (Solana mint) — market stats, ATH/ATL, supply, links, dev/community metrics |
+| `GET /api/x402/market-chart` | $0.001 | USD price series for `?id=` over `?days=1\|7\|30\|90\|365` |
+| `GET /api/x402/market-categories` | $0.001 | Every sector ranked by market cap with 24h change |
+| `GET /api/x402/market-exchanges` | $0.001 | Top 100 spot exchanges by trust score, USD volume |
+| `GET /api/x402/market-derivatives` | $0.001 | Perp tickers (funding, OI, volume); `?view=exchanges` for venues |
+| `GET /api/x402/market-global` | $0.001 | Total cap, volume, dominance + Fear & Greed index |
+| `GET /api/x402/market-gas` | $0.001 | ETH gas tiers from on-chain fee history + USD action costs |
+| `GET /api/x402/market-trending` | $0.001 | Most-searched coins, categories, NFTs (24h attention) |
+| `GET /api/x402/market-defi` | $0.001 | Top 100 DeFi protocols by TVL + market totals (CEX excluded) |
+| `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-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 |
+
+Full per-endpoint parameter docs are in the free index (`/api/x402/market`) and in each endpoint's discovery listing.
+
+## Buying a call
+
+Any x402 client works. The raw exchange:
+
+```bash
+# 1. Unpaid request → 402 challenge with price, networks, and pay-to address
+curl -s https://three.ws/api/x402/market-pulse | jq .accepts
+
+# 2. Pay (sign an exact-scheme USDC transfer per the challenge), then retry
+# with the payment envelope — any x402 SDK automates this:
+curl -s -H "X-PAYMENT: <base64 payment payload>" https://three.ws/api/x402/market-pulse
+```
+
+With the [x402 fetch wrapper](https://www.npmjs.com/package/x402-fetch) it's one call:
+
+```js
+import { wrapFetchWithPayment } from 'x402-fetch';
+
+const payFetch = wrapFetchWithPayment(fetch, walletClient); // your signer
+const res = await payFetch('https://three.ws/api/x402/market-pulse');
+const pulse = await res.json(); // { global, fear_greed, top_coins, gas, defi, ... }
+```
+
+A failed upstream never charges you: the endpoint verifies payment, runs the data fetch, and **only settles after the data is in hand**. Invalid params are rejected with a 422 before settlement, upstream outages with a 503 — in both cases no USDC moves.
+
+## Errors
+
+| Status | `error` | Meaning |
+| --- | --- | --- |
+| 402 | `payment_required` | No/invalid payment — body carries the challenge |
+| 404 | `not_found` / `pool_not_found` | Unknown coin id, contract, or pool uuid |
+| 422 | `invalid_*` | A parameter failed validation (message says which) |
+| 503 | `data_unavailable` | Upstream outage — retry shortly; you were not charged |
+
+## Related
+
+- [x402 developer tools](./x402-dev-tools.md) — free test bench for debugging payment envelopes
+- [Crypto Data API](https://three.ws/api/crypto) — the free, keyless Solana/pump.fun bundle (token snapshots, holders, whales)
+- Sibling paid intel endpoints: `market-heatmap`, `market-mood`, `gas-oracle`, `yield-scan`, `stablecoin-health`, `hack-check`, `news-pulse`, `defi-radar` — value-added composites over the same data, also in the discovery doc
+- Data sources: CoinGecko (with CoinPaprika/CoinLore failover), DeFiLlama, alternative.me, public Ethereum RPCs
diff --git a/docs/start-here.md b/docs/start-here.md
index ec4690eb7..35d1faceb 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -69,6 +69,7 @@ If you're here to create and share agents rather than write code, follow this pa
- **Trading?** → [The trading surfaces](./trading-surfaces.md) maps the solo stack (Radar, Coin Intelligence, Live Trade Feed, Watchlist, Mission Control); [trading arenas](./trading-arenas.md) covers tournaments, the theater, vaults, and swarms; [Oracle](./oracle.md) is the conviction engine underneath all of it
- **Trusting an agent with money?** → [Custody you can verify](./custody.md) — spend limits, freeze, Merkle proof-of-custody, and social recovery; [claim your wallet](./trader-card.md) turns any pump.fun track record into a public, provable Trader Card. Every real-funds feature sits behind the [risk acknowledgment](./risk-acknowledgment.md) — read the [Risk Disclosure](https://three.ws/legal/risk) before committing anything
- **Vetting a counterparty before you pay it?** → [Trust primitives](./trust-primitives.md) — the cross-chain Agent Reputation endpoint scores ANY wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence, in one paid call, before your agent transacts
+- **Your agent needs market data?** → [Market Data API](./market-data-api.md) — the live feeds behind every /markets page (prices, TVL, yields, stablecoins, gas, derivatives, exploits) as 17 pay-per-call x402 endpoints from $0.001 USDC, plus the one-call `market-pulse` bundle; start at the free index [/api/x402/market](https://three.ws/api/x402/market)
- **Debugging an x402 integration?** → [x402 developer tools](./x402-dev-tools.md) — a free test bench: echo your payment envelope (signatures redacted), debug a failed 402 exchange into an ordered fix list, and verify a receipt's attestation and on-chain settlement, all against a live server without spending anything
- **Paying from the BNB ecosystem?** → [BNB Chain payments](./bnb-payments.md) — three.ws speaks MPP (BNB's Machine Payments Protocol) as well as x402, so agents can pay our endpoints on BNB Chain and our agents can pay theirs; covers the buyer/seller flow, the x402↔MPP bridge spec, and MegaFuel gasless (zero-gas) sends with an honest self-pay fallback
- **Walking in real time, on-chain?** → [The on-chain world](./bnb-world.md) — `/agora`'s Play mode has an opt-in toggle that commits your walk to a real BNB Chain contract at its live ~0.45s block cadence, gaslessly, and renders every other on-chain player as a live ghost marker; covers why this only works on BNB Chain, the architecture, and a reproducible two-wallet proof
diff --git a/package.json b/package.json
index ea0616511..c00207751 100644
--- a/package.json
+++ b/package.json
@@ -109,6 +109,7 @@
"dev:lib": "TARGET=lib vite",
"presence": "node scripts/three-ws-presence.mjs",
"build:pages": "node scripts/build-page-index.mjs",
+ "build:discovery": "node scripts/build-discovery-cards.mjs",
"build:ibm-shell": "node scripts/build-ibm-shell.mjs",
"i18n": "npm run i18n:extract && npm run i18n:translate",
"i18n:extract": "node scripts/i18n-extract.mjs",
@@ -143,7 +144,7 @@
"audit:web": "node scripts/page-audit.mjs",
"snapshot": "node scripts/page-snapshot.mjs",
"build:news": "node scripts/build-news.mjs",
- "prebuild": "(node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & npm run build:club-assets & npm run build:walk-environments & wait) && node scripts/inject-blog-seo.mjs --write && node scripts/inject-hidden-guard.mjs --write && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs --strict && node scripts/audit-empty-handlers.mjs && node scripts/audit-hidden-guard.mjs) && node scripts/inject-seo-meta.mjs --write && node scripts/inject-theme-boot.mjs --write",
+ "prebuild": "(node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & node scripts/build-discovery-cards.mjs & npm run build:club-assets & npm run build:walk-environments & wait) && node scripts/inject-blog-seo.mjs --write && node scripts/inject-hidden-guard.mjs --write && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs --strict && node scripts/audit-empty-handlers.mjs && node scripts/audit-hidden-guard.mjs) && node scripts/inject-seo-meta.mjs --write && node scripts/inject-theme-boot.mjs --write",
"seo:meta": "node scripts/inject-blog-seo.mjs --write && node scripts/build-page-index.mjs && node scripts/inject-seo-meta.mjs --write",
"build": "NODE_OPTIONS='--no-deprecation --max-old-space-size=6144' vite build && node scripts/strip-sw-from-embeds.mjs && node scripts/inject-tour-boot.mjs",
"build:wasm": "PATH=\"$HOME/.cargo/bin:$PATH\" RUSTFLAGS='-C target-feature=+simd128' wasm-pack build crates/vanity-grinder --target web --release --out-dir ../../src/solana/vanity/wasm && printf '%s\\n' '# wasm-pack writes a default `*` gitignore that excludes everything.' '# Override it: the generated files in this directory ARE checked in so the' '# app builds without requiring a Rust toolchain at install time. Run' '# `npm run build:wasm` after editing /crates/vanity-grinder/src/lib.rs to' '# refresh these artifacts.' '!*' > src/solana/vanity/wasm/.gitignore",
diff --git a/pages/markets.html b/pages/markets.html
index fc8e81242..21dd40136 100644
--- a/pages/markets.html
+++ b/pages/markets.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html lang="en" class="cv-page">
+<html lang="en" class="cv-page" data-shell>
<head>
<script>
/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {
diff --git a/public/.well-known/agent-card.json b/public/.well-known/agent-card.json
index 04a9de375..3285a89bb 100644
--- a/public/.well-known/agent-card.json
+++ b/public/.well-known/agent-card.json
@@ -1,6 +1,6 @@
{
"name": "three.ws",
- "description": "AI-powered 3D model viewer and validation agent. Load glTF/GLB models, run validation, inspect materials, and manage avatar assets.",
+ "description": "three.ws — the 3D agent economy. Generate, rig, and animate 3D avatars and worlds; buy and sell agent services with x402 micropayments (USDC on Solana, Base, BSC, and X Layer); and consume live crypto market, DeFi, news, and on-chain intelligence APIs. Machine-readable paid-service catalog at https://three.ws/.well-known/x402.json.",
"url": "https://three.ws/",
"provider": {
"organization": "three.ws",
@@ -20,52 +20,96 @@
]
},
"authentication": {
- "schemes": ["bearer"],
+ "schemes": [
+ "bearer"
+ ],
"credentials": null
},
- "defaultInputModes": ["text/plain", "application/json"],
- "defaultOutputModes": ["text/plain", "application/json"],
+ "defaultInputModes": [
+ "text/plain",
+ "application/json"
+ ],
+ "defaultOutputModes": [
+ "text/plain",
+ "application/json"
+ ],
"skills": [
{
"id": "list-avatars",
"name": "List Avatars",
"description": "List all avatars owned by the authenticated user",
- "tags": ["avatar", "list"],
- "examples": ["Show me my avatars", "List all my 3D models"]
+ "tags": [
+ "avatar",
+ "list"
+ ],
+ "examples": [
+ "Show me my avatars",
+ "List all my 3D models"
+ ]
},
{
"id": "get-avatar",
"name": "Get Avatar",
"description": "Retrieve details of a specific avatar by ID or slug",
- "tags": ["avatar", "inspect"],
- "examples": ["Get avatar details for cz", "Show avatar info"]
+ "tags": [
+ "avatar",
+ "inspect"
+ ],
+ "examples": [
+ "Get avatar details for cz",
+ "Show avatar info"
+ ]
},
{
"id": "search-avatars",
"name": "Search Public Avatars",
"description": "Search public avatar gallery by query",
- "tags": ["avatar", "search"],
- "examples": ["Find avatars matching 'robot'", "Search public models"]
+ "tags": [
+ "avatar",
+ "search"
+ ],
+ "examples": [
+ "Find avatars matching 'robot'",
+ "Search public models"
+ ]
},
{
"id": "render-avatar",
"name": "Render Avatar",
"description": "Get an embeddable HTML model-viewer snippet that renders the given avatar in 3D",
- "tags": ["avatar", "render", "preview"],
- "examples": ["Render my avatar in the viewer", "Preview this model"]
+ "tags": [
+ "avatar",
+ "render",
+ "preview"
+ ],
+ "examples": [
+ "Render my avatar in the viewer",
+ "Preview this model"
+ ]
},
{
"id": "delete-avatar",
"name": "Delete Avatar",
"description": "Delete an avatar owned by the authenticated user",
- "tags": ["avatar", "delete"],
- "examples": ["Delete my old avatar", "Remove avatar abc123"]
+ "tags": [
+ "avatar",
+ "delete"
+ ],
+ "examples": [
+ "Delete my old avatar",
+ "Remove avatar abc123"
+ ]
},
{
"id": "validate-model",
"name": "Validate glTF/GLB Model",
"description": "Run the Khronos glTF-Validator against a remote model URL and return a structured error/warning/info/hint report",
- "tags": ["model", "validation", "gltf", "glb"],
+ "tags": [
+ "model",
+ "validation",
+ "gltf",
+ "glb"
+ ],
"examples": [
"Validate https://example.com/model.glb",
"Is this GLB spec-compliant?",
@@ -76,7 +120,13 @@
"id": "inspect-model",
"name": "Inspect glTF/GLB Model",
"description": "Parse a remote model and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used",
- "tags": ["model", "inspect", "stats", "gltf", "glb"],
+ "tags": [
+ "model",
+ "inspect",
+ "stats",
+ "gltf",
+ "glb"
+ ],
"examples": [
"How many triangles are in this model?",
"Inspect https://example.com/scene.glb",
@@ -87,7 +137,12 @@
"id": "optimize-model",
"name": "Suggest Optimizations",
"description": "Inspect a remote model and return actionable suggestions for reducing size and draw-call overhead (Draco/Meshopt, KTX2, texture resize, reindexing, material merging)",
- "tags": ["model", "optimize", "suggestions", "performance"],
+ "tags": [
+ "model",
+ "optimize",
+ "suggestions",
+ "performance"
+ ],
"examples": [
"How can I make this model smaller?",
"Optimize this GLB for web delivery",
@@ -98,14 +153,43 @@
"id": "inspect-glb-a2a",
"name": "Inspect glTF/GLB (A2A)",
"description": "Pay-per-call glTF/GLB inspector exposed over the Agent-to-Agent (A2A) protocol with x402 settlement. Send a JSON-RPC message/send to the URL below — the first call returns payment requirements, the retry with a signed PaymentPayload settles on-chain and returns the inspection report as a task artifact.",
- "tags": ["model", "gltf", "glb", "inspect", "a2a", "x402", "paid"],
+ "tags": [
+ "model",
+ "gltf",
+ "glb",
+ "inspect",
+ "a2a",
+ "x402",
+ "paid"
+ ],
"examples": [
"Inspect https://example.com/model.glb (A2A x402)",
"Vet this GLB before I mint it"
],
- "inputModes": ["application/json", "text/plain"],
- "outputModes": ["application/json"],
+ "inputModes": [
+ "application/json",
+ "text/plain"
+ ],
+ "outputModes": [
+ "application/json"
+ ],
"url": "https://three.ws/api/agents/a2a-paid"
+ },
+ {
+ "id": "x402-service-catalog",
+ "name": "Paid x402 Service Catalog",
+ "description": "74 pay-per-call services settled via x402 (USDC on Solana and Base): market-data (26), 3d (18), agent-infra (17), launch (5), trust (4), payments (4). Every service is listed with price, input schema, and output example in the machine-readable discovery document — fetch it, pick a service, and pay the 402 challenge.",
+ "tags": [
+ "x402",
+ "paid",
+ "catalog",
+ "discovery"
+ ],
+ "examples": [
+ "Fetch https://three.ws/.well-known/x402.json and list the market-data services",
+ "Pay the 402 challenge on /api/x402/token-intel to get a token signal"
+ ],
+ "url": "https://three.ws/.well-known/x402.json"
}
]
}
diff --git a/public/.well-known/agent-registration.json b/public/.well-known/agent-registration.json
index 2146b599f..1cca113e0 100644
--- a/public/.well-known/agent-registration.json
+++ b/public/.well-known/agent-registration.json
@@ -1,8 +1,10 @@
{
"type": "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",
- "additionalTypes": ["https://three.ws/specs/3d-agent-card-v1"],
+ "additionalTypes": [
+ "https://three.ws/specs/3d-agent-card-v1"
+ ],
"name": "three.ws",
- "description": "AI-powered 3D model viewer and validation agent. Drag and drop glTF, GLB, and 3D files to preview instantly in your browser. Supports real-time rendering, model validation, environment maps, and animation playback via Three.js and WebGL.",
+ "description": "three.ws — the 3D agent economy. Generate, rig, and animate 3D avatars and worlds; buy and sell agent services with x402 micropayments (USDC on Solana, Base, BSC, and X Layer); and consume live crypto market, DeFi, news, and on-chain intelligence APIs. Machine-readable paid-service catalog at https://three.ws/.well-known/x402.json.",
"image": "https://three.ws/og-image.png",
"active": true,
"agentCard": "https://three.ws/.well-known/3d-agent-card.json",
@@ -13,8 +15,16 @@
"sizeBytes": 2875236,
"polygonCount": 13317,
"boundingBox": {
- "min": [-0.464, -0.006, -0.146],
- "max": [0.464, 1.766, 0.197]
+ "min": [
+ -0.464,
+ -0.006,
+ -0.146
+ ],
+ "max": [
+ 0.464,
+ 1.766,
+ 0.197
+ ]
},
"license": "CC-BY-4.0"
},
@@ -37,14 +47,823 @@
"x402Support": true,
"x402Endpoints": [
{
- "url": "https://three.ws/api/mcp",
+ "url": "https://three.ws/api/x402/model-check",
+ "method": "GET",
+ "description": "Model Check — an agent handed a 3D asset URL verifies it before using or paying for it: $0.001 USDC per call returns structural stats (vertex/triangle counts, materials, textures, animations, extensions) and prioritized optimization recommendations.",
+ "networks": [
+ "solana",
+ "base",
+ "arbitrum"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/agent-reputation",
+ "method": "GET",
+ "description": "Cross-chain Agent Reputation — get a deterministic 0–100 trust score for ANY counterparty (Solana wallet, EVM wallet, pump.fun mint, ERC-8004 agent id, or three.ws agent_id — auto-detected) before you pay, trade, or delegate to it.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.01"
+ },
+ {
+ "url": "https://three.ws/api/x402/agent-bouncer",
+ "method": "GET",
+ "description": "Agent Bouncer — the Pole Club door check, opened to the whole platform’s Solana reputation.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.01"
+ },
+ {
+ "url": "https://three.ws/api/x402/onchain-identity-verify",
+ "method": "GET",
+ "description": "Cross-platform On-Chain Identity Verifier — prove any claim that an identity controls an address.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.005"
+ },
+ {
+ "url": "https://three.ws/api/x402/fact-check",
+ "method": "POST",
+ "description": "Real-Time Fact Checker — submit a claim and receive a sourced verdict (supported/contradicted/mixed/insufficient) backed by live web search and LLM analysis, with cited sources and a SHA-256 attestation you can audit.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.1"
+ },
+ {
+ "url": "https://three.ws/api/x402/pump-launch",
+ "method": "POST",
+ "description": "Pump Launcher — launch a pump.fun token autonomously in one paid call: no SOL, no wallet, no account.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "5"
+ },
+ {
+ "url": "https://three.ws/api/x402/forge",
+ "method": "POST",
+ "description": "Forge — production text/image→3D for agents that need real assets, not drafts: game assets, NFT art, scene props, and product visualization as textured GLB.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.15"
+ },
+ {
+ "url": "https://three.ws/api/x402/mint-to-mesh",
+ "method": "GET",
+ "description": "Mint to Mesh — pass any Solana SPL token mint, get back a binary glTF (GLB) cube themed and colored from that token's own on-chain Metaplex metadata, ready to render.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/mint-to-mesh-batch",
+ "method": "POST",
+ "description": "Mint to Mesh (Batch) — resolve 1–10 Solana SPL mints to themed glTF (GLB) cubes in a single paid call instead of paying for N round-trips.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.05"
+ },
+ {
+ "url": "https://three.ws/api/x402/skill-marketplace",
+ "method": "GET",
+ "description": "Skill Marketplace — list active skill listings with prices across all three.ws agents.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/symbol-availability",
+ "method": "GET",
+ "description": "Symbol Availability — pre-launch ticker collision check against three.ws's pump.fun mint index.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/vanity",
+ "method": "GET",
+ "description": "Vanity Grinder — put your brand on-chain: get a Solana address that starts with your ticker/prefix and/or ends with a chosen suffix, for a branded token MINT address, a recognizable agent/treasury wallet, or any wallet identifiable at a glance.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.01"
+ },
+ {
+ "url": "https://three.ws/api/x402/vanity-verifiable",
+ "method": "GET",
+ "description": "Provably-Fair Vanity Grinder — generate a brand-new Solana keypair whose Base58 address starts with a chosen prefix and/or ends with a chosen suffix, with a SIGNED receipt that proves the key was ground fresh and never kept.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.02"
+ },
+ {
+ "url": "https://three.ws/api/x402/vanity-premium",
+ "method": "GET",
+ "description": "Premium Vanity Inventory — buy a PRE-GROUND Solana address with a long (4–5+ char) brandable prefix, delivered instantly from stock.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "1"
+ },
+ {
+ "url": "https://three.ws/api/x402/permit2-paid-demo",
+ "method": "GET",
+ "description": "Permit2 + EIP-2612 Gas Sponsoring Demo — forces the gasless Permit2 path so a fresh wallet holding USDC but ZERO ETH can complete the flow.",
+ "networks": [
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/asset-download",
+ "method": "GET",
+ "description": "three.ws Asset Bazaar — pay once in USDC to unlock a 3D asset (GLB, avatar, or accessory) hosted on R2.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.1"
+ },
+ {
+ "url": "https://three.ws/api/x402/remix-asset",
+ "method": "POST",
+ "description": "Remix a published 3D model by describing a change; a creator-set royalty of the fee routes on-chain to the original creator.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.25"
+ },
+ {
+ "url": "https://three.ws/api/x402/skill-call",
+ "method": "GET",
+ "description": "three.ws Skill Call — pay the per-call price of a marketplace skill in USDC (Base or Solana) and receive its executable payload: the tool schema and content the calling agent runs.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.01"
+ },
+ {
+ "url": "https://three.ws/api/x402/token-intel",
+ "method": "GET",
+ "description": "three.ws Token Oracle — pay $0.01 USDC per call for live market intel on ANY token by contract address: price, 24 h change, market cap, liquidity, 24 h volume, and a bullish / bearish / neutral signal with a two-sentence rationale.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.01"
+ },
+ {
+ "url": "https://three.ws/api/x402/defi-radar",
+ "method": "GET",
+ "description": "three.ws DeFi Radar — one $0.005 USDC call returns the whole DeFi market at a glance: total TVL with the biggest 24 h gainers and losers, the top fee-earning protocols, and the top DEXes by 24 h volume.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.005"
+ },
+ {
+ "url": "https://three.ws/api/x402/yield-scan",
+ "method": "GET",
+ "description": "three.ws Yield Scanner — $0.005 USDC per call filters 15,000+ live DeFi yield pools by chain, TVL floor, and stablecoin-only, then returns the top pools with APY breakdown and per-pool risk flags.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.005"
+ },
+ {
+ "url": "https://three.ws/api/x402/stablecoin-health",
+ "method": "GET",
+ "description": "three.ws Stablecoin Peg Monitor — $0.005 USDC per call returns live peg deviation, supply, and 24 h / 7 d / 30 d supply flow for every major stablecoin, with an on-peg / drifting / depegged verdict per coin.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.005"
+ },
+ {
+ "url": "https://three.ws/api/x402/hack-check",
+ "method": "GET",
+ "description": "three.ws Exploit History Check — $0.002 USDC per call searches the full DeFi exploit database for a protocol name and returns its incident history, amounts lost, techniques, and a clean / incident-history verdict.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.002"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-heatmap",
+ "method": "GET",
+ "description": "three.ws Market Heatmap — $0.002 USDC per call returns the top coins by market cap with 1 h / 24 h / 7 d momentum plus market-breadth stats (advancers, decliners, average move) in one normalized snapshot.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.002"
+ },
+ {
+ "url": "https://three.ws/api/x402/gas-oracle",
+ "method": "GET",
+ "description": "three.ws Multi-Chain Gas Oracle — $0.001 USDC per call returns live fee tiers for Ethereum and Base (slow / standard / fast from real fee history) plus Solana priority-fee percentiles, in one call.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-mood",
+ "method": "GET",
+ "description": "three.ws Market Mood Index — $0.002 USDC per call blends the Fear & Greed index with live sentiment scored across 192 crypto news feeds into one 0–100 mood reading with the headlines driving it.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.002"
+ },
+ {
+ "url": "https://three.ws/api/x402/news-pulse",
+ "method": "GET",
+ "description": "three.ws Ticker News Pulse — $0.002 USDC per call measures live news coverage for one ticker across 192 crypto publisher feeds: mention count, velocity vs the prior window, sentiment split, and top headlines.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.002"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-coins",
+ "method": "GET",
+ "description": "Ranked coin market table — price, market cap, 24h volume, 24h/7d change, and a 7-day sparkline for up to 250 coins per call, with sector scoping and coin-id search.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-coin",
+ "method": "GET",
+ "description": "Full profile for one coin by CoinGecko id or Solana contract — market stats, ATH/ATL, supply, links, developer and community metrics, sentiment, plain-text description.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-chart",
+ "method": "GET",
+ "description": "Historical USD price series for any coin — [timestamp, price] pairs over 1, 7, 30, 90, or 365 days, granularity auto-chosen per window.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-categories",
+ "method": "GET",
+ "description": "Every CoinGecko sector ranked by market cap — AI, L1, memes, DeFi and hundreds more, with 24h cap change, volume, and top-3 coin logos.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-exchanges",
+ "method": "GET",
+ "description": "Top 100 spot exchanges ranked by trust score, with 24h volume in BTC and USD, country, and year established.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-derivatives",
+ "method": "GET",
+ "description": "Perpetual futures tickers — price, funding rate, open interest, 24h volume across venues — or the derivatives-exchange leaderboard by open interest.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-global",
+ "method": "GET",
+ "description": "Whole-market stats in one call — total market cap, 24h volume, BTC/ETH dominance, active coins, plus the Fear & Greed index.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-gas",
+ "method": "GET",
+ "description": "Live ETH gas in three tiers (slow/standard/fast) computed from on-chain fee history, with USD cost estimates for transfers, swaps, and mints.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-trending",
+ "method": "GET",
+ "description": "The last 24h's most-searched coins, categories, and NFT collections — early attention signals before they show up in price.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-defi",
+ "method": "GET",
+ "description": "Top 100 DeFi protocols ranked by TVL with 1d/7d change, chains, category, and market cap, plus whole-market TVL totals (CEX reserves excluded).",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-chains",
+ "method": "GET",
+ "description": "Every chain ranked by DeFi TVL with native token symbol and share of total locked value — the cross-chain capital map.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-yields",
+ "method": "GET",
+ "description": "Query ~15,000 DeFi yield pools — filter by chain, project, stablecoin-only, or TVL floor, sort by APY or TVL, or pull one pool's APY/TVL history.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-stablecoins",
+ "method": "GET",
+ "description": "Top 100 stablecoins by circulating supply with live price for peg health, peg mechanism, and chain deployments, plus total stablecoin market cap.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-fees",
+ "method": "GET",
+ "description": "Which protocols actually earn — top 100 by 24h fees or revenue with 1d/7d/30d totals and change, plus the whole-market daily chart.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-dex-volumes",
+ "method": "GET",
+ "description": "Top 100 DEXs by 24h trading volume with 7d totals, market share, and the aggregate daily volume chart.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-hacks",
+ "method": "GET",
+ "description": "Every recorded DeFi hack — amount stolen, technique, classification, chains, funds returned — searchable, with all-time and 12-month loss stats.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/market-pulse",
+ "method": "GET",
+ "description": "The whole market in one paid call — global stats, Fear & Greed, top-10 coins, trending, ETH gas, DeFi TVL, stablecoin supply, DEX volume, and protocol fees.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.005"
+ },
+ {
+ "url": "https://three.ws/api/x402/cosmetic-purchase",
+ "method": "GET",
+ "description": "three.ws Avatar Shop — pay once in USDC to unlock a premium avatar cosmetic (skin or emote) for an account.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.5"
+ },
+ {
+ "url": "https://three.ws/api/x402/animation-download",
+ "method": "GET",
+ "description": "three.ws Animation Bazaar — pay once in USDC to unlock a 3D avatar animation (GLB).",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.01"
+ },
+ {
+ "url": "https://three.ws/api/x402/club-cover",
+ "method": "GET",
+ "description": "three.ws Pole Club Cover Charge — pay $0.01 USDC to access the three.ws Pole Club.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.01"
+ },
+ {
+ "url": "https://three.ws/api/x402/analytics",
+ "method": "POST",
+ "description": "three.ws Economy Analytics — pay $0.005 USDC per call for a live, aggregated view of platform activity.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.005"
+ },
+ {
+ "url": "https://three.ws/api/x402/api-key-health",
+ "method": "POST",
+ "description": "API Key Validity Health Check — verifies that the platform has a valid, non-expired access key covering a given scope.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/auth-health",
+ "method": "POST",
+ "description": "Auth Session Lifecycle Health — pay $0.001 USDC to exercise the full JWT auth session lifecycle: create, validate, refresh, and expiry-rejection.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/avatar-optimize-batch",
+ "method": "POST",
+ "description": "three.ws Avatar Optimization Pipeline — pay $0.001 USDC to trigger a batch glTF/GLB analysis of the top most-viewed public avatars.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/pipeline-rig",
+ "method": "POST",
+ "description": "3D Asset Pipeline — Rig: pay $0.05 USDC to make a static GLB animation-ready.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.05"
+ },
+ {
+ "url": "https://three.ws/api/x402/pipeline-remesh",
+ "method": "POST",
+ "description": "3D Asset Pipeline — Remesh: pay $0.03 USDC to retopologize a GLB.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.03"
+ },
+ {
+ "url": "https://three.ws/api/x402/pipeline-gameready",
+ "method": "POST",
+ "description": "3D Asset Pipeline — Game-Ready: pay $0.03 USDC to make a GLB engine-ready.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.03"
+ },
+ {
+ "url": "https://three.ws/api/x402/pipeline-stylize",
+ "method": "POST",
+ "description": "3D Asset Pipeline — Stylize: pay $0.03 USDC to geometrically restyle a GLB.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.03"
+ },
+ {
+ "url": "https://three.ws/api/x402/pipeline-rembg",
+ "method": "POST",
+ "description": "3D Asset Pipeline — Background Removal: pay $0.01 USDC to strip the background from an image, returning a transparent PNG — the clean reference view image→3D reconstruction needs so it never bakes a room into the mesh.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.01"
+ },
+ {
+ "url": "https://three.ws/api/x402/pipeline",
+ "method": "POST",
+ "description": "One call, full 3D asset pipeline — text or GLB in, rigged/optimized game-ready GLB out; the only asset pipeline in the x402 ecosystem.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.15"
+ },
+ {
+ "url": "https://three.ws/api/x402/embody",
+ "method": "POST",
+ "description": "Give your agent a 3D body — one x402 call returns a rigged, animated, talking avatar plus a one-tag embed for any website. The only embodiment endpoint in the x402 ecosystem.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "1"
+ },
+ {
+ "url": "https://three.ws/api/x402/bazaar-feed",
+ "method": "POST",
+ "description": "Bazaar Feed — pay $0.001 USDC per call for two live views of the x402 service marketplace.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/billboard",
+ "method": "GET",
+ "description": "three.ws coin worlds — feature your content on a 3D world’s billboard.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.05"
+ },
+ {
+ "url": "https://three.ws/api/x402/cross-chain",
+ "method": "POST",
+ "description": "Cross-Chain Bridge Status Monitor — pay $0.005 USDC to receive the live operational status and latency of major Solana bridge providers (Wormhole, Li.Fi, deBridge).",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.005"
+ },
+ {
+ "url": "https://three.ws/api/x402/did",
+ "method": "POST",
+ "description": "DID Verification Canary — pay $0.001 USDC to resolve three.ws's published W3C DID document over its real public route, structurally validate it, and measure end-to-end resolution latency.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/feed-health",
+ "method": "POST",
+ "description": "three.ws Feed Health Validator — fetches a named public feed (changelog RSS, sitemap, etc.) and returns a structural health verdict: { valid, item_count, latest_title }.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/llm-proxy",
+ "method": "POST",
+ "description": "three.ws LLM Inference Proxy — pay per completion with no API key required.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.005"
+ },
+ {
+ "url": "https://three.ws/api/x402/mcp-tool-catalog",
+ "method": "POST",
+ "description": "three.ws MCP Tool Discovery — pay $0.001 USDC to discover MCP tools that were registered (or whose price/shape changed, or that were removed) on the three.ws MCP server since you last probed.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/model-validation-sweep",
+ "method": "POST",
+ "description": "three.ws model quality sweep — picks the next public GLB avatar in the database that has never been inspected (or whose inspection is older than 24 hours), downloads the file, runs the glTF-Transform inspector, computes a 0-100 quality score, and records a time-series row.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/notify",
+ "method": "POST",
+ "description": "Notification Delivery Probe — pay $0.001 USDC to send a canary message through the platform notification channel and confirm delivery.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/pay-by-name",
+ "method": "POST",
+ "description": "Pay-By-Name Resolution — pay $0.001 USDC to resolve a wallet name (@username, a *.sol name, or a raw base58 address) to a verified on-chain Solana address via the three.ws pay-by-name registry.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/rate-limit-probe",
+ "method": "POST",
+ "description": "Rate-Limit Capacity Probe — pay $0.001 USDC to learn how many more calls the x402 autonomous loop can make to a target endpoint today before hitting its daily USDC spend cap.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/schema-check",
+ "method": "POST",
+ "description": "three.ws JSON API schema conformance checker — pay $0.001 USDC to fetch a named three.ws public API and validate its response against the declared schema.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/solana-register-health",
+ "method": "GET",
+ "description": "Solana Agent Registration Health Check — verifies three.ws's server-custodial Solana agent-registration subsystem end-to-end by resolving a known canary agent's on-chain Metaplex Agent Registry record (Identity PDA + Core asset) and confirming both accounts exist on-chain right now.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/spend-session",
+ "method": "POST",
+ "description": "three.ws Spend Session Health — pay $0.01 USDC to probe the Agent Payment Sessions governance layer.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.01"
+ },
+ {
+ "url": "https://three.ws/api/x402/telegram-health",
+ "method": "POST",
+ "description": "Changelog Telegram Bot Health Check — pays $0.001 USDC to verify that the three.ws platform bot can reach the Telegram API and is alive.",
+ "networks": [
+ "solana",
+ "base"
+ ],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ },
+ {
+ "url": "https://three.ws/api/x402/wallet-connect",
"method": "POST",
- "description": "MCP tool call — 3D avatar viewer, glTF model validation/inspection/optimization, and Solana agent data",
- "networks": ["solana", "base"],
+ "description": "Wallet Connection Session Health Check — probes the SIWS (Sign-In With Solana) session initiation path: issues a real nonce challenge against the platform auth gateway, validates its structure and expiry, and measures roundtrip latency.",
+ "networks": [
+ "solana",
+ "base"
+ ],
"scheme": "exact",
"priceUsdc": "0.001"
}
],
"registrations": [],
- "supportedTrust": ["reputation", "validation"]
+ "supportedTrust": [
+ "reputation",
+ "validation"
+ ]
}
diff --git a/public/.well-known/ai-plugin.json b/public/.well-known/ai-plugin.json
index 6f78bb74c..8a550cdbf 100644
--- a/public/.well-known/ai-plugin.json
+++ b/public/.well-known/ai-plugin.json
@@ -2,8 +2,8 @@
"schema_version": "v1",
"name_for_human": "three.ws",
"name_for_model": "3d_agent",
- "description_for_human": "AI-powered 3D model viewer. Drag and drop glTF, GLB, and 3D files to preview instantly in your browser.",
- "description_for_model": "A web-based 3D model viewer that supports glTF and GLB file formats. Users can drag-and-drop 3D models to preview them with real-time rendering powered by Three.js and WebGL.",
+ "description_for_human": "three.ws — 3D avatar/world generation and live crypto intelligence APIs, pay-per-call via x402.",
+ "description_for_model": "three.ws exposes a 3D model viewer plus a paid pay-per-call API catalog settled via the x402 protocol (HTTP 402, USDC on Solana and Base): text→3D generation, avatar rigging, token and DeFi market intelligence, news sentiment, gas oracles, vanity address mining, and agent reputation. The machine-readable catalog with prices and schemas is at https://three.ws/.well-known/x402.json; free endpoints are indexed at /api/crypto and /api/3d.",
"auth": {
"type": "none"
},
diff --git a/public/crypto-agent-manifest.json b/public/crypto-agent-manifest.json
index a45765fbd..637efc7fc 100644
--- a/public/crypto-agent-manifest.json
+++ b/public/crypto-agent-manifest.json
@@ -3,22 +3,30 @@
"name": "Crypto Oracle",
"description": "A crypto expert agent that can provide real-time price information.",
"body": {
- "uri": "https://cdn.three.ws/models/sample-avatar.glb",
+ "uri": "https://three.ws/avatars/default.glb",
"format": "gltf-binary"
},
"brain": {
"provider": "anthropic",
- "model": "claude-sonnet-4-6",
+ "model": "claude-sonnet-5",
"instructions": "You are a crypto expert. You can provide real-time price information for any cryptocurrency. When asked for a price, use the getPrice tool. For example, to get the price of Solana, you would call getPrice({ coin_id: 'solana', vs_currency: 'usd' }).",
"temperature": 0.7,
"maxTokens": 1024
},
"voice": {
- "tts": { "provider": "browser" },
- "stt": { "provider": "browser" }
+ "tts": {
+ "provider": "browser"
+ },
+ "stt": {
+ "provider": "browser"
+ }
+ },
+ "memory": {
+ "mode": "local"
},
- "memory": { "mode": "local" },
"skills": [
- { "uri": "/skills/crypto-price/" }
+ {
+ "uri": "/skills/crypto-price/"
+ }
]
}
diff --git a/public/nav.js b/public/nav.js
index 7d9d5054b..fc5151930 100644
--- a/public/nav.js
+++ b/public/nav.js
@@ -188,6 +188,7 @@ function boot() {
loadDiscovery();
loadGettingStarted();
loadThemeSwitcher();
+ initCompanionAutoStart();
const navContainer = document.getElementById('nav-container');
if (!navContainer) return;
Promise.all([
@@ -609,6 +610,49 @@ function ensureWalkCompanion() {
document.head.appendChild(s);
}
+// ── First-visit companion auto-start ─────────────────────────────────────────
+// Every visitor gets their agent in the first few seconds: if they have never
+// decided about the companion (the enabled key is absent — '0' means they
+// closed it, '1' means it's already on), summon it once, deferred to idle so
+// it costs the first paint nothing. The companion module mints the guest
+// identity (name + body) and introduces itself; see
+// src/walk-companion-identity.js.
+const WALK_AUTO_KEY = 'walk:companion:auto';
+
+// Routes that own their own full-screen 3D or camera experience — summoning a
+// second WebGL avatar there hurts more than it helps. (walk-sdk keeps its own
+// exclusion list too; this is the conservative outer gate.)
+const WALK_AUTO_SKIP = /^\/(play|walk|club|tour|world|scan|arena|pose|splat|capture)(\/|$)|^\/create\/selfie/;
+
+function initCompanionAutoStart() {
+ // Every check lives inside the deferred callback: boot() can run while this
+ // script is still evaluating (late injection), and the WALK_ENABLED_KEY
+ // const below would be in its temporal dead zone if read synchronously here.
+ const summon = () => {
+ try {
+ if (localStorage.getItem(WALK_ENABLED_KEY) !== null) return; // visitor already chose (on or off)
+ } catch (_) {
+ return; // no storage → the greeting/claim loop can't work either
+ }
+ if (WALK_AUTO_SKIP.test(location.pathname)) return;
+ if (document.documentElement.getAttribute('data-walk-auto') === 'off') return;
+ if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
+ if (navigator.connection && navigator.connection.saveData) return;
+ try {
+ localStorage.setItem(WALK_ENABLED_KEY, '1');
+ localStorage.setItem(WALK_AUTO_KEY, '1');
+ } catch (_) {
+ return;
+ }
+ ensureWalkCompanion();
+ window.dispatchEvent(new CustomEvent('walk-companion:change'));
+ };
+ const idle = () =>
+ 'requestIdleCallback' in window ? requestIdleCallback(summon, { timeout: 4000 }) : setTimeout(summon, 1500);
+ if (document.readyState === 'complete') setTimeout(idle, 2000);
+ else window.addEventListener('load', () => setTimeout(idle, 2000), { once: true });
+}
+
function initWalkToggle(root) {
// Desktop button (`.nav-end`) + mobile drawer row — both toggle the same
// companion and stay mirrored, so the avatar is reachable at every breakpoint.
diff --git a/public/search.js b/public/search.js
index f84983f8f..c5a761b20 100644
--- a/public/search.js
+++ b/public/search.js
@@ -6,6 +6,16 @@
// • /features.json — static page/feature registry (loaded once)
// • /skills-index.json — skill catalog (loaded once)
// • quick actions + recents — in-memory verbs + localStorage history
+//
+// Beyond search, the palette EXECUTES commands in place — it is the agent's
+// command line, not just a router. Type a verb and the work happens inside
+// the panel against the real public APIs (no auth needed):
+// • forge <prompt> → POST /api/forge (free text→3D lane), polls to a GLB
+// • digest → GET /api/news/digest — the day clustered into stories
+// • price <coin|$X> → GET /api/coin/markets + /detail (falls back to pump)
+// • ask <question> → POST /api/chat — streamed answer from the site agent
+// Command completions are announced on the DOM ('tws:palette-action') and the
+// agent bus ('action:taken') so the corner companion can react to them.
// Opt out per page: <html data-search="off">
(function () {
@@ -84,6 +94,20 @@
'.tws-sk-skel-lines{flex:1;display:flex;flex-direction:column;gap:5px;}',
'.tws-sk-skel-l{height:12px;border-radius:4px;background:#1c1c1c;animation:tws-sk-pulse 1.4s ease infinite;}',
'.tws-sk-skel-l.w60{width:60%}.tws-sk-skel-l.w40{width:40%}.tws-sk-skel-l.w80{width:80%}',
+ /* command run panel */
+ '.tws-sk-run-head{display:flex;align-items:center;gap:10px;padding:12px 16px;border-bottom:1px solid #1c1c1c;}',
+ '.tws-sk-run-title{flex:1;min-width:0;font-size:13.5px;font-weight:600;color:#f6f6f6;letter-spacing:-.01em;',
+ 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}',
+ '.tws-sk-run-status{flex-shrink:0;display:flex;align-items:center;gap:8px;',
+ 'font:500 11px/1 "JetBrains Mono",ui-monospace,monospace;color:#6a6a6a;letter-spacing:.04em;}',
+ '.tws-sk-run-status.ok{color:#4ade80;}',
+ '.tws-sk-run-status.err{color:#f87171;}',
+ '.tws-sk-run-body{padding:4px 0 6px;}',
+ '.tws-sk-answer{padding:10px 16px 12px;font-size:13px;line-height:1.55;color:#d6d6d6;',
+ 'white-space:pre-wrap;overflow-wrap:break-word;max-height:300px;overflow-y:auto;}',
+ '.tws-sk-answer:empty::before{content:"…";color:#4a4a4a;}',
+ '.tws-sk-run-foot{padding:8px 16px 10px;border-top:1px solid #1c1c1c;',
+ 'font:500 10px/1 "JetBrains Mono",ui-monospace,monospace;color:#4a4a4a;letter-spacing:.08em;text-transform:uppercase;}',
/* live region */
'#tws-search-live{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;}',
/* keyframes */
@@ -190,6 +214,126 @@
{ title: 'Browse all pages', desc: 'The full three.ws directory, filterable', href: '/sitemap', icon: '🗺️', keys: 'sitemap site map all pages everything directory index list browse find' },
];
+ // ── Commands ───────────────────────────────────────────────────────────────
+ // Executable verbs. Unlike QUICK_ACTIONS (which navigate), a command runs in
+ // place: activating it opens the run panel and does the actual work against
+ // the real API. Matching is intentionally strict verb-first parsing — the
+ // palette must never hijack a plain search query.
+
+ function fetchJson(url, opts) {
+ return fetch(url, opts).then(function (r) {
+ if (!r.ok) { var e = new Error('HTTP ' + r.status); e.status = r.status; throw e; }
+ return r.json();
+ });
+ }
+
+ // Anonymous per-browser client id sent to the free forge lane (its only
+ // identifying header; used server-side for telemetry, not auth).
+ function forgeClientId() {
+ try {
+ var v = localStorage.getItem('tws:forge:client');
+ if (!v) {
+ v = Math.random().toString(36).slice(2) + Date.now().toString(36);
+ localStorage.setItem('tws:forge:client', v);
+ }
+ return v;
+ } catch (_) { return 'anon'; }
+ }
+
+ // Broadcast a command lifecycle beat so other surfaces (the corner companion,
+ // the agent bus's mood engine) can react to what the visitor just did.
+ function emitAction(action, phase, detail) {
+ var payload = Object.assign({ action: action, phase: phase }, detail || {});
+ try {
+ document.dispatchEvent(new CustomEvent('tws:palette-action', { detail: payload }));
+ } catch (_) {}
+ try {
+ var bus = window.__agentBus || window.__threewsAgentBus;
+ if (bus && bus.emit) bus.emit('action:taken', Object.assign({ agentId: null, source: 'palette' }, payload));
+ } catch (_) {}
+ }
+
+ var CMD_DEFS = [
+ {
+ id: 'forge',
+ icon: '✨',
+ example: 'forge a bronze dragon statue',
+ prefill: 'forge ',
+ match: function (q) {
+ var m = q.match(/^(?:forge|make|generate|imagine)\s+(.{3,200})$/i);
+ return m ? { prompt: m[1].trim() } : null;
+ },
+ title: function (a) { return 'Forge “' + a.prompt + '”'; },
+ desc: 'Generate a real 3D model right here — free text→​3D lane',
+ run: runForgeCommand,
+ },
+ {
+ id: 'digest',
+ icon: '📰',
+ example: 'digest',
+ match: function (q) {
+ return /^(?:digest|briefing|news digest|what happened(?:\s+today)?\??|today)$/i.test(q) ? {} : null;
+ },
+ title: function () { return 'Today’s crypto digest'; },
+ desc: 'The last 24h clustered into narratives, right here',
+ run: runDigestCommand,
+ },
+ {
+ id: 'price',
+ icon: '💹',
+ example: 'price btc',
+ prefill: 'price ',
+ match: function (q) {
+ var m = q.match(/^(?:price|quote)\s+(.{1,40})$/i) || q.match(/^\$([a-z0-9]{1,15})$/i);
+ return m ? { query: m[1].trim() } : null;
+ },
+ title: function (a) { return 'Price of ' + a.query; },
+ desc: 'Live market data — majors and pump.fun coins',
+ run: runPriceCommand,
+ },
+ {
+ id: 'ask',
+ icon: '💬',
+ example: 'ask what is x402?',
+ prefill: 'ask ',
+ match: function (q) {
+ var m = q.match(/^ask\s+(.{3,400})$/i);
+ if (m) return { question: m[1].trim() };
+ // A natural question ("how do agents pay each other?") is offered as
+ // an option below the search results — never auto-run.
+ if (q.length >= 10 && /\?$/.test(q)) return { question: q };
+ return null;
+ },
+ title: function () { return 'Ask your agent'; },
+ desc: 'Streamed answer from the site agent — free, no account',
+ run: runAskCommand,
+ },
+ ];
+
+ // Parse a query into the first matching command. Exposed on the public API
+ // for tests and for other surfaces (the companion dock) to reuse.
+ function parseCommand(q) {
+ var query = String(q || '').trim();
+ if (!query) return null;
+ for (var i = 0; i < CMD_DEFS.length; i++) {
+ var args = CMD_DEFS[i].match(query);
+ if (args) return { def: CMD_DEFS[i], args: args };
+ }
+ return null;
+ }
+
+ // Every command matching the query (a "$sol?" style query can match two).
+ function matchedCommands(q) {
+ var query = String(q || '').trim();
+ if (!query) return [];
+ var out = [];
+ for (var i = 0; i < CMD_DEFS.length; i++) {
+ var args = CMD_DEFS[i].match(query);
+ if (args) out.push({ def: CMD_DEFS[i], args: args });
+ }
+ return out;
+ }
+
// Default destinations shown when the palette opens with no query (and no
// recent history yet) — the flagship surfaces, so the palette is never empty.
var SUGGESTED_PAGES = [
@@ -282,7 +426,8 @@
return h;
}
- function resultRow(href, iconHTML, name, desc, badge, q) {
+ function resultRow(href, iconHTML, name, desc, badge, q, opts) {
+ var run = opts && opts.run;
var a = el('a', {
class: 'tws-sk-row',
href: href,
@@ -309,6 +454,14 @@
a.appendChild(b);
}
+ if (run) {
+ // Command rows execute in place instead of navigating; they never enter
+ // the Recents list (a recent must be a re-openable destination).
+ a._twsRun = run;
+ a.addEventListener('click', function (e) { e.preventDefault(); run(); });
+ return a;
+ }
+
// Payload replayed into the Recents list when this row is opened.
a._twsRecent = { href: href, name: name, desc: desc || '', badge: badge || '', iconHTML: iconHTML };
@@ -380,7 +533,7 @@
input = el('input', {
id: 'tws-search-input',
type: 'search',
- placeholder: 'Search agents, coins, skills, actions, pages…',
+ placeholder: 'Search — or type forge …, digest, price btc, ask …',
autocomplete: 'off',
autocorrect: 'off',
spellcheck: 'false',
@@ -455,6 +608,7 @@
function close() {
if (!dialog) return;
+ stopRun();
dialog.removeAttribute('open');
document.body.style.overflow = '';
if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = null; }
@@ -470,7 +624,13 @@
// ── Keyboard handlers ──────────────────────────────────────────────────────
function onDialogKeydown(e) {
- if (e.key === 'Escape') { e.preventDefault(); close(); }
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ // From a run panel, Esc steps back to the search results; a second Esc
+ // closes the palette.
+ if (runActive) { exitRunPanel(true); input.focus(); return; }
+ close();
+ }
}
function onKeydown(e) {
@@ -511,6 +671,7 @@
function activateSelected() {
if (selectedIndex >= 0 && allRows[selectedIndex]) {
var row = allRows[selectedIndex];
+ if (row._twsRun) { row._twsRun(); return; }
recordRecent(row._twsRecent);
close();
window.location.href = row.href;
@@ -522,6 +683,12 @@
function showInitial() {
var groups = [];
+ // Lead with the executable verbs — the palette is a command line first.
+ groups.push({
+ label: 'Do',
+ items: CMD_DEFS.map(commandExampleRow),
+ });
+
var recent = loadRecent();
if (recent.length) {
groups.push({
@@ -627,9 +794,348 @@
}
}
+ // ── Command run panel ─────────────────────────────────────────────────────
+ // Activating a command swaps the results list for a run panel and does the
+ // work in place. Esc (or typing) returns to the search results; the palette
+ // itself stays open so the visitor never loses context.
+
+ var runAbort = null; // AbortController for the in-flight command
+ var runActive = false; // whether the run panel currently owns the results area
+ var runTimer = null; // elapsed-time ticker / poll timer
+
+ function stopRun() {
+ if (runAbort) { runAbort.abort(); runAbort = null; }
+ if (runTimer) { clearInterval(runTimer); clearTimeout(runTimer); runTimer = null; }
+ runActive = false;
+ }
+
+ function exitRunPanel(rerunQuery) {
+ stopRun();
+ var q = input.value.trim();
+ if (rerunQuery && q) { showLoading(); runSearch(q); }
+ else showInitial();
+ }
+
+ function spinnerEl() {
+ return el('div', { class: 'tws-sk-spinner', 'aria-hidden': 'true' });
+ }
+
+ // Build the panel chrome and hand the command a small UI toolkit.
+ function openRunPanel(def, args) {
+ stopRun();
+ runActive = true;
+ runAbort = new AbortController();
+ results.innerHTML = '';
+ allRows = [];
+ selectedIndex = -1;
+ status.hidden = true;
+ input.setAttribute('aria-expanded', 'true');
+
+ var head = el('div', { class: 'tws-sk-run-head' });
+ var ico = el('div', { class: 'tws-sk-ico', 'aria-hidden': 'true' });
+ ico.textContent = def.icon;
+ var title = el('div', { class: 'tws-sk-run-title', text: def.title(args) });
+ var statusEl = el('div', { class: 'tws-sk-run-status' });
+ statusEl.appendChild(spinnerEl());
+ var statusText = el('span', { text: 'Working…' });
+ statusEl.appendChild(statusText);
+ head.appendChild(ico);
+ head.appendChild(title);
+ head.appendChild(statusEl);
+
+ var body = el('div', { class: 'tws-sk-run-body' });
+ var foot = el('div', { class: 'tws-sk-run-foot', text: 'Esc — back to search' });
+
+ results.appendChild(head);
+ results.appendChild(body);
+ results.appendChild(foot);
+
+ var ui = {
+ body: body,
+ signal: runAbort.signal,
+ setStatus: function (text, mode) {
+ statusEl.innerHTML = '';
+ statusEl.className = 'tws-sk-run-status' + (mode ? ' ' + mode : '');
+ if (!mode) statusEl.appendChild(spinnerEl());
+ var t = el('span', { text: text });
+ statusEl.appendChild(t);
+ liveRegion.textContent = def.title(args) + ' — ' + text;
+ },
+ // Register result rows for arrow-key navigation inside the panel.
+ addRows: function (rows) {
+ rows.forEach(function (row) {
+ row.id = 'tws-sk-row-' + allRows.length;
+ body.appendChild(row);
+ allRows.push(row);
+ });
+ },
+ fail: function (message, linkHref, linkText) {
+ ui.setStatus('failed', 'err');
+ var msg = el('div', { class: 'tws-sk-answer', text: message });
+ body.appendChild(msg);
+ if (linkHref) {
+ ui.addRows([resultRow(linkHref, '↗', linkText || 'Open', '', '', '')]);
+ }
+ },
+ };
+
+ emitAction(def.id, 'start', { args: args });
+ try {
+ def.run(args, ui);
+ } catch (err) {
+ ui.fail('Command failed: ' + (err && err.message ? err.message : 'unknown error'));
+ }
+ }
+
+ function commandRow(match, q) {
+ var def = match.def;
+ var row = resultRow('#', def.icon, def.title(match.args), def.desc, 'Run', q, {
+ run: function () { openRunPanel(def, match.args); },
+ });
+ return { el: row };
+ }
+
+ // A zero-query example row: activating it prefills the input (teaching the
+ // verb) rather than running with a canned argument. Commands with no
+ // arguments (digest) run directly.
+ function commandExampleRow(def) {
+ var run = def.prefill
+ ? function () {
+ input.value = def.prefill;
+ input.focus();
+ onInput();
+ }
+ : function () { openRunPanel(def, def.match(def.example)); };
+ return { el: resultRow('#', def.icon, def.example, def.desc, 'Run', '', { run: run }) };
+ }
+
+ // ── Command implementations ────────────────────────────────────────────────
+
+ function runForgeCommand(args, ui) {
+ var startedAt = Date.now();
+ var elapsed = function () { return Math.round((Date.now() - startedAt) / 1000) + 's'; };
+ ui.setStatus('forging · 0s');
+ runTimer = setInterval(function () {
+ if (!runActive) return;
+ ui.setStatus('forging · ' + elapsed() + ' — usually 20–60s');
+ }, 1000);
+
+ function finish(job) {
+ clearInterval(runTimer); runTimer = null;
+ ui.setStatus('done · ' + elapsed(), 'ok');
+ var openHref = job.creation_id
+ ? '/forge/share/' + encodeURIComponent(job.creation_id)
+ : '/forge/embed?src=' + encodeURIComponent(job.glb_url);
+ var rows = [
+ resultRow(openHref, '🧊', 'Open your model', 'Orbit it in 3D, share, or remix', 'GLB', ''),
+ resultRow(job.glb_url, '⬇️', 'Download the GLB', 'The raw binary — drop it into any engine', '', ''),
+ resultRow('/forge?prompt=' + encodeURIComponent(args.prompt), '🛠', 'Refine on the Forge', 'Higher tiers, engines, and image input', '', ''),
+ ];
+ ui.addRows(rows);
+ emitAction('forge', 'done', { prompt: args.prompt, glb_url: job.glb_url, creation_id: job.creation_id || null });
+ }
+
+ function poll(jobId) {
+ if (!runActive) return;
+ fetchJson('/api/forge?job=' + encodeURIComponent(jobId), { signal: ui.signal })
+ .then(function (job) {
+ if (!runActive) return;
+ if (job.status === 'done' && job.glb_url) return finish(job);
+ if (job.status === 'failed') {
+ clearInterval(runTimer); runTimer = null;
+ ui.fail(job.error || 'Generation failed — the free lane may be busy.', '/forge', 'Try on the Forge page');
+ emitAction('forge', 'failed', { prompt: args.prompt });
+ return;
+ }
+ if (Date.now() - startedAt > 4 * 60 * 1000) {
+ clearInterval(runTimer); runTimer = null;
+ ui.fail('Still running after 4 minutes — the lane is saturated. Your job may still finish on the Forge page.', '/forge', 'Open the Forge');
+ return;
+ }
+ runTimer = setTimeout(function () { poll(jobId); }, 2500);
+ })
+ .catch(function (err) {
+ if (err && err.name === 'AbortError') return;
+ clearInterval(runTimer); runTimer = null;
+ ui.fail('Lost the job while polling — it may still finish on the Forge page.', '/forge', 'Open the Forge');
+ });
+ }
+
+ fetch('/api/forge', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-forge-client': forgeClientId() },
+ body: JSON.stringify({ prompt: args.prompt }),
+ signal: ui.signal,
+ })
+ .then(function (r) {
+ if (r.status === 429) throw Object.assign(new Error('rate'), { status: 429 });
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ return r.json();
+ })
+ .then(function (job) {
+ if (!runActive) return;
+ if (job.status === 'done' && job.glb_url) return finish(job);
+ if (job.job_id) return poll(job.job_id);
+ throw new Error(job.error || 'unexpected response');
+ })
+ .catch(function (err) {
+ if (err && err.name === 'AbortError') return;
+ clearInterval(runTimer); runTimer = null;
+ if (err && err.status === 429) {
+ ui.fail('Free-lane rate limit reached for now — try again in a few minutes, or use the Forge page.', '/forge', 'Open the Forge');
+ } else {
+ ui.fail('Couldn’t start the generation: ' + err.message, '/forge', 'Try on the Forge page');
+ }
+ emitAction('forge', 'failed', { prompt: args.prompt });
+ });
+ }
+
+ function runDigestCommand(args, ui) {
+ ui.setStatus('clustering the last 24h…');
+ fetchJson('/api/news/digest?hours=24&limit=8', { signal: ui.signal })
+ .then(function (d) {
+ if (!runActive) return;
+ var narratives = (d && d.narratives) || [];
+ if (!narratives.length) {
+ ui.fail('No digest available right now.', '/markets/digest', 'Open the digest page');
+ return;
+ }
+ ui.setStatus(narratives.length + ' stories · mood ' + (d.mood || 'neutral'), 'ok');
+ var stanceIcon = { bullish: '🟢', bearish: '🔴', neutral: '⚪' };
+ var rows = narratives.map(function (n) {
+ var tickers = (n.tickers || []).slice(0, 4).map(function (t) { return '$' + t; }).join(' ');
+ var desc = n.coverage + ' outlets' + (tickers ? ' · ' + tickers : '') + (n.summary ? ' — ' + n.summary : '');
+ var href = (n.articles && n.articles[0] && n.articles[0].link) || '/markets/digest';
+ return resultRow(href, stanceIcon[n.stance] || '⚪', n.title, desc, n.stance || '', '');
+ });
+ rows.push(resultRow('/markets/digest', '📰', 'Read the full digest', 'Every narrative with all covering outlets', '', ''));
+ ui.addRows(rows);
+ emitAction('digest', 'done', { stories: narratives.length, mood: d.mood || null });
+ })
+ .catch(function (err) {
+ if (err && err.name === 'AbortError') return;
+ ui.fail('The digest is unavailable right now.', '/markets/digest', 'Open the digest page');
+ });
+ }
+
+ function runPriceCommand(args, ui) {
+ ui.setStatus('looking up ' + args.query + '…');
+ var q = args.query;
+ fetchJson('/api/coin/markets?q=' + encodeURIComponent(q), { signal: ui.signal })
+ .then(function (d) {
+ var hit = d && d.coins && d.coins[0];
+ if (!hit) throw new Error('no match');
+ return fetchJson('/api/coin/detail?id=' + encodeURIComponent(hit.id), { signal: ui.signal });
+ })
+ .then(function (d) {
+ if (!runActive) return;
+ var c = d && d.coin;
+ if (!c || !c.market) throw new Error('no market data');
+ var m = c.market;
+ var chg = m.change_pct && m.change_pct.h24;
+ var price = m.price != null ? '$' + Number(m.price).toLocaleString('en-US', { maximumFractionDigits: m.price < 1 ? 6 : 2 }) : '—';
+ var chgTxt = chg != null ? (chg >= 0 ? '▲ +' : '▼ ') + chg.toFixed(2) + '% 24h' : '';
+ ui.setStatus(price + (chgTxt ? ' · ' + chgTxt : ''), chg == null ? 'ok' : chg >= 0 ? 'ok' : 'err');
+ var mcap = m.market_cap != null ? 'Mcap $' + Number(m.market_cap).toLocaleString('en-US', { notation: 'compact', maximumFractionDigits: 1 }) : '';
+ var rows = [
+ resultRow('/coin/' + encodeURIComponent(c.id), c.image ? '<img src="' + esc(c.image) + '" alt="" loading="lazy" />' : '🪙',
+ c.name + ' · ' + String(c.symbol || '').toUpperCase(), price + (chgTxt ? ' · ' + chgTxt : '') + (mcap ? ' · ' + mcap : ''),
+ c.rank ? '#' + c.rank : '', ''),
+ resultRow('/compare?ids=' + encodeURIComponent(c.id), '⚖️', 'Compare it', 'Line it up against up to three other coins', '', ''),
+ ];
+ ui.addRows(rows);
+ emitAction('price', 'done', { id: c.id, symbol: c.symbol });
+ })
+ .catch(function (err) {
+ if (err && err.name === 'AbortError') return;
+ // Not a listed major — try pump.fun tokens before giving up.
+ fetchJson('/api/pump/search?q=' + encodeURIComponent(q) + '&limit=3', { signal: ui.signal })
+ .then(function (d) {
+ if (!runActive) return;
+ var coins = (d && d.data) || [];
+ if (!coins.length) {
+ ui.fail('No coin found for “' + q + '”.', '/coins', 'Browse all coins');
+ return;
+ }
+ ui.setStatus('pump.fun match', 'ok');
+ ui.addRows(coins.map(function (c) {
+ var priceTxt = c.price_usd != null ? '$' + Number(c.price_usd).toLocaleString('en-US', { maximumFractionDigits: 8 }) : '';
+ return resultRow('/communities/' + esc(c.mint), coinIcon(c), c.name || c.symbol, (c.symbol ? '$' + c.symbol : '') + (priceTxt ? ' · ' + priceTxt : ''), 'Coin', '');
+ }));
+ emitAction('price', 'done', { query: q, source: 'pump' });
+ })
+ .catch(function (e2) {
+ if (e2 && e2.name === 'AbortError') return;
+ ui.fail('No coin found for “' + q + '”.', '/coins', 'Browse all coins');
+ });
+ });
+ }
+
+ function runAskCommand(args, ui) {
+ ui.setStatus('thinking…');
+ var answer = el('div', { class: 'tws-sk-answer' });
+ answer.setAttribute('aria-live', 'polite');
+ ui.body.appendChild(answer);
+
+ fetch('/api/chat', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ message: args.question,
+ context: 'Asked from the command palette on ' + location.pathname,
+ history: [],
+ }),
+ signal: ui.signal,
+ })
+ .then(function (r) {
+ if (r.status === 401) {
+ ui.fail('Chat needs a signed-in session right now.', '/login', 'Sign in');
+ return null;
+ }
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ var reader = r.body.getReader();
+ var decoder = new TextDecoder();
+ var buffer = '';
+ function pump() {
+ return reader.read().then(function (chunk) {
+ if (chunk.done) return;
+ buffer += decoder.decode(chunk.value, { stream: true });
+ var frames = buffer.split('\n\n');
+ buffer = frames.pop();
+ frames.forEach(function (frame) {
+ var line = frame.split('\n').find(function (l) { return l.indexOf('data: ') === 0; });
+ if (!line) return;
+ var evt;
+ try { evt = JSON.parse(line.slice(6)); } catch (_) { return; }
+ if (evt.type === 'chunk' && evt.text) {
+ answer.textContent += evt.text;
+ answer.scrollTop = answer.scrollHeight;
+ } else if (evt.type === 'done') {
+ if (evt.reply && !answer.textContent) answer.textContent = evt.reply;
+ ui.setStatus('answered', 'ok');
+ emitAction('ask', 'done', { question: args.question });
+ } else if (evt.type === 'error') {
+ ui.fail(evt.error || 'The agent hit an error.');
+ }
+ });
+ return pump();
+ });
+ }
+ return pump();
+ })
+ .catch(function (err) {
+ if (err && err.name === 'AbortError') return;
+ ui.fail('The agent is unreachable right now — try again shortly, or open the full chat.', '/chat', 'Open chat');
+ });
+ }
+
// ── Search ─────────────────────────────────────────────────────────────────
function onInput() {
+ // Typing abandons an open run panel and returns to live search.
+ if (runActive) stopRun();
+
var q = input.value.trim();
if (!q) { showInitial(); return; }
@@ -736,7 +1242,10 @@
};
});
+ var cmdItems = matchedCommands(q).map(function (m) { return commandRow(m, q); });
+
renderResults([
+ { label: 'Do', items: cmdItems },
{ label: 'Actions', items: actionItems },
{ label: 'Agents', items: agentItems },
{ label: 'Coins', items: coinItems },
@@ -776,6 +1285,17 @@
});
// ── Expose public API ──────────────────────────────────────────────────────
+ // parseCommand/runCommand let other surfaces (the corner companion, tests)
+ // reuse the same verb grammar and drive a command programmatically.
+
+ function runCommand(query) {
+ var match = parseCommand(query);
+ if (!match) return false;
+ open();
+ input.value = String(query || '').trim();
+ openRunPanel(match.def, match.args);
+ return true;
+ }
- window.__twsSearch = { open: open, close: close };
+ window.__twsSearch = { open: open, close: close, parseCommand: parseCommand, runCommand: runCommand };
})();
diff --git a/scripts/build-discovery-cards.mjs b/scripts/build-discovery-cards.mjs
new file mode 100644
index 000000000..745641901
--- /dev/null
+++ b/scripts/build-discovery-cards.mjs
@@ -0,0 +1,124 @@
+// Regenerate the static discovery cards in public/ from the live service
+// catalog (api/_lib/service-catalog/), so the cards agents and crawlers read
+// can never drift from what the platform actually sells.
+//
+// Why: these files went stale for weeks — agent-registration.json advertised
+// ONE paid x402 endpoint while /.well-known/x402.json (rendered live from the
+// catalog) advertised 40+, and every description still said "3D model viewer"
+// from the pre-agent-economy era. Static files need a generator or they rot.
+//
+// What it patches (surgically — hand-authored fields are preserved):
+// • public/.well-known/agent-registration.json — description + the FULL
+// x402Endpoints list projected from the catalog (url, method, useCase,
+// networks, scheme, priceUsdc). `registrations` (on-chain write-back,
+// owned by scripts/erc8004-register-self.mjs) is left untouched.
+// • public/.well-known/agent-card.json — description + one generated
+// `x402-service-catalog` skill summarizing the paid catalog by category
+// with live counts and the discovery-doc URL. Hand-written skills stay.
+// • public/.well-known/ai-plugin.json — descriptions updated to the current
+// platform framing (viewer + paid x402 data/3D APIs).
+// • public/crypto-agent-manifest.json — repoints the dead cdn.three.ws
+// sample body at the live default avatar and pins a current model id.
+//
+// Run: npm run build:discovery (wired into prebuild so every deploy is fresh)
+
+import { readFileSync, writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const { getCatalog } = await import(path.join(root, 'api/_lib/service-catalog/index.js'));
+
+const DESCRIPTION =
+ 'three.ws — the 3D agent economy. Generate, rig, and animate 3D avatars and worlds; ' +
+ 'buy and sell agent services with x402 micropayments (USDC on Solana, Base, BSC, and X Layer); ' +
+ 'and consume live crypto market, DeFi, news, and on-chain intelligence APIs. ' +
+ 'Machine-readable paid-service catalog at https://three.ws/.well-known/x402.json.';
+
+function readJson(rel) {
+ return JSON.parse(readFileSync(path.join(root, rel), 'utf8'));
+}
+
+function writeJson(rel, value, { indent = '\t' } = {}) {
+ writeFileSync(path.join(root, rel), `${JSON.stringify(value, null, indent)}\n`);
+ console.log(`[discovery-cards] wrote ${rel}`);
+}
+
+const catalog = await getCatalog();
+const paid = catalog.filter((e) => e.source === 'x402' && e.status === 'live');
+if (paid.length < 40) {
+ // The catalog rendering broke once before (empty-catalog bug, prompt 10) —
+ // refuse to "regenerate" the cards down to a stub instead of shipping rot.
+ throw new Error(`suspiciously small paid catalog (${paid.length} entries) — refusing to regenerate`);
+}
+
+// ── agent-registration.json (ERC-8004 registration-v1) ──────────────────────
+{
+ const reg = readJson('public/.well-known/agent-registration.json');
+ reg.description = DESCRIPTION;
+ reg.x402Endpoints = paid.map((e) => ({
+ url: e.endpoint,
+ method: e.method,
+ description: e.useCase,
+ networks: e.price.networks,
+ scheme: 'exact',
+ priceUsdc: e.price.usd,
+ }));
+ writeJson('public/.well-known/agent-registration.json', reg);
+}
+
+// ── agent-card.json (A2A card with the a2a-x402 extension) ───────────────────
+{
+ const card = readJson('public/.well-known/agent-card.json');
+ card.description = DESCRIPTION;
+ const byCategory = new Map();
+ for (const e of paid) byCategory.set(e.category, (byCategory.get(e.category) || 0) + 1);
+ const categorySummary = [...byCategory.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([cat, n]) => `${cat} (${n})`)
+ .join(', ');
+ const generated = {
+ id: 'x402-service-catalog',
+ name: 'Paid x402 Service Catalog',
+ description:
+ `${paid.length} pay-per-call services settled via x402 (USDC on Solana and Base): ` +
+ `${categorySummary}. Every service is listed with price, input schema, and output example ` +
+ 'in the machine-readable discovery document — fetch it, pick a service, and pay the 402 challenge.',
+ tags: ['x402', 'paid', 'catalog', 'discovery'],
+ examples: [
+ 'Fetch https://three.ws/.well-known/x402.json and list the market-data services',
+ 'Pay the 402 challenge on /api/x402/token-intel to get a token signal',
+ ],
+ url: 'https://three.ws/.well-known/x402.json',
+ };
+ const idx = card.skills.findIndex((s) => s.id === generated.id);
+ if (idx === -1) card.skills.push(generated);
+ else card.skills[idx] = generated;
+ writeJson('public/.well-known/agent-card.json', card);
+}
+
+// ── ai-plugin.json ───────────────────────────────────────────────────────────
+{
+ const plugin = readJson('public/.well-known/ai-plugin.json');
+ plugin.description_for_human =
+ 'three.ws — 3D avatar/world generation and live crypto intelligence APIs, pay-per-call via x402.';
+ plugin.description_for_model =
+ 'three.ws exposes a 3D model viewer plus a paid pay-per-call API catalog settled via the x402 ' +
+ 'protocol (HTTP 402, USDC on Solana and Base): text→3D generation, avatar rigging, token and ' +
+ 'DeFi market intelligence, news sentiment, gas oracles, vanity address mining, and agent ' +
+ 'reputation. The machine-readable catalog with prices and schemas is at ' +
+ 'https://three.ws/.well-known/x402.json; free endpoints are indexed at /api/crypto and /api/3d.';
+ writeJson('public/.well-known/ai-plugin.json', plugin);
+}
+
+// ── crypto-agent-manifest.json (sample agent-manifest/0.2) ───────────────────
+{
+ const manifest = readJson('public/crypto-agent-manifest.json', { indent: ' ' });
+ // cdn.three.ws is dead (connection refused) — point the sample body at the
+ // live default avatar so the manifest demo actually loads.
+ manifest.body.uri = 'https://three.ws/avatars/default.glb';
+ manifest.brain.model = 'claude-sonnet-5';
+ writeJson('public/crypto-agent-manifest.json', manifest, { indent: ' ' });
+}
+
+console.log(`[discovery-cards] done — ${paid.length} paid services projected`);
diff --git a/scripts/x402-register-directories.mjs b/scripts/x402-register-directories.mjs
new file mode 100644
index 000000000..26de3c8b5
--- /dev/null
+++ b/scripts/x402-register-directories.mjs
@@ -0,0 +1,146 @@
+// Register three.ws paid x402 endpoints with the external x402 directories
+// that accept programmatic submissions, and print the exact checklist for the
+// surfaces that need a human (wallet signature / web form / GitHub PR).
+//
+// Why: discovery on x402scan, the CDP Bazaar, and agentic.market is mostly
+// crawl- or settlement-driven, but the long tail of directories (402index,
+// x402-list) accepts direct registration — free listings we should never
+// leave unclaimed. Ranking everywhere is settled-tx volume + distinct buyers
+// in the trailing 30 days; registration gets us FOUND, the ring loop's canary
+// purchases keep us ACTIVE.
+//
+// Usage:
+// node scripts/x402-register-directories.mjs --dry-run # print the plan
+// node scripts/x402-register-directories.mjs # register a batch
+// node scripts/x402-register-directories.mjs --limit 5 # smaller batch
+// node scripts/x402-register-directories.mjs --state <file> # custom ledger
+//
+// 402index rate-limits registration to 10/hour/IP, so each run submits at
+// most --limit (default 8) endpoints and records progress in a ledger file
+// (data/x402-directory-registrations.json) — re-run hourly until it reports
+// nothing left to do. Re-running is safe: registered URLs are skipped via the
+// ledger, and the directory itself reviews duplicates.
+
+import { readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const { getCatalog } = await import(path.join(root, 'api/_lib/service-catalog/index.js'));
+
+const args = process.argv.slice(2);
+const DRY_RUN = args.includes('--dry-run');
+const limitIdx = args.indexOf('--limit');
+const BATCH_LIMIT = limitIdx !== -1 ? Math.max(1, Number(args[limitIdx + 1]) || 8) : 8;
+const stateIdx = args.indexOf('--state');
+const LEDGER_PATH = path.join(
+ root,
+ stateIdx !== -1 ? args[stateIdx + 1] : 'data/x402-directory-registrations.json',
+);
+
+const FOUR02INDEX_REGISTER = 'https://402index.io/api/v1/register';
+
+function loadLedger() {
+ if (!existsSync(LEDGER_PATH)) return { '402index': {} };
+ try {
+ const parsed = JSON.parse(readFileSync(LEDGER_PATH, 'utf8'));
+ return { '402index': {}, ...parsed };
+ } catch {
+ return { '402index': {} };
+ }
+}
+
+function saveLedger(ledger) {
+ writeFileSync(LEDGER_PATH, `${JSON.stringify(ledger, null, '\t')}\n`);
+}
+
+// Only endpoints a directory probe can complete against: live paid x402
+// routes that answer GET/POST with a spec-valid 402 challenge in production.
+const catalog = await getCatalog();
+const candidates = catalog
+ .filter((e) => e.source === 'x402' && e.status === 'live')
+ .map((e) => ({ url: e.endpoint, slug: e.slug, method: e.method, description: e.useCase }));
+
+if (!candidates.length) throw new Error('empty paid catalog — refusing to run');
+
+// Verify each candidate actually serves a 402 in production before submitting
+// it — registering a 404 (not-yet-deployed route) gets rejected by the
+// directory's probe and burns a rate-limited slot.
+async function serves402(entry) {
+ try {
+ const r = await fetch(entry.url, {
+ method: entry.method,
+ headers: { accept: 'application/json', ...(entry.method === 'POST' ? { 'content-type': 'application/json' } : {}) },
+ ...(entry.method === 'POST' ? { body: '{}' } : {}),
+ signal: AbortSignal.timeout(10_000),
+ });
+ return r.status === 402;
+ } catch {
+ return false;
+ }
+}
+
+const ledger = loadLedger();
+const pending = candidates.filter((c) => !ledger['402index'][c.url]?.ok);
+console.log(`catalog: ${candidates.length} live paid endpoints; ${pending.length} not yet registered at 402index`);
+
+let submitted = 0;
+for (const entry of pending) {
+ if (submitted >= BATCH_LIMIT) break;
+
+ const live = await serves402(entry);
+ if (!live) {
+ console.log(`SKIP ${entry.slug} — production does not answer 402 yet (deploy first)`);
+ continue;
+ }
+
+ if (DRY_RUN) {
+ console.log(`DRY ${entry.slug} → POST ${FOUR02INDEX_REGISTER} url=${entry.url}`);
+ submitted++;
+ continue;
+ }
+
+ try {
+ const r = await fetch(FOUR02INDEX_REGISTER, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({
+ url: entry.url,
+ name: `three.ws ${entry.slug}`,
+ protocol: 'x402',
+ description: entry.description,
+ }),
+ signal: AbortSignal.timeout(15_000),
+ });
+ const body = await r.text();
+ const ok = r.ok;
+ ledger['402index'][entry.url] = {
+ ok,
+ status: r.status,
+ at: new Date().toISOString(),
+ response: body.slice(0, 300),
+ };
+ saveLedger(ledger);
+ console.log(`${ok ? 'OK ' : 'ERR '} ${entry.slug} → 402index ${r.status} ${body.slice(0, 120)}`);
+ submitted++;
+ } catch (err) {
+ console.log(`ERR ${entry.slug} → 402index ${err.message}`);
+ }
+}
+
+const remaining = candidates.filter((c) => !ledger['402index'][c.url]?.ok).length;
+console.log(`\n402index: ${submitted} submitted this run, ${remaining} remaining (rate limit 10/h/IP — re-run in an hour if any remain)`);
+
+console.log(`
+── Manual / human-gated surfaces (see docs/x402-distribution.md) ──────────────
+ x402scan https://www.x402scan.com/resources/register — one-time SIWX
+ wallet signature per resource (Base + Solana). No funds move.
+ x402-list https://x402-list.com/submit — web form, first submission
+ free; endpoint is auto-probed for a valid 402 handshake.
+ x402.org PR partner metadata to the x402 repo ecosystem page.
+ awesome-x402 PRs to xpaysh/awesome-x402 and Merit-Systems/awesome-x402.
+ CDP Bazaar settlement-triggered: settle ≥1 payment per endpoint through
+ the CDP facilitator (needs CDP_API_KEY_ID/SECRET on prod),
+ then verify via GET api.cdp.coinbase.com/platform/v2/x402/
+ discovery/resources. agentic.market auto-indexes from there.
+`);
diff --git a/src/agents/guest-agent.js b/src/agents/guest-agent.js
new file mode 100644
index 000000000..70961c061
--- /dev/null
+++ b/src/agents/guest-agent.js
@@ -0,0 +1,97 @@
+// Ephemeral "your agent" for signed-out visitors — the identity behind the
+// first-five-seconds companion. Every visitor gets a named agent immediately;
+// signing up "claims" it (the /create-agent wizard prefills from this draft
+// and POSTs the real agent). This is the agent-identity sibling of
+// src/guest-avatar.js, which stages a GLB the same way for the create flow.
+//
+// A draft is a tiny localStorage record — no wallet, no DB row, no network.
+// The name is provisional: server-side uniqueness is per-account and only
+// checked at claim time (POST /api/agents returns 409 on collision, and the
+// wizard already handles renames).
+
+import { randomAgentName } from '../shared/agent-names.js';
+
+const KEY = '3dagent:guest-agent';
+
+// Companion roster ids (walk-sdk/src/roster.js) that are light enough to be a
+// first-visit default — small embedded-rig GLBs, no retarget cost.
+const STARTER_AVATARS = ['robot', 'fox', 'guide', 'cz'];
+
+// The walk companion reads its avatar choice from this legacy key
+// (walk-sdk/src/config.js); we seed it so the corner agent renders the same
+// body the draft records, but never clobber a choice the visitor already made.
+const WALK_AVATAR_KEY = 'walk:companion:avatar';
+
+function read() {
+ try {
+ const raw = localStorage.getItem(KEY);
+ if (!raw) return null;
+ const rec = JSON.parse(raw);
+ if (!rec || typeof rec !== 'object' || !rec.id || !rec.name) return null;
+ return rec;
+ } catch {
+ return null;
+ }
+}
+
+function write(rec) {
+ try {
+ localStorage.setItem(KEY, JSON.stringify(rec));
+ } catch {
+ /* storage unavailable (private mode) — the caller keeps the in-memory copy */
+ }
+ return rec;
+}
+
+/** The current guest-agent draft, or null. Synchronous and cheap. */
+export function peekGuestAgent() {
+ return read();
+}
+
+/**
+ * Return the guest-agent draft, minting one on first call: a random two-word
+ * name plus a light companion avatar. Idempotent — subsequent calls return the
+ * stored record.
+ * @returns {{ id: string, name: string, avatarId: string, createdAt: number }}
+ */
+export function ensureGuestAgent() {
+ const existing = read();
+ if (existing) return existing;
+ const rec = {
+ id: cryptoRandomId(),
+ name: randomAgentName(),
+ avatarId: STARTER_AVATARS[Math.floor(Math.random() * STARTER_AVATARS.length)],
+ createdAt: Date.now(),
+ };
+ write(rec);
+ try {
+ if (!localStorage.getItem(WALK_AVATAR_KEY)) {
+ localStorage.setItem(WALK_AVATAR_KEY, rec.avatarId);
+ }
+ } catch {
+ /* companion falls back to its own default */
+ }
+ return rec;
+}
+
+/** Merge a patch into the draft (e.g. a rename). No-op when nothing is staged. */
+export function updateGuestAgent(patch) {
+ const rec = read();
+ if (!rec || !patch) return rec;
+ return write({ ...rec, ...patch });
+}
+
+/** Drop the draft — called after the wizard creates the real agent. */
+export function clearGuestAgent() {
+ try {
+ localStorage.removeItem(KEY);
+ } catch {
+ /* ignore */
+ }
+}
+
+function cryptoRandomId() {
+ const bytes = new Uint8Array(8);
+ (globalThis.crypto || window.crypto).getRandomValues(bytes);
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
+}
diff --git a/src/coins-index.js b/src/coins-index.js
index e09369fdb..b3fd6e8f7 100644
--- a/src/coins-index.js
+++ b/src/coins-index.js
@@ -5,6 +5,7 @@
import { formatUsd, formatPercent, escapeHtml as esc } from './shared/coin-format.js';
import { coinRow, COIN_COLUMNS, coinSortValue } from './shared/market-table.js';
+import { onPageReady } from './shell/page-lifecycle.js';
const $ = (id) => document.getElementById(id);
@@ -425,25 +426,39 @@ function scheduleLiquidations() {
liqTimer = setInterval(pollLiquidations, LIQ_POLL_MS);
}
-function loadLiquidations() {
+function loadLiquidations(signal) {
if (!$('cv-liq')) return;
renderLiqSkeleton();
pollLiquidations();
scheduleLiquidations();
- document.addEventListener('visibilitychange', () => {
- if (!document.hidden) pollLiquidations();
- });
+ // A shell navigation away from /coins aborts the signal — stop polling a
+ // strip that no longer exists instead of hitting the API from other pages.
+ signal?.addEventListener('abort', () => clearInterval(liqTimer));
+ document.addEventListener(
+ 'visibilitychange',
+ () => {
+ if (!document.hidden) pollLiquidations();
+ },
+ { signal },
+ );
}
// ── Boot ────────────────────────────────────────────────────────────────────
-
-loadStats();
-// If the liquidations strip's first poll lands before the markets table finishes
-// loading, its top-3 items resolve no symbol→id links yet (state.coins is still
-// empty). Re-render with the same data once the table is in so those items pick
-// up their /coin/:id links without waiting for the next 30s poll.
-loadCoins().then(() => {
- if (lastLiqData) renderLiqPopulated(lastLiqData);
-});
-loadLiquidations();
-wireSearch();
+// /coins is a persistent-shell page (<html data-shell> in pages/coins.html):
+// the module loads once and re-initializes on every shell navigation here.
+
+onPageReady(
+ ({ signal }) => {
+ loadStats();
+ // If the liquidations strip's first poll lands before the markets table finishes
+ // loading, its top-3 items resolve no symbol→id links yet (state.coins is still
+ // empty). Re-render with the same data once the table is in so those items pick
+ // up their /coin/:id links without waiting for the next 30s poll.
+ loadCoins().then(() => {
+ if (lastLiqData) renderLiqPopulated(lastLiqData);
+ });
+ loadLiquidations(signal);
+ wireSearch();
+ },
+ { match: (p) => p.replace(/\/$/, '') === '/coins' },
+);
diff --git a/src/create-agent.js b/src/create-agent.js
index 32db2dcd0..a41365305 100644
--- a/src/create-agent.js
+++ b/src/create-agent.js
@@ -14,6 +14,7 @@
import { apiFetch } from './api.js';
import { getMe, saveRemoteGlbToAccount } from './account.js';
+import { peekGuestAgent, clearGuestAgent } from './agents/guest-agent.js';
import { log } from './shared/log.js';
import { isValidGlbMagic } from './shared/glb-magic.js';
import { track, trackFunnelStep, trackError, ANALYTICS_EVENTS } from './analytics.js';
@@ -151,9 +152,25 @@ async function boot() {
showAuthGate();
return;
}
+ prefillFromGuestDraft();
showStep(0);
}
+// The corner companion mints an ephemeral agent for signed-out visitors
+// (src/agents/guest-agent.js) and its "Claim →" CTA lands here. Carry the
+// draft's name into the wizard so the agent they met is the agent they create.
+// Never overwrite something the user already typed.
+function prefillFromGuestDraft() {
+ const draft = peekGuestAgent();
+ if (!draft?.name) return;
+ const nameEl = $('f-name');
+ if (!nameEl || nameEl.value.trim()) return;
+ nameEl.value = draft.name;
+ state.name = draft.name;
+ $('name-count').textContent = `${draft.name.length} / 60`;
+ setMsg(`Claiming ${draft.name} — your companion becomes a real agent when you finish.`, '');
+}
+
function cacheEls() {
el.form = $('wizard');
el.body = $('wizard-body');
@@ -1188,6 +1205,9 @@ async function submit() {
const agent = createData.agent;
if (!agent?.id) throw new Error('Create succeeded but no agent was returned.');
+ // The ephemeral companion draft is claimed — the real agent replaces it.
+ clearGuestAgent();
+
// Activation funnel: a real agent identity now exists.
trackFunnelStep('activation', ANALYTICS_EVENTS.AGENT_CREATED, {
agent_id: agent.id,
diff --git a/src/markets-page.js b/src/markets-page.js
index 9505e9619..87c73eb72 100644
--- a/src/markets-page.js
+++ b/src/markets-page.js
@@ -7,6 +7,7 @@
import { formatUsd, formatPercent, escapeHtml as esc } from './shared/coin-format.js';
import { coinRow, COIN_COLUMNS, coinSortValue } from './shared/market-table.js';
import { newsCard, wireNewsContainer } from './shared/news-render.js';
+import { onPageReady } from './shell/page-lifecycle.js';
const $ = (id) => document.getElementById(id);
@@ -326,4 +327,6 @@ async function init() {
renderSuite(suiteStats);
}
-init();
+// /markets is a persistent-shell page (<html data-shell> in pages/markets.html):
+// the module loads once and re-initializes on every shell navigation back here.
+onPageReady(() => init(), { match: (p) => p.replace(/\/$/, '') === '/markets' });
diff --git a/src/shared/agent-names.js b/src/shared/agent-names.js
new file mode 100644
index 000000000..aecfb419b
--- /dev/null
+++ b/src/shared/agent-names.js
@@ -0,0 +1,28 @@
+// Random agent names — the client-side twin of the wordlist namer in
+// api/_lib/launcher-sources.js (randomCoin). That module is server-only (it
+// sits next to fetch-based launch sources), so the wordlists are mirrored here
+// rather than imported; keep the two lists in sync when editing either.
+// Dependency-free on purpose: the guest-agent draft mints a name before any
+// API or heavy bundle has loaded.
+
+export const ADJECTIVES = [
+ 'Turbo', 'Cosmic', 'Feral', 'Velvet', 'Quantum', 'Rogue', 'Lucid', 'Hyper',
+ 'Molten', 'Neon', 'Phantom', 'Atomic', 'Wild', 'Solar', 'Frostbit', 'Electric',
+ 'Savage', 'Mythic', 'Stellar', 'Chrome', 'Gilded', 'Vapor', 'Radiant', 'Drift',
+];
+
+export const NOUNS = [
+ 'Otter', 'Comet', 'Goblin', 'Yeti', 'Falcon', 'Mantis', 'Kraken', 'Pixel',
+ 'Nomad', 'Bishop', 'Tiger', 'Sprout', 'Anvil', 'Specter', 'Lotus', 'Bandit',
+ 'Phoenix', 'Walrus', 'Cobra', 'Maple', 'Raven', 'Bison', 'Koi', 'Hawk',
+];
+
+/**
+ * A friendly two-word agent name, e.g. "Turbo Otter".
+ * @param {() => number} [rand] - injectable RNG for deterministic tests
+ * @returns {string}
+ */
+export function randomAgentName(rand = Math.random) {
+ const pick = (arr) => arr[Math.min(arr.length - 1, Math.floor(rand() * arr.length))];
+ return `${pick(ADJECTIVES)} ${pick(NOUNS)}`;
+}
diff --git a/src/shell/page-lifecycle.js b/src/shell/page-lifecycle.js
new file mode 100644
index 000000000..45c893f5c
--- /dev/null
+++ b/src/shell/page-lifecycle.js
@@ -0,0 +1,49 @@
+// Page lifecycle for persistent-shell pages.
+//
+// On a shell page (<html data-shell>), navigating to another shell page swaps
+// only <main> — the document, and therefore every loaded module, survives.
+// A page module that initializes at import time would then run exactly once
+// and never again. onPageReady() is the contract that fixes that:
+//
+// import { onPageReady } from './shell/page-lifecycle.js';
+// onPageReady(({ signal }) => init(), { match: (p) => p === '/markets' });
+//
+// Semantics:
+// • Runs the initializer immediately on import (first load — also covers a
+// module injected mid-swap by view-transitions.js).
+// • Re-runs it on every 'shell:navigated' event whose destination pathname
+// passes `match` — with a fresh AbortSignal, the previous run's signal
+// aborted first, so document/window listeners registered with { signal }
+// clean themselves up.
+// • Runs at most once per navigation: window.__shellNavId (incremented by
+// view-transitions.js before scripts/events fire) is the dedupe token, so
+// an injected module that inits on import doesn't init again when the
+// same navigation's event reaches it.
+
+export function onPageReady(init, { match = () => true } = {}) {
+ let lastNavId = null;
+ let controller = null;
+
+ const run = () => {
+ const navId = window.__shellNavId || 0;
+ if (navId === lastNavId) return;
+ if (!match(location.pathname)) {
+ // Navigated away from this module's page — tear down its listeners.
+ controller?.abort();
+ controller = null;
+ lastNavId = navId;
+ return;
+ }
+ lastNavId = navId;
+ controller?.abort();
+ controller = new AbortController();
+ init({ signal: controller.signal });
+ };
+
+ if (match(location.pathname)) {
+ lastNavId = window.__shellNavId || 0;
+ controller = new AbortController();
+ init({ signal: controller.signal });
+ }
+ document.addEventListener('shell:navigated', run);
+}
diff --git a/src/view-transitions.js b/src/view-transitions.js
index 991e0ceaf..55c472c62 100644
--- a/src/view-transitions.js
+++ b/src/view-transitions.js
@@ -1,17 +1,23 @@
-// Native View Transitions for internal navigation.
+// Native View Transitions + persistent-shell navigation.
//
-// Chrome 111+, Safari 18+, Firefox flagged. Falls back to a normal location
-// change in browsers that don't support it — no UX regression.
+// Two tiers, one delegated click listener:
//
-// Behavior:
-// - Intercept clicks on same-origin <a> links that aren't downloads, hash-
-// only, or external-target.
-// - Wrap the navigation in document.startViewTransition() so the browser
-// auto-morphs old → new page state. Pages opt into per-element morphs by
-// setting CSS `view-transition-name` on shared elements (avatar card →
-// hero, marketplace tile → product page, etc.).
+// 1. Every page: same-origin link clicks are wrapped in
+// document.startViewTransition() so the browser auto-morphs old → new
+// page state (Chrome 111+, Safari 18+; falls back to a normal location
+// change — no UX regression).
//
-// No JS framework dependency — just a single delegated listener.
+// 2. Shell pages (<html data-shell>): navigation between two shell-marked
+// pages swaps ONLY <main> (plus title/meta) in place. The header, footer,
+// corner stack, command palette, and the walking companion agent are
+// never torn down — a live WebGL avatar or a streaming answer survives
+// the navigation. Page modules re-init through src/shell/page-lifecycle.js
+// (onPageReady), keyed off the 'shell:navigated' document event and the
+// window.__shellNavId token this file increments per swap.
+//
+// CONSTRAINTS (see the 'view-transitions' plugin in vite.config.js, which
+// inlines this file as a classic script on every page): keep it dependency-
+// free, keep exactly one `export function`, and no other module syntax.
const SUPPORTED = typeof document !== 'undefined' && 'startViewTransition' in document;
@@ -28,14 +34,137 @@ function isInternalLink(a) {
return true;
}
-function handleClick(e) {
- if (e.defaultPrevented) return;
- if (e.button !== 0) return;
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
- const a = e.target.closest?.('a[href]');
- if (!a || !isInternalLink(a)) return;
- e.preventDefault();
- const dest = a.href;
+// ── Persistent shell ─────────────────────────────────────────────────────────
+
+const SHELL_ATTR = 'data-shell';
+let shellFetchController = null; // in-flight swap fetch (latest click wins)
+let popstateWired = false;
+
+function isShellPage() {
+ return document.documentElement.hasAttribute(SHELL_ATTR);
+}
+
+// Await any stylesheet the destination needs that this document doesn't have
+// yet — appending after the swap would flash unstyled content.
+function mergeStylesheets(doc) {
+ const waits = [];
+ doc.querySelectorAll('head link[rel="stylesheet"][href]').forEach((link) => {
+ const href = link.getAttribute('href');
+ if (document.querySelector(`link[rel="stylesheet"][href="${CSS.escape(href)}"]`)) return;
+ waits.push(
+ new Promise((resolveLoad) => {
+ const el = document.createElement('link');
+ el.rel = 'stylesheet';
+ el.href = href;
+ el.addEventListener('load', resolveLoad, { once: true });
+ el.addEventListener('error', resolveLoad, { once: true });
+ document.head.appendChild(el);
+ }),
+ );
+ });
+ return Promise.all(waits);
+}
+
+function syncMeta(doc) {
+ document.title = doc.title;
+ const copy = (selector) => {
+ const next = doc.querySelector(selector);
+ const cur = document.querySelector(selector);
+ if (next && cur) {
+ const attr = next.hasAttribute('content') ? 'content' : 'href';
+ cur.setAttribute(attr, next.getAttribute(attr) || '');
+ }
+ };
+ copy('meta[name="description"]');
+ copy('link[rel="canonical"]');
+ copy('meta[property="og:title"]');
+ copy('meta[property="og:url"]');
+}
+
+// Bring in the destination's page modules. Same-src module scripts are a no-op
+// by the browser's module map, so only genuinely new entries execute; already-
+// loaded modules re-init via their onPageReady 'shell:navigated' listener.
+function runPageScripts(doc) {
+ doc.querySelectorAll('script[type="module"][src]').forEach((s) => {
+ const src = s.getAttribute('src');
+ if (document.querySelector(`script[type="module"][src="${CSS.escape(src)}"]`)) return;
+ const el = document.createElement('script');
+ el.type = 'module';
+ el.src = src;
+ document.body.appendChild(el);
+ });
+}
+
+async function shellSwap(dest, { push = true } = {}) {
+ shellFetchController?.abort();
+ shellFetchController = new AbortController();
+ const res = await fetch(dest, {
+ headers: { accept: 'text/html' },
+ signal: shellFetchController.signal,
+ });
+ if (!res.ok) return false;
+ const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
+ // Both ends must opt in — an unmarked destination gets a full navigation
+ // (its scripts may assume a fresh document).
+ if (!doc.documentElement.hasAttribute(SHELL_ATTR)) return false;
+ const newMain = doc.querySelector('main');
+ const curMain = document.querySelector('main');
+ if (!newMain || !curMain) return false;
+
+ await mergeStylesheets(doc);
+
+ if (push) history.pushState({ shell: true }, '', dest);
+ wirePopstate();
+
+ const apply = () => {
+ syncMeta(doc);
+ curMain.replaceWith(document.adoptNode(newMain));
+ window.scrollTo(0, 0);
+ };
+ if (SUPPORTED) {
+ const t = document.startViewTransition(apply);
+ t?.ready?.catch(() => {});
+ await t?.finished?.catch(() => {});
+ } else {
+ apply();
+ }
+
+ // Bump the nav token BEFORE scripts/events so a freshly injected module and
+ // an already-loaded one agree on which navigation they are initializing for.
+ window.__shellNavId = (window.__shellNavId || 0) + 1;
+ runPageScripts(doc);
+ document.dispatchEvent(new CustomEvent('shell:navigated', { detail: { url: String(dest) } }));
+
+ // Accessibility: a swap is a navigation — move focus to the new content.
+ const main = document.querySelector('main');
+ if (main) {
+ if (!main.hasAttribute('tabindex')) main.setAttribute('tabindex', '-1');
+ main.focus({ preventScroll: true });
+ }
+ return true;
+}
+
+function wirePopstate() {
+ if (popstateWired) return;
+ popstateWired = true;
+ window.addEventListener('popstate', () => {
+ // Back/forward across swapped entries: try to swap to the restored URL;
+ // anything unexpected falls back to a real load of the current URL.
+ shellSwap(location.href, { push: false })
+ .then((ok) => {
+ if (!ok) location.reload();
+ })
+ .catch(() => location.reload());
+ });
+}
+
+// ── Click handling ───────────────────────────────────────────────────────────
+
+function fallbackNavigate(dest) {
+ if (!SUPPORTED) {
+ location.href = dest;
+ return;
+ }
const transition = document.startViewTransition(() => {
location.href = dest;
});
@@ -47,8 +176,32 @@ function handleClick(e) {
transition?.finished?.catch(() => {});
}
+function handleClick(e) {
+ if (e.defaultPrevented) return;
+ if (e.button !== 0) return;
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
+ const a = e.target.closest?.('a[href]');
+ if (!a || !isInternalLink(a)) return;
+ e.preventDefault();
+ const dest = a.href;
+ if (isShellPage()) {
+ shellSwap(dest)
+ .then((ok) => {
+ if (!ok) fallbackNavigate(dest);
+ })
+ .catch((err) => {
+ if (err?.name === 'AbortError') return; // superseded by a newer click
+ fallbackNavigate(dest);
+ });
+ return;
+ }
+ fallbackNavigate(dest);
+}
+
export function enableViewTransitions() {
- if (!SUPPORTED) return false;
+ // The shell swap works without startViewTransition (it just skips the
+ // morph), so wire the listener even where the API is missing.
+ if (typeof document === 'undefined') return false;
// Idempotent — safe to call from every page entry.
if (document._viewTransitionsWired) return true;
document._viewTransitionsWired = true;
diff --git a/src/walk-companion-identity.js b/src/walk-companion-identity.js
new file mode 100644
index 000000000..9dadc5585
--- /dev/null
+++ b/src/walk-companion-identity.js
@@ -0,0 +1,202 @@
+// Companion identity — turns the corner avatar from an anonymous mascot into
+// "your agent". Non-invasive add-on in the same style as walk-trails /
+// click-to-walk: it observes the live walk-sdk instance (never edits the SDK)
+// and slots a small identity chip into the companion's host chrome.
+//
+// What it does:
+// • Guests get an ephemeral agent on the spot — a named draft minted by
+// src/agents/guest-agent.js — with a "Claim →" CTA into /create-agent,
+// which prefills from the draft and POSTs the real agent on signup.
+// • Signed-in visitors get their canonical agent's name (active-agent.js).
+// • A one-time introduction bubble when the companion was auto-summoned.
+// • Reactions to command-palette work: the avatar waves and comments when a
+// ⌘K command (forge / digest / price / ask) completes.
+
+import { ensureGuestAgent } from './agents/guest-agent.js';
+
+const AUTH_HINT_KEY = '3dagent:auth-hint';
+const INTRO_KEY = 'tws:companion:introduced';
+const AUTO_KEY = 'walk:companion:auto';
+
+function readJson(storage, key) {
+ try {
+ const raw = storage.getItem(key);
+ return raw ? JSON.parse(raw) : null;
+ } catch {
+ return null;
+ }
+}
+
+function isAuthed() {
+ const hint = readJson(localStorage, AUTH_HINT_KEY);
+ return !!(hint && hint.authed);
+}
+
+function ensureChipStyles() {
+ const id = 'walk-companion-identity-style';
+ if (document.getElementById(id)) return;
+ const s = document.createElement('style');
+ s.id = id;
+ s.textContent = [
+ '.walk-companion-id{position:absolute;bottom:4px;left:50%;transform:translateX(-50%);',
+ 'display:inline-flex;align-items:center;gap:6px;max-width:calc(100% - 8px);',
+ 'padding:3px 8px;border-radius:999px;background:rgba(12,14,20,.72);',
+ 'backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);',
+ 'font:600 10.5px/1.2 "Inter",system-ui,sans-serif;color:#f2f2f2;',
+ 'letter-spacing:.01em;white-space:nowrap;pointer-events:auto;z-index:3;',
+ 'border:1px solid rgba(255,255,255,.14);transition:background .15s ease,border-color .15s ease;}',
+ '.walk-companion-id:hover{background:rgba(12,14,20,.9);border-color:rgba(255,255,255,.28);}',
+ '.walk-companion-id-name{overflow:hidden;text-overflow:ellipsis;}',
+ '.walk-companion-id-claim{color:#8ab4ff;text-decoration:none;font-weight:700;}',
+ '.walk-companion-id-claim:hover,.walk-companion-id-claim:focus-visible{color:#b7d1ff;text-decoration:underline;}',
+ '.walk-companion-id-claim:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px;border-radius:4px;}',
+ ].join('');
+ document.head.appendChild(s);
+}
+
+async function resolveIdentity() {
+ if (isAuthed()) {
+ try {
+ // Lazy import: keeps apiFetch/active-agent out of the guest path entirely.
+ const mod = await import('./agents/active-agent.js');
+ const agent = await mod.getActiveAgent();
+ if (agent && agent.name) {
+ return { name: agent.name, guest: false, href: agent.id ? `/agent/${agent.id}` : '/dashboard' };
+ }
+ } catch {
+ /* fall through to the hint-name below */
+ }
+ const hint = readJson(localStorage, AUTH_HINT_KEY);
+ return { name: hint?.name ? `${hint.name}’s agent` : 'Your agent', guest: false, href: '/dashboard' };
+ }
+ const draft = ensureGuestAgent();
+ return { name: draft.name, guest: true, href: '/create-agent?from=companion' };
+}
+
+function buildChip(identity) {
+ const chip = document.createElement('div');
+ chip.className = 'walk-companion-id';
+ chip.setAttribute('data-walk-block', '');
+ const name = document.createElement(identity.guest ? 'span' : 'a');
+ name.className = 'walk-companion-id-name';
+ name.textContent = identity.name;
+ if (!identity.guest) {
+ name.href = identity.href;
+ name.style.color = 'inherit';
+ name.style.textDecoration = 'none';
+ name.setAttribute('aria-label', `${identity.name} — open your agent`);
+ }
+ chip.appendChild(name);
+ if (identity.guest) {
+ const claim = document.createElement('a');
+ claim.className = 'walk-companion-id-claim';
+ claim.href = identity.href;
+ claim.textContent = 'Claim →';
+ claim.setAttribute(
+ 'aria-label',
+ `Claim ${identity.name} — create your account and make this agent real`,
+ );
+ chip.appendChild(claim);
+ }
+ return chip;
+}
+
+function introduce(instance, identity) {
+ let auto = false;
+ try {
+ auto = localStorage.getItem(AUTO_KEY) === '1' && !sessionStorage.getItem(INTRO_KEY);
+ } catch {
+ return;
+ }
+ if (!auto || !identity.guest) return;
+ // Let the SDK's own arrival greeting finish before speaking.
+ setTimeout(() => {
+ if (!instance.mounted) return;
+ try {
+ sessionStorage.setItem(INTRO_KEY, '1');
+ instance._say(`I’m ${identity.name} — your agent. Press ⌘K and put me to work.`);
+ } catch {
+ /* bubble is decorative — never fatal */
+ }
+ }, 6500);
+}
+
+// React to real work done through the command palette: a wave plus a short
+// comment makes the agent feel like it did the job (it did — same session,
+// same identity).
+const REACTIONS = {
+ forge: {
+ start: () => 'On it — forging your model…',
+ done: () => 'Done — your model is ready ✨',
+ failed: () => 'That forge didn’t take — try again in a minute.',
+ },
+ digest: { done: (d) => `That’s the day in ${d.stories || 'a few'} stories.` },
+ price: { done: () => null },
+ ask: { done: () => null },
+};
+
+function installReactions(getInstance) {
+ document.addEventListener('tws:palette-action', (e) => {
+ const { action, phase } = e.detail || {};
+ const instance = getInstance();
+ if (!instance || !instance.mounted) return;
+ const line = REACTIONS[action]?.[phase]?.(e.detail);
+ try {
+ if (phase === 'done') instance.controller?.playWave?.();
+ if (line) instance._say(line);
+ } catch {
+ /* companion mid-swap — skip the flourish */
+ }
+ });
+}
+
+/**
+ * Install the identity layer. Follows the live instance across avatar swaps
+ * and playground round-trips by re-attaching whenever the host changes.
+ * @param {{ getInstance: () => object|null }} opts
+ */
+export function installIdentity({ getInstance }) {
+ ensureChipStyles();
+ installReactions(getInstance);
+
+ let chipHost = null;
+ let identity = null;
+ let resolving = false;
+ let introduced = false;
+
+ async function tick() {
+ const instance = getInstance();
+ const host = instance?.mounted ? instance.host : null;
+ if (!host) {
+ chipHost = null;
+ return;
+ }
+ if (host === chipHost && host.querySelector('.walk-companion-id')) return;
+ if (!identity && !resolving) {
+ resolving = true;
+ identity = await resolveIdentity().catch(() => null);
+ resolving = false;
+ }
+ if (!identity) return;
+ host.querySelector('.walk-companion-id')?.remove();
+ host.appendChild(buildChip(identity));
+ chipHost = host;
+ if (!introduced) {
+ introduced = true;
+ introduce(instance, identity);
+ }
+ }
+
+ tick();
+ // Host changes are rare (mount, swap, detach) — a slow poll is cheaper and
+ // more robust than wiring into SDK internals.
+ setInterval(tick, 1200);
+
+ // A sign-in in another tab upgrades the chip in this one.
+ window.addEventListener('storage', (e) => {
+ if (e.key === AUTH_HINT_KEY) {
+ identity = null;
+ chipHost = null;
+ }
+ });
+}
diff --git a/src/walk-companion.js b/src/walk-companion.js
index ff9c37573..ff23b1bb8 100644
--- a/src/walk-companion.js
+++ b/src/walk-companion.js
@@ -17,6 +17,7 @@ import { installTransitions } from './walk-companion-transitions.js';
import { createWalkTrails2D, createTrailSetting, TRAIL_STYLE_LABELS } from './walk-trails.js';
import { installClickToWalk } from './walk-companion-click-to-walk.js';
import { installNarrator } from './walk-companion-narrator.js';
+import { installIdentity } from './walk-companion-identity.js';
// The companion is the site-wide "your agent" body. Booting the mood embodiment
// here makes it reflect the agent's live emotional state (aura + breathing) on
// every page the companion runs — and starts the mood engine for the session.
@@ -279,4 +280,11 @@ installNarrator({
storageKey: NARRATE_KEY,
});
+// ── Identity ─────────────────────────────────────────────────────────────────
+// The corner avatar is "your agent", not a mascot: guests get a named
+// ephemeral agent (claimable into a real one), signed-in visitors see their
+// canonical agent, and the avatar reacts when ⌘K commands finish. See
+// src/walk-companion-identity.js.
+installIdentity({ getInstance: () => walk.instance });
+
walk.bootstrap();
diff --git a/tests/market-data-api.test.js b/tests/market-data-api.test.js
new file mode 100644
index 000000000..0d3f66887
--- /dev/null
+++ b/tests/market-data-api.test.js
@@ -0,0 +1,207 @@
+// Paid Market Data API (/api/x402/market-*) — wiring + contract guards.
+//
+// Three layers, all offline (no upstream calls, no payment):
+// 1. Registry invariants — the single-source-of-truth entries every surface
+// (live 402, service catalog, discovery doc, free index) derives from.
+// 2. Fetcher param validation — rejected params throw {status:422} BEFORE
+// any upstream fetch, which the paid-endpoint wrapper maps to an error
+// response pre-settle: a malformed request is never charged.
+// 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';
+
+// Discovery env must be set BEFORE the paid-endpoint stack loads — same stub
+// set tests/service-catalog.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 { MARKET_CATEGORIES, MARKET_CATEGORY_BY_SLUG } = await import(
+ '../api/_lib/market-data/registry.js'
+);
+const { MARKET_FETCHERS } = await import('../api/_lib/market-data/fetch.js');
+const { MARKET_DATA_SERVICES } = await import(
+ '../api/_lib/service-catalog/services/market-data.js'
+);
+
+const params = (obj = {}) => new URLSearchParams(obj);
+
+async function expectRejection(promise, { status, code }) {
+ let err;
+ try {
+ await promise;
+ } catch (e) {
+ err = e;
+ }
+ expect(err, 'expected the fetcher to throw').toBeTruthy();
+ expect(err.status).toBe(status);
+ expect(err.code).toBe(code);
+}
+
+// ── Registry invariants ─────────────────────────────────────────────────────
+describe('market-data registry', () => {
+ it('covers every category with exactly one fetcher (no orphans either way)', () => {
+ const registrySlugs = [...MARKET_CATEGORY_BY_SLUG.keys()].sort();
+ const fetcherSlugs = Object.keys(MARKET_FETCHERS).sort();
+ expect(fetcherSlugs).toEqual(registrySlugs);
+ });
+
+ it('every entry carries complete listing metadata', () => {
+ expect(MARKET_CATEGORIES.length).toBeGreaterThanOrEqual(17);
+ const slugs = new Set();
+ for (const c of MARKET_CATEGORIES) {
+ expect(c.slug, c.slug).toMatch(/^market-[a-z-]+$/);
+ expect(slugs.has(c.slug), `duplicate slug ${c.slug}`).toBe(false);
+ slugs.add(c.slug);
+ // The catalog test requires ≥60-char descriptions and ≤5 tags; enforce
+ // at the source so a new category can't regress the discovery listing.
+ expect(c.description.length, `${c.slug} description`).toBeGreaterThanOrEqual(60);
+ expect(c.tags.length, `${c.slug} tags`).toBeGreaterThanOrEqual(2);
+ expect(c.tags.length, `${c.slug} tags`).toBeLessThanOrEqual(5);
+ expect(c.priceAtomics).toMatch(/^\d+$/);
+ expect(c.useCases.length).toBeGreaterThan(0);
+ expect(c.inputSchema.type).toBe('object');
+ expect(c.outputExample && typeof c.outputExample).toBe('object');
+ // The advertised example must only use declared params (CDP validates
+ // the listing's info block against its own schema — a stray key delists).
+ for (const key of Object.keys(c.inputExample)) {
+ expect(c.inputSchema.properties[key], `${c.slug} example key ${key}`).toBeTruthy();
+ }
+ }
+ });
+
+ it('projects one catalog descriptor per category on the /api/x402/<slug> path', () => {
+ expect(MARKET_DATA_SERVICES.length).toBe(MARKET_CATEGORIES.length);
+ for (const s of MARKET_DATA_SERVICES) {
+ expect(s.path).toBe(`/api/x402/${s.slug}`);
+ expect(s.status).toBe('live');
+ expect(s.acceptsBuilder).toBe('standard');
+ expect(s.priceAtomics).toBe(MARKET_CATEGORY_BY_SLUG.get(s.slug).priceAtomics);
+ }
+ });
+});
+
+// ── Fetcher validation (pre-settle rejections, no network) ─────────────────
+describe('market-data fetcher validation', () => {
+ it('market-coins rejects a malformed category and an over-long search', async () => {
+ await expectRejection(MARKET_FETCHERS['market-coins'](params({ category: 'Not A Slug!' })), {
+ status: 422,
+ code: 'invalid_category',
+ });
+ await expectRejection(MARKET_FETCHERS['market-coins'](params({ q: 'x'.repeat(65) })), {
+ status: 422,
+ code: 'invalid_query',
+ });
+ });
+
+ it('market-coin rejects a bad contract and a missing id', async () => {
+ await expectRejection(MARKET_FETCHERS['market-coin'](params({ contract: 'nope' })), {
+ status: 422,
+ code: 'invalid_contract',
+ });
+ await expectRejection(MARKET_FETCHERS['market-coin'](params()), {
+ status: 422,
+ code: 'invalid_id',
+ });
+ });
+
+ it('market-chart rejects an invalid window and a bad id', async () => {
+ await expectRejection(MARKET_FETCHERS['market-chart'](params({ id: 'bitcoin', days: '13' })), {
+ status: 422,
+ code: 'invalid_days',
+ });
+ await expectRejection(MARKET_FETCHERS['market-chart'](params({ id: 'NOT VALID' })), {
+ status: 422,
+ code: 'invalid_id',
+ });
+ });
+
+ it('market-derivatives rejects an unknown view', async () => {
+ await expectRejection(MARKET_FETCHERS['market-derivatives'](params({ view: 'spot' })), {
+ status: 422,
+ code: 'invalid_view',
+ });
+ });
+
+ it('market-yields rejects a malformed pool uuid', async () => {
+ await expectRejection(MARKET_FETCHERS['market-yields'](params({ pool: 'not-a-uuid' })), {
+ status: 422,
+ code: 'invalid_pool',
+ });
+ });
+});
+
+// ── Live 402 challenge ──────────────────────────────────────────────────────
+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 challenge(slug, search = '') {
+ const mod = await import(`../api/x402/${slug}.js`);
+ const res = fakeRes();
+ await mod.default(
+ { method: 'GET', url: `/api/x402/${slug}${search}`, headers: { host: 'three.ws' } },
+ res,
+ );
+ return res;
+}
+
+// The challenge may advertise additional rails (e.g. the env-gated $THREE
+// accept) at converted amounts — the price contract we guard is the USDC one.
+const USDC_ASSETS = new Set([
+ process.env.X402_ASSET_MINT_SOLANA,
+ process.env.X402_ASSET_ADDRESS_BASE,
+ process.env.X402_ASSET_ADDRESS_ARBITRUM,
+]);
+const usdcAmounts = (body) =>
+ body.accepts
+ .filter((a) => USDC_ASSETS.has(a.asset))
+ .map((a) => a.amount ?? a.maxAmountRequired);
+
+describe('market-data 402 challenges', () => {
+ it('an unpaid market-global call gets a 402 advertising the registry price', async () => {
+ const res = await challenge('market-global');
+ expect(res.statusCode).toBe(402);
+ const amounts = usdcAmounts(JSON.parse(res.body));
+ expect(amounts.length).toBeGreaterThan(0);
+ expect(amounts.every((a) => a === MARKET_CATEGORY_BY_SLUG.get('market-global').priceAtomics)).toBe(true);
+ });
+
+ it('the pulse bundle prices at its own premium tier', async () => {
+ const res = await challenge('market-pulse');
+ expect(res.statusCode).toBe(402);
+ const amounts = usdcAmounts(JSON.parse(res.body));
+ expect(amounts.length).toBeGreaterThan(0);
+ expect(amounts.every((a) => a === MARKET_CATEGORY_BY_SLUG.get('market-pulse').priceAtomics)).toBe(true);
+ });
+
+ it('every category route module builds a live handler', async () => {
+ for (const c of MARKET_CATEGORIES) {
+ const mod = await import(`../api/x402/${c.slug}.js`);
+ expect(typeof mod.default, c.slug).toBe('function');
+ }
+ });
+});