Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(tests): add unit tests for <agent-3d> brain resolution logic
fudjia70beb5afafd1
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex cd164bc3e..e10796006 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -540,7 +540,7 @@ See [MCP Layer](#mcp-layer) section for full tool listings.#### x402 Paid Endpoints (`api/x402/*`)-**34 files** in `api/x402/`, each a paid endpoint built on `paidEndpoint()`. Payable on Base USDC, Solana USDC, and (for `model-check`/`mint-to-mesh`) Arbitrum One USDC; discoverable via `/.well-known/x402.json` + `/openapi.json`. Additional priced endpoints beyond the table: `model-check` ($0.001), `mint-to-mesh-batch` ($0.05), `revenue-vision` ($0.001), `symbol-availability` ($0.001), `permit2-paid-demo` ($0.001, Base gas-sponsored EIP-2612), `onchain-identity-verify` ($0.005), `agent-reputation` ($0.01), `pump-agent-audit` ($0.02). Sample paid MCP-tool prices: `render_avatar` $0.005, `text_to_3d`/`image_to_3d` $0.15, `mesh_forge` $0.25, `forge_avatar` $0.45, `ibm_granite_forecast` $0.05.+**34 files** in `api/x402/`, each a paid endpoint built on `paidEndpoint()`. Payable on Base USDC, Solana USDC, and (for `model-check`/`mint-to-mesh`) Arbitrum One USDC; discoverable via `/.well-known/x402.json` + `/openapi.json`. Additional priced endpoints beyond the table: `model-check` ($0.001), `mint-to-mesh-batch` ($0.05), `symbol-availability` ($0.001), `permit2-paid-demo` ($0.001, Base gas-sponsored EIP-2612), `onchain-identity-verify` ($0.005), `agent-reputation` ($0.01), `pump-agent-audit` ($0.02). Sample paid MCP-tool prices: `render_avatar` $0.005, `text_to_3d`/`image_to_3d` $0.15, `mesh_forge` $0.25, `forge_avatar` $0.45, `ibm_granite_forecast` $0.05.Representative endpoints:@@ -699,7 +699,7 @@ Beyond the feature areas above, the `api/` tree exposes many more surfaces. Comp| `/api/monetization/*` | `prices`, `revenue`, `wallet`, `withdrawals` | Per-agent price config, revenue, payout wallet, withdrawals || `/api/custody/*` | `anchor`, `integrity` | Proof-of-custody public epoch anchors + integrity checks || `/api/ledger/[agentId]` | `[agentId]`, `verify/` | Reasoning Ledger: explainable agent-decision timeline |-| `/api/onramp/link`, `/api/usage/summary`, `/api/insights/revenue-vision` | — | Fiat on-ramp link, per-user usage summary, revenue-vision insights |+| `/api/onramp/link`, `/api/usage/summary` | — | Fiat on-ramp link, per-user usage summary || `/api/token/[action]` | `[action]` | $THREE on-chain token HTTP layer (price/balance/burn surface) || `/api/cz/claim`, `/api/cosmetics/*` | `catalog`, `owned`, `earnings`, `leaderboard`, `split` | Cosmetics catalog + creator revenue split + ownership |@@ -3162,7 +3162,6 @@ All **150+ directories** under `api/` plus many top-level single-file endpoints.| `guardian/` | assess | Granite Guardian assessment. || `ibm/` | attest, galaxy, oracle, twin, vision | IBM Granite product surfaces. || `inference/` | livepeer | Livepeer inference proxy. |-| `insights/` | revenue-vision | AI revenue insights. || `intel/` | smart-money, wallet/ | Smart-money + wallet intel. || `irl/` | agent-card, agent-summary, drops, fix-token, interactions(+stream), pins, privacy, report, world-lines | IRL/AR layer. || `jobs/` | flush-usage-events | Usage-event flush. |diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ec3c7cb8f..5b2020d64 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,23 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-07-08++- **Blockchain TVL by Chain** (`/chains`) — A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.+- **Crypto Categories by Market Cap** (`/categories`) — Every crypto sector ranked by market cap — smart contract platforms, AI agents, memecoins, DeFi, gaming, and more — with 24h change, volume, and the top coins in each. See which narratives are leading the market right now.+- **Crypto Currency Converter** (`/converter`) — Convert between any cryptocurrency and major world fiat currencies at live market rates — crypto to crypto, crypto to fiat, and back. Type an amount, pick both sides, and share the result via URL.+- **Crypto Derivatives & Perpetual Futures** (`/derivatives`) — Live perpetual-futures markets across exchanges — price, 24h change, funding rate, open interest, and volume for every major contract. Filter by underlying index (BTC, ETH, SOL) and sort by any column.+- **Crypto Token Screener** (`/screener`) — Screen the top 250 cryptocurrencies with live filters — search by name or symbol, isolate gainers or losers, and set minimum market cap and 24h volume thresholds. Every column sorts and every row links to a full coin detail page.+- **DeFi TVL & Top Protocols** (`/defi`) — Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.+- **glTF / GLB Viewer** (`/viewer`) — Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.+- **Stablecoins Market Cap & Peg Health** (`/stablecoins`) — Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.+- **Top Crypto Exchanges** (`/exchanges`) — The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.+- **<agent-3d> talks out of the box with brain="free"** — Any embedded avatar can now hold a real conversation with zero setup: add brain="free" to an <agent-3d> tag and it routes through three.ws's host-paid free-tier proxy (OpenRouter, Groq, or NVIDIA NIM, whichever is healthy) — no API key, no backend code, no per-token cost to the embedder. Previously the brain attribute required an exact model id and defaulted to a silent avatar; brain="free" is now a supported alias, and it's honored on both the src= (bare GLB) and body= (ad-hoc agent) embed paths, which is where this fell through before. (`/docs/embedding`) `[feature, sdk]`+- **Markets goes deep — Screener, Categories, Exchanges, Derivatives, Converter, DeFi, Chains, Stablecoins** — Eight new tools join the Markets suite, all live data and all free. Screener filters the top 250 coins by market cap, volume, and 24h move. Categories ranks every crypto sector so you can see which narrative leads. Exchanges ranks venues by trust score and volume. Derivatives shows perpetual-futures funding, open interest, and volume. Converter turns any crypto into any major fiat at live rates. And a DeFi trio — DeFi TVL by protocol, Chains by total value locked, and Stablecoins with peg health — brings on-chain liquidity into view via DeFiLlama. Every one is cross-linked from the markets table. (`/screener`) `[feature]`+- **New shared DeFi utility library: one source of truth for chain and token constants across EVM and Solana** — Added @three-ws/defi-utils, a zero-dependency internal package with chain IDs, native-token symbols, common token addresses (including SPA and USDs on Arbitrum), and minimal ERC-20 ABI fragments for nine EVM chains, plus a Solana extension (SOL/USDC/$THREE mint resolution and base58 address validation). Also ships address and amount validators and USD/percent/token-amount formatters. It replaces ad hoc constant duplication across the codebase's API handlers and frontend modules going forward. `[sdk]`+- **Paid API endpoints now stay up through a cache-provider outage** — Hardened the pay-per-call x402 API surface — every /api/x402/* and /api/okx/3d/* endpoint — so it degrades gracefully instead of failing when the shared Redis cache is unreachable. Previously a missing cache configuration could take these paid endpoints offline; they now serve normally on a safe per-instance fallback, with on-chain payment safety unchanged (each payment authorization is still single-use, so no double-charge is possible). `[fix, infra]`+- **The three.ws crypto API now has a real free tier** — Any unauthenticated call to the unified /api/v1/x API (CoinGecko, DefiLlama, Jupiter Solana prices/quotes/search) now gets real data with zero setup, up to a per-endpoint quota — no wallet, no key, no signup. curl https://three.ws/api/v1/x/coingecko/price?ids=solana just works. Every response carries rate-limit headers so an agent can see exactly how much free budget is left; once it's used up, the same URL falls through to pay-per-call USDC (x402) or a three.ws API key instead of dead-ending. (`/docs/api-reference`) `[feature]`+## 2026-07-07- **3D API** (`/3d`) — Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 3eae7661a..78f83eea6 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -63,6 +63,7 @@ bottom.| Real-funds risk acknowledgment | gate [public/risk-ack.js](public/risk-ack.js) `→ /legal/risk`, app wrapper [src/shared/risk-ack.js](src/shared/risk-ack.js), record endpoint [api/legal/risk-ack.js](api/legal/risk-ack.js), disclosure [public/legal/risk.html](public/legal/risk.html) | In-repo | Versioned, once-per-browser acceptance dialog every money-committing surface awaits before executing (trade, snipe, withdraw, swap, launch, x402, onramp — devnet exempt). Acceptances persist in `audit_log` (`risk-ack-accept`). See [docs/risk-acknowledgment.md](docs/risk-acknowledgment.md) || Global markets + coin detail pages | [pages/coins.html](pages/coins.html) + [src/coins-index.js](src/coins-index.js) `→ /coins`, [pages/coin.html](pages/coin.html) + [src/coin-page.js](src/coin-page.js) `→ /coin/:id`, backend [api/coin/](api/coin) (detail, ohlc, markets, news, global over [api/_lib/coingecko.js](api/_lib/coingecko.js)) | In-repo | CoinGecko-style markets index (global stats bar, sortable top-coins table, search, sparklines) + a rich detail page per coin (interactive chart, stats grid, related news, links). Design adopted from cryptocurrency.cv; accepts CoinGecko slugs or Solana mints. Docs: [docs/coin-pages.md](docs/coin-pages.md) || Market tools (heatmap, sentiment, gas, compare) | [pages/heatmap.html](pages/heatmap.html) + [src/heatmap.js](src/heatmap.js) `→ /heatmap`, [pages/fear-greed.html](pages/fear-greed.html) + [src/fear-greed.js](src/fear-greed.js) `→ /fear-greed`, [pages/gas.html](pages/gas.html) + [src/gas.js](src/gas.js) `→ /gas`, [pages/compare.html](pages/compare.html) + [src/compare.js](src/compare.js) `→ /compare`; backend [api/coin/fear-greed.js](api/coin/fear-greed.js), [api/coin/gas.js](api/coin/gas.js) | In-repo | Four tools extending Markets, same design system: treemap heatmap (market-cap-sized tiles), Fear & Greed gauge + history, live Ethereum gas tracker (keyless `eth_feeHistory`), and up-to-4-coin compare (overlay perf + stats). All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |+| Market tools II (screener, categories, exchanges, derivatives, converter, DeFi, chains, stablecoins) | Pages+JS `→ /screener /categories /exchanges /derivatives /converter /defi /chains /stablecoins`; backend [api/coin/](api/coin) (categories, exchanges, derivatives, rates) over CoinGecko + [api/defi/](api/defi) (protocols, chains, stablecoins) over DeFiLlama | In-repo | Eight more Markets tools, same design system: token screener + category rankings + exchange/derivatives tables + crypto⇄fiat converter (CoinGecko), plus a DeFiLlama trio — DeFi TVL by protocol, chains by TVL, stablecoins with peg health. All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |## npm workspaces@@ -80,6 +81,7 @@ packages/avatar-schema/ → @three-ws/avatar-schemapackages/avatar-cli/ → @three-ws/avatar-clipackages/retarget/ → @three-ws/retarget (humanoid bone canonicalizer + clip retargeting engine, extracted from src/)packages/viewer-presets/ → @three-ws/viewer-presets+packages/defi-utils/ → @three-ws/defi-utils (zero-dependency chain/token constants + address/amount validation + formatters, EVM + Solana; ported from SperaxOS)packages/avatar-agent-mcp/ → @three-ws/avatar-agent-mcp (MCP server — avatar agent tools)packages/pumpfun-mcp/ → @three-ws/pumpfun-mcp (MCP server — pump.fun launch tools)packages/ibm-watsonx-mcp/ → @three-ws/ibm-watsonx-mcp (MCP server — IBM watsonx.ai)diff --git a/api/_lib/aggregator.js b/api/_lib/aggregator.jsindex d513fe53d..0910e01cc 100644--- a/api/_lib/aggregator.js+++ b/api/_lib/aggregator.js@@ -51,6 +51,15 @@ export async function executeUpstream({ provider, endpoint, query = {}, body, apconst path = typeof endpoint.path === 'function' ? endpoint.path(query) : endpoint.path;const url = new URL(provider.base + path);+ // `endpoint.method` is the caller-facing HTTP verb (what the aggregator front+ // door requires the request to use); `endpoint.upstreamMethod` — optional,+ // only set when they differ — is what we actually send upstream. This exists+ // for read-only JSON-RPC upstreams (e.g. Solana) that are POST-only on the+ // wire: the public surface stays a plain GET (agent-friendly, cacheable,+ // no body to construct), while the upstream call is a POST built from the+ // caller's query params. See the `solana` provider in api/v1/_providers.js.+ const upstreamMethod = endpoint.upstreamMethod || endpoint.method;+if (endpoint.method === 'GET' && endpoint.query) {for (const [k, v] of Object.entries(endpoint.query(query))) {if (v != null && v !== '') url.searchParams.set(k, String(v));@@ -59,8 +68,10 @@ export async function executeUpstream({ provider, endpoint, query = {}, body, apconst headers = { accept: 'application/json' };let outBody;- if (endpoint.method === 'POST') {- outBody = endpoint.body ? endpoint.body(body) : body;+ if (upstreamMethod === 'POST') {+ // A GET-caller/POST-upstream endpoint has no caller body to forward — its+ // `body()` builder consumes the caller's query params instead.+ outBody = endpoint.body ? endpoint.body(endpoint.method === 'GET' ? query : body) : body;headers['content-type'] = 'application/json';}provider.applyKey(headers, url, apiKey);@@ -70,7 +81,7 @@ export async function executeUpstream({ provider, endpoint, query = {}, body, aplet res;try {res = await fetch(url, {- method: endpoint.method,+ method: upstreamMethod,headers,body: outBody != null ? JSON.stringify(outBody) : undefined,signal: controller.signal,diff --git a/api/_lib/bnb/babt.js b/api/_lib/bnb/babt.jsnew file mode 100644index 000000000..0038b1973--- /dev/null+++ b/api/_lib/bnb/babt.js@@ -0,0 +1,125 @@+/**+ * BABT (Binance Account Bound Token) holder check — a free, KYC-backed+ * sybil-resistance signal unique to BSC.+ *+ * Verified real and third-party-queryable 2026-07-08 (see+ * `docs/bnb-babt-findings.md` for the full research writeup + live probes):+ * BABT is a soulbound BEP-721 extension minted by Binance to identity-verified+ * accounts, deployed and actively minting on BOTH BSC mainnet and testnet.+ * Checking "does address X hold a BABT" costs one free `eth_call` to+ * `balanceOf` on a verified, public contract — no API key, no Binance+ * relationship, no off-chain oracle.+ *+ * Contract addresses are copied verbatim from Binance's own developer docs+ * (developers.binance.com/docs/babt/apis-spec) and independently confirmed via+ * `eth_getCode` (both have deployed bytecode) and `name()` (both return+ * "Binance Account Bound Token"). Never invent or "guess-fix" these addresses.+ *+ * Limitation to respect everywhere this is surfaced (docs/UI copy included):+ * BABT proves the address is *currently* bound to some Binance-KYC'd account —+ * it is not a permanent identity anchor (Binance allows revoke + re-mint to a+ * new wallet, which changes `tokenIdOf`), and the real KYC'd holder base+ * (1.16M+) lives on mainnet — testnet mints are real but developer-only.+ */++import { getPublicClient, assertBscAddress, isEvmAddress, BnbRpcError } from './chains.js';++/** Verified BABT contract addresses (do not invent — see module docstring). */+export const BABT_CONTRACTS = {+ bscMainnet: '0x2B09d47D550061f995A3b5C6F0Fd58005215D7c8',+ bscTestnet: '0x984E6a7b9cb73cB7884c9ca9b1Ee625546F9D0E3',+};++const balanceOfAbi = [+ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'owner', type: 'address' }], outputs: [{ type: 'uint256' }] },+];+const tokenIdOfAbi = [+ { type: 'function', name: 'tokenIdOf', stateMutability: 'view', inputs: [{ name: 'from', type: 'address' }], outputs: [{ type: 'uint256' }] },+];++/** Typed error for a BABT contract read failure (RPC/contract unreachable). */+export class BabtCheckError extends Error {+ /** @param {string} message @param {{ network?: string, contract?: string, cause?: unknown }} [info] */+ constructor(message, info = {}) {+ super(message);+ this.name = 'BabtCheckError';+ this.network = info.network;+ this.contract = info.contract;+ if (info.cause) this.cause = info.cause;+ }+}++/** @returns {'bscMainnet'|'bscTestnet'} normalized network key; defaults to mainnet (real KYC'd holder base). */+function normalizeNetwork(network) {+ if (network === 97 || network === '97' || network === 'testnet' || network === 'bscTestnet') return 'bscTestnet';+ return 'bscMainnet';+}++/**+ * Check whether `address` holds a BABT (Binance Account Bound Token) — a+ * free, real, on-chain KYC-backed uniqueness signal on BSC.+ *+ * @param {string} address EVM address to check.+ * @param {'bscMainnet'|'bscTestnet'|56|97} [network] Defaults to mainnet, where+ * the real 1.16M+ KYC'd holder base lives. Pass `'bscTestnet'` to exercise+ * the integration without a mainnet read (testnet mints are real but are+ * developer test accounts, not KYC'd users).+ * @param {{ client?: import('viem').PublicClient, contract?: string }} [opts]+ * `client`/`contract` are injectable for tests; production code should omit+ * both and let this resolve the real public client + verified contract.+ * @returns {Promise<{ address:string, network:string, holdsBabt:boolean, tokenId:string|null, contract:string, checkedAt:string }>}+ * @throws {TypeError} if `address` is not a syntactically valid EVM address.+ * @throws {BabtCheckError} if the on-chain read fails (RPC/contract unreachable).+ */+export async function hasBabt(address, network = 'bscMainnet', opts = {}) {+ const addr = assertBscAddress(address);+ const key = normalizeNetwork(network);+ const contract = opts.contract || BABT_CONTRACTS[key];+ const client = opts.client || getPublicClient(key);++ let balance;+ try {+ balance = await client.readContract({+ address: contract,+ abi: balanceOfAbi,+ functionName: 'balanceOf',+ args: [addr],+ });+ } catch (err) {+ throw new BabtCheckError(`BABT balanceOf read failed: ${err.shortMessage || err.message}`, {+ network: key,+ contract,+ cause: err,+ });+ }++ const holdsBabt = BigInt(balance) > 0n;+ let tokenId = null;+ if (holdsBabt) {+ try {+ const tid = await client.readContract({+ address: contract,+ abi: tokenIdOfAbi,+ functionName: 'tokenIdOf',+ args: [addr],+ });+ tokenId = tid.toString();+ } catch {+ // tokenIdOf is a secondary detail (Binance's own docs warn against+ // treating it as a stable identity anchor) — a failure here must not+ // downgrade a confirmed balanceOf>0 holder into a false negative.+ tokenId = null;+ }+ }++ return {+ address: addr,+ network: key,+ holdsBabt,+ tokenId,+ contract,+ checkedAt: new Date().toISOString(),+ };+}++export { isEvmAddress, BnbRpcError };diff --git a/api/_lib/bnb/mpp-buyer.js b/api/_lib/bnb/mpp-buyer.jsnew file mode 100644index 000000000..913507f55--- /dev/null+++ b/api/_lib/bnb/mpp-buyer.js@@ -0,0 +1,172 @@+/**+ * MPP (BNB Machine Payments Protocol / b402) buyer client — lets our agents PAY+ * any MPP-protected endpoint in the BNB ecosystem, the mirror of `mpp-server.js`+ * and the sibling of `api/_lib/x402-buyer-fetch.js` (whose return shape it+ * matches: `{ ok, result, response, ... }`).+ *+ * b402 is x402 v2, so the 402 → sign EIP-3009 → retry-with-`X-PAYMENT` dance is+ * the same one our Base x402 buyer runs — this module just targets BNB networks+ * (`eip155:56` / `eip155:97`) and signs with `@bnb-chain/mpp`'s+ * `buildEip3009Payment`. A HARD `maxSpend` cap is enforced BEFORE any signature:+ * an endpoint quoting above the cap is refused with zero payment attempted.+ *+ * The caller injects the signing account; no private key is read here.+ *+ * @example+ * import { mppFetch } from '../_lib/bnb/mpp-buyer.js';+ * import { privateKeyToAccount } from 'viem/accounts';+ * const account = privateKeyToAccount(process.env.BNB_TESTNET_DEPLOYER_KEY);+ * const res = await mppFetch('https://three.ws/api/x402/three-intel', { method: 'GET' }, {+ * account, maxSpend: '20000', network: 'eip155:97',+ * });+ * if (res.ok) console.log(res.result, res.settlement);+ */++import { buildEip3009Payment, encodeXPayment, decodeXPaymentResponse } from '@bnb-chain/mpp/b402';++/** CAIP-2 networks this buyer will pay on. */+export const MPP_BUYER_NETWORKS = ['eip155:56', 'eip155:97'];++/** Thrown only for programmer errors (missing account). Payment DECISIONS return objects. */+export class MppBuyerError extends Error {+ constructor(message, code = 'mpp_buyer_error') {+ super(message);+ this.name = 'MppBuyerError';+ this.code = code;+ }+}++function b64decode(s) {+ if (!s) return null;+ try {+ return JSON.parse(Buffer.from(s, 'base64').toString('utf8'));+ } catch {+ return null;+ }+}++function safeJson(text) {+ try {+ return JSON.parse(text);+ } catch {+ return null;+ }+}++function bodyToInit(method, body, headers = {}) {+ if (body == null) return { method, headers };+ if (typeof body === 'string' || body instanceof ArrayBuffer || body instanceof Uint8Array) {+ return { method, headers, body };+ }+ return { method, headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body) };+}++/** Pick a payable BNB eip3009 `exact` requirement from the 402 menu. */+function selectRequirement(accepts, network) {+ const payable = accepts.filter(+ (a) =>+ a &&+ a.scheme === 'exact' &&+ MPP_BUYER_NETWORKS.includes(a.network) &&+ (a.extra?.assetTransferMethod ? a.extra.assetTransferMethod === 'eip3009' : true),+ );+ if (network) return payable.find((a) => a.network === network) || null;+ return payable[0] || null;+}++/**+ * Pay an MPP-protected endpoint. Handles the 402 → pay → retry loop with a hard+ * spend cap and bounded retries.+ *+ * @param {string} url+ * @param {{ method?:string, body?:any, headers?:object, fetchImpl?:Function }} [opts]+ * @param {{ account: import('viem').LocalAccount, maxSpend: string|bigint, network?:string, fetchImpl?:Function }} pay+ * @returns {Promise<+ * { ok:true, result:any, response:Response, requirement:object, payment:object, settlement:object|undefined } |+ * { ok:false, abort:true, code:string, reason:string } |+ * { ok:false, status:number, error:string }+ * >}+ */+export async function mppFetch(url, opts = {}, pay = {}) {+ const { account, maxSpend, network } = pay;+ const fetchImpl = pay.fetchImpl || opts.fetchImpl || globalThis.fetch;+ if (!account || typeof account.signTypedData !== 'function') {+ throw new MppBuyerError('mppFetch requires a viem account (LocalAccount) in the third argument', 'bad_account');+ }+ if (maxSpend == null) {+ throw new MppBuyerError('mppFetch requires a maxSpend cap (atomic units) — refusing to pay uncapped', 'no_cap');+ }+ const cap = BigInt(maxSpend);++ const init = bodyToInit(opts.method || 'GET', opts.body, opts.headers);+ const probe = await fetchImpl(url, init);+ if (probe.status !== 402) {+ const text = await probe.text();+ return { ok: probe.ok, status: probe.status, result: safeJson(text) ?? text, response: probe };+ }++ // Parse the 402 challenge (JSON body, or the PAYMENT-REQUIRED header).+ const challenge =+ safeJson(await probe.clone().text()) || b64decode(probe.headers.get('payment-required'));+ if (!challenge || !Array.isArray(challenge.accepts)) {+ return { ok: false, status: 402, error: 'invalid_402_body' };+ }++ const requirement = selectRequirement(challenge.accepts, network);+ if (!requirement) {+ // Either no BNB network offered, or only unsupported credential types.+ const hasBnb = challenge.accepts.some((a) => MPP_BUYER_NETWORKS.includes(a?.network));+ return {+ ok: false,+ abort: true,+ code: hasBnb ? 'unsupported_credential' : 'no_bnb_requirement',+ reason: hasBnb+ ? 'endpoint offers a BNB network but only via an unsupported credential (this client signs eip3009 only)'+ : 'endpoint does not offer a BNB (eip155:56/97) payment option',+ };+ }++ // HARD cap — refuse before signing anything.+ const price = BigInt(requirement.amount);+ if (price > cap) {+ return {+ ok: false,+ abort: true,+ code: 'over_budget',+ reason: `quote ${price} exceeds maxSpend ${cap} (atomic units) — no payment sent`,+ };+ }++ // Sign the EIP-3009 credential and attach it.+ let payment;+ try {+ payment = await buildEip3009Payment({ account, requirements: requirement, resourceUrl: url });+ } catch (e) {+ return { ok: false, abort: true, code: 'sign_failed', reason: `could not sign credential: ${e.message}` };+ }+ const header = encodeXPayment(payment);++ const paidInit = bodyToInit(opts.method || 'GET', opts.body, { ...opts.headers, 'X-PAYMENT': header });+ const paidRes = await fetchImpl(url, paidInit);++ if (paidRes.status === 402) {+ // Server still says unpaid — do NOT retry-forever; surface it.+ const text = await paidRes.text();+ return { ok: false, status: 402, error: safeJson(text)?.error || 'payment_rejected', response: paidRes };+ }+ if (!paidRes.ok) {+ const text = await paidRes.text();+ return { ok: false, status: paidRes.status, error: safeJson(text)?.error || `http_${paidRes.status}`, response: paidRes };+ }++ const text = await paidRes.text();+ const settlement = decodeXPaymentResponse(paidRes.headers.get('x-payment-response'));+ return {+ ok: true,+ result: safeJson(text) ?? text,+ response: paidRes,+ requirement,+ payment,+ settlement,+ };+}diff --git a/api/_lib/bnb/mpp-server.js b/api/_lib/bnb/mpp-server.jsnew file mode 100644index 000000000..f0d399a9a--- /dev/null+++ b/api/_lib/bnb/mpp-server.js@@ -0,0 +1,311 @@+/**+ * MPP (BNB Machine Payments Protocol) server adapter — accept BNB-ecosystem+ * payments on a paid endpoint, ADDITIVELY alongside our existing x402 stack.+ *+ * `@bnb-chain/mpp`'s b402 layer IS x402 v2 (CDP wire-shape compatible): the same+ * `X-PAYMENT` / `X-PAYMENT-RESPONSE` headers and EIP-3009 credential our Base+ * x402 path already uses. So "speaking MPP" here means advertising an extra+ * `accepts[]` entry for BNB Chain (`eip155:56`/`97`) and, when a buyer pays on a+ * BNB network, settling through the Binance OnchainPay (b402) facilitator+ * instead of our Solana/Base facilitator. The Solana/Base x402 path is untouched.+ *+ * Settlement uses the real b402 facilitator via `B402Client` (RSA "Tesla"+ * signed, `B402_*` env). WITHOUT those merchant credentials the adapter still+ * verifies credentials off-chain (recover payer, shape-gate, pin requirements,+ * replay-guard) and reports `mpp_not_configured` for the on-chain settle — it+ * never fabricates a receipt. See docs/bnb-payments.md + specs/x402-mpp-bridge.md.+ */++import {+ B402Client,+ decodeXPayment,+ isEip3009PaymentPayload,+ recoverEip3009Payer,+ encodeXPaymentResponse,+ chainIdFromNetwork,+} from '@bnb-chain/mpp/b402/server';+import { getRedis } from '../redis.js';++/** CAIP-2 networks this adapter accepts (BNB Chain only; Solana/Base stay on x402). */+export const MPP_NETWORKS = { bscMainnet: 'eip155:56', bscTestnet: 'eip155:97' };++/** Typed error for MPP verify/settle failures with a machine-readable `code`. */+export class MppError extends Error {+ constructor(message, code = 'mpp_error', status = 400) {+ super(message);+ this.name = 'MppError';+ this.code = code;+ this.status = status;+ }+}++/** Read-through env helper (kept local so this module has no env.js coupling). */+function cfg(name, fallback) {+ const v = process.env[name];+ return v == null || v === '' ? fallback : v;+}++/**+ * Whether the MPP path is enabled for outgoing challenges. It is advertised+ * whenever a BSC payout address is configured; on-chain settlement additionally+ * needs `B402_*` merchant credentials (checked at settle time).+ */+export function mppEnabled() {+ return !!cfg('X402_PAY_TO_BSC', cfg('MPP_PAY_TO_BSC'));+}++/**+ * Build the MPP `accepts[]` entry (an x402-v2 `PaymentRequirements`) advertising+ * that this route is payable on BNB Chain. Defaults to BSC testnet (00-CONTEXT:+ * writes default to testnet). The `extra` fields (token EIP-712 `name`,+ * facilitator `signerAddress`) come from the b402 `/supported` menu when a+ * client is provided; otherwise from env, so the challenge is honest about what+ * it can accept.+ *+ * @param {{ route:string, priceAtomics:string|number, network?:string, description?:string, supported?:object }} routeMeta+ * @returns {Promise<import('@bnb-chain/mpp/b402').PaymentRequirements>}+ */+export async function mppRequirements(routeMeta) {+ const network = routeMeta.network || cfg('MPP_NETWORK', MPP_NETWORKS.bscTestnet);+ const payTo = cfg('X402_PAY_TO_BSC', cfg('MPP_PAY_TO_BSC'));+ if (!payTo) throw new MppError('X402_PAY_TO_BSC is not configured', 'mpp_no_payto', 500);++ // Prefer the live /supported kind (correct token domain name + signer).+ let asset = cfg('MPP_ASSET_ADDRESS_BSC');+ let name = cfg('MPP_ASSET_NAME');+ let signerAddress = cfg('MPP_FACILITATOR_SIGNER', '0x0000000000000000000000000000000000000000');+ const kinds = routeMeta.supported?.kinds;+ if (Array.isArray(kinds)) {+ const kind = kinds.find(+ (k) => k.network === network && k?.extra?.assetTransferMethod === 'eip3009',+ );+ if (kind) {+ asset = kind.asset || asset;+ name = kind.extra?.name || name;+ signerAddress = kind.extra?.signerAddress || signerAddress;+ }+ }+ if (!asset) throw new MppError('no eip3009 asset configured for MPP (set MPP_ASSET_ADDRESS_BSC or pass /supported)', 'mpp_no_asset', 500);++ return {+ scheme: 'exact',+ network,+ amount: String(routeMeta.priceAtomics),+ asset,+ payTo,+ maxTimeoutSeconds: Number(cfg('MPP_MAX_TIMEOUT_SECONDS', '300')),+ extra: { name: name || 'USD', version: cfg('MPP_ASSET_VERSION', '1'), assetTransferMethod: 'eip3009', signerAddress },+ };+}++/**+ * Full 402 challenge body advertising MPP payability for a route. Shaped like an+ * x402-v2 `PaymentRequiredBody` so any x402/b402 client understands it.+ */+export async function mppChallenge(routeMeta) {+ const requirements = await mppRequirements(routeMeta);+ return {+ x402Version: 2,+ error: 'payment required',+ accepts: [requirements],+ resource: { url: routeMeta.route, description: routeMeta.description },+ };+}++/** True when the decoded X-PAYMENT targets a BNB network this adapter owns. */+export function isMppPayment(paymentPayload) {+ const net = paymentPayload?.accepted?.network;+ return net === MPP_NETWORKS.bscMainnet || net === MPP_NETWORKS.bscTestnet;+}++/**+ * Cheap, non-throwing check: does this request carry an X-PAYMENT that decodes+ * to a BNB-network payment? Lets a dual-protocol endpoint route BNB payments to+ * the MPP path and leave every Solana/Base x402 payment to the existing stack.+ * Returns false for a missing/undecodable/non-BNB header — never throws.+ */+export function looksLikeMppPayment(req) {+ const header = getHeader(req, 'x-payment');+ if (!header) return false;+ try {+ return isMppPayment(decodeXPayment(header));+ } catch {+ return false;+ }+}++// ── replay guard ───────────────────────────────────────────────────────────+// A single-use lock on the EIP-3009 nonce (per network+asset), so a captured+// credential can't be settled twice. Backed by Redis (SET NX PX); falls back to+// a process-local map when Redis is unavailable (dev/tests) — the on-chain+// nonce is itself single-use, so this is defence-in-depth, not the sole guard.+const localReplay = new Map();+const REPLAY_TTL_MS = 15 * 60 * 1000;++async function reserveNonce(key) {+ const redis = getRedis();+ if (redis) {+ try {+ const ok = await redis.set(key, '1', { nx: true, px: REPLAY_TTL_MS });+ return ok === 'OK' || ok === true;+ } catch {+ /* fall through to local */+ }+ }+ const now = Date.now();+ const prev = localReplay.get(key);+ if (prev && prev > now) return false;+ localReplay.set(key, now + REPLAY_TTL_MS);+ return true;+}++/**+ * Verify an incoming MPP (b402) payment OFF-CHAIN (free, no gas): decode,+ * shape-gate, pin to our requirements, recover the payer, replay-guard the+ * nonce, and — when a facilitator client is configured — run the b402 `/verify`+ * signature check. Does NOT settle. The caller runs its business logic AFTER a+ * successful verify and BEFORE {@link mppSettle}, so a failed request never+ * moves funds (mirrors the x402 verify→work→settle order).+ *+ * Never throws for a normal "no/invalid payment" — returns a typed result.+ *+ * @param {{ headers: Record<string,string|undefined> | Headers }} req+ * @param {import('@bnb-chain/mpp/b402').PaymentRequirements} requirements OUR pinned requirements+ * @param {{ client?: import('@bnb-chain/mpp/b402/server').B402Client, skipReplay?: boolean }} [opts]+ * @returns {Promise<+ * { ok:true, payload:object, payer:string, client:object|null, settleable:boolean } |+ * { ok:false, code:string, status:number, reason:string }+ * >}+ */+export async function mppVerify(req, requirements, opts = {}) {+ const header = getHeader(req, 'x-payment');+ if (!header) return fail('no_payment', 402, 'missing X-PAYMENT header');++ let payload;+ try {+ payload = decodeXPayment(header);+ } catch (e) {+ return fail('bad_payment', 400, `undecodable X-PAYMENT: ${e.message}`);+ }++ // Shape-gate attacker-controlled input BEFORE reading nested fields.+ if (!isEip3009PaymentPayload(payload)) {+ return fail('unsupported_credential', 400, 'only exact/eip3009 payloads are accepted on the MPP path');+ }+ if (!isMppPayment(payload)) {+ return fail('wrong_network', 400, `payment network ${payload?.accepted?.network} is not a BNB network`);+ }++ // Pin every buyer-echoed field to OUR requirements — reject a self-consistent+ // payload that names a different recipient/asset/amount/network locally.+ const a = payload.accepted;+ const mismatch = pin(a, requirements);+ if (mismatch) return fail('offer_mismatch', 400, `payment ${mismatch} does not match this resource`);++ // Recover the payer from the signature and confirm it matches authorization.from.+ let payer;+ try {+ payer = await recoverEip3009Payer(payload);+ } catch (e) {+ return fail('bad_signature', 400, `signature recovery failed: ${e.message}`);+ }+ const from = payload.payload?.authorization?.from;+ if (!from || payer.toLowerCase() !== from.toLowerCase()) {+ return fail('bad_signature', 400, 'recovered signer does not match authorization.from');+ }++ // Replay guard on the nonce.+ if (!opts.skipReplay) {+ const nonce = payload.payload.authorization.nonce;+ const key = `mpp:nonce:${a.network}:${a.asset}:${nonce}`.toLowerCase();+ const fresh = await reserveNonce(key);+ if (!fresh) return fail('replay', 409, 'this payment credential was already used');+ }++ const client = opts.client || B402Client.fromEnv();+ if (client) {+ try {+ const verify = await client.verify({ x402Version: 2, paymentPayload: payload, paymentRequirements: requirements });+ if (verify && verify.isValid === false) {+ return fail('verify_failed', 402, verify.invalidReason || 'facilitator rejected the credential');+ }+ } catch (e) {+ return fail('facilitator_unreachable', 502, `b402 /verify error: ${e.message}`);+ }+ }++ return { ok: true, payload, payer, client: client || null, settleable: !!client };+}++/**+ * Settle a verified MPP payment ON-CHAIN via the b402 facilitator. Call ONLY+ * after {@link mppVerify} succeeded and the resource's work is done. Without+ * merchant credentials this returns `mpp_not_configured` (503) — it never+ * fabricates a receipt.+ *+ * @param {object} payload the verified PaymentPayload from mppVerify+ * @param {import('@bnb-chain/mpp/b402').PaymentRequirements} requirements+ * @param {{ client?: object|null }} [opts]+ * @returns {Promise<{ ok:true, settlement:object, paymentResponseHeader:string } | { ok:false, code:string, status:number, reason:string }>}+ */+export async function mppSettle(payload, requirements, opts = {}) {+ const client = opts.client || B402Client.fromEnv();+ if (!client) {+ return fail(+ 'mpp_not_configured',+ 503,+ 'MPP credential verified but on-chain settlement is unconfigured — set B402_BASE_URL / B402_CLIENT_ID / B402_ACCESS_TOKEN / B402_PRIVATE_KEY',+ );+ }+ try {+ const settlement = await client.settle({ x402Version: 2, paymentPayload: payload, paymentRequirements: requirements });+ if (settlement && settlement.success === false) {+ return fail('settle_failed', 402, settlement.errorReason || 'facilitator settlement failed');+ }+ return { ok: true, settlement, paymentResponseHeader: encodeXPaymentResponse(settlement) };+ } catch (e) {+ // A settle-phase transport error means UNKNOWN state — surface 502 so the+ // caller reconciles on-chain rather than assuming unpaid.+ return fail('facilitator_unreachable', 502, `b402 /settle error: ${e.message}`);+ }+}++/**+ * Convenience: verify + settle in one call (no business logic between). Handy+ * for tests and fire-and-forget callers; HTTP endpoints should instead+ * verify → do work → settle so a failed request never charges.+ */+export async function mppVerifyAndSettle(req, requirements, opts = {}) {+ const verified = await mppVerify(req, requirements, opts);+ if (!verified.ok) return verified;+ const settled = await mppSettle(verified.payload, requirements, { client: verified.client });+ if (!settled.ok) return settled;+ return { ok: true, settlement: settled.settlement, payer: verified.payer, paymentResponseHeader: settled.paymentResponseHeader };+}++/** Compare a buyer-echoed offer against our requirements; return the first mismatched field name or null. */+function pin(offer, req) {+ if (offer.network !== req.network) return 'network';+ if (offer.asset?.toLowerCase() !== req.asset?.toLowerCase()) return 'asset';+ if (offer.payTo?.toLowerCase() !== req.payTo?.toLowerCase()) return 'payTo';+ if (String(offer.amount) !== String(req.amount)) return 'amount';+ if (offer.scheme !== req.scheme) return 'scheme';+ // chainId sanity: network must decode to a real EIP-155 id.+ try {+ chainIdFromNetwork(offer.network);+ } catch {+ return 'network';+ }+ return null;+}++function getHeader(req, name) {+ const h = req?.headers;+ if (!h) return undefined;+ if (typeof h.get === 'function') return h.get(name) || undefined;+ return h[name] ?? h[name.toLowerCase()] ?? undefined;+}++function fail(code, status, reason) {+ return { ok: false, code, status, reason };+}diff --git a/api/_lib/bnb/vault-crypto.js b/api/_lib/bnb/vault-crypto.jsnew file mode 100644index 000000000..aed5babe8--- /dev/null+++ b/api/_lib/bnb/vault-crypto.js@@ -0,0 +1,247 @@+/**+ * Vault content-encryption + key-wrapping primitives for the BNB vault track+ * (prompts 08-11). Encrypts a GLB once with a random per-object AES-256-GCM+ * content key, then wraps that content key to a specific buyer's secp256k1+ * public key (an EVM address's key) so the bytes can sit on a public-ish+ * Storage Provider while only an authorized, paying buyer can ever recover+ * the plaintext. Wire format: `specs/vault-manifest.md`.+ *+ * CLAUDE.md: never hand-roll crypto primitives. Every primitive here comes+ * from an audited library — Node's built-in `crypto` (AES-256-GCM, the same+ * FIPS-validated OpenSSL implementation Node ships) and `@noble/curves` /+ * `@noble/hashes` (already a pinned workspace dependency — see package.json)+ * for secp256k1 ECDH and HKDF-SHA256. The only original code here is the+ * ECIES *composition* (ECDH -> HKDF -> AES-256-GCM), which is unavoidable —+ * composing a key-wrap scheme from primitives is exactly what a library like+ * `eciesjs` also does, and `eciesjs` itself depends on `@noble/curves` ++ * `@noble/hashes`. Since both are already installed and pinned in this repo,+ * building directly on them (rather than adding `eciesjs` as a redundant+ * second dependency graph on top of the same primitives) is the open-source+ * -first, dependency-minimal choice per CLAUDE.md ("check existing workspace+ * dependencies first ... never add a dependency that duplicates one already+ * present"). This is the well-known ECIES construction used by Ethereum+ * tooling (e.g. `eth-crypto`, `eciesjs`): ephemeral-key ECDH over secp256k1,+ * HKDF-SHA256 to derive a symmetric key, AES-256-GCM to encrypt the payload.+ */++import { randomBytes, createCipheriv, createDecipheriv, createHash } from 'node:crypto';+import { secp256k1 } from '@noble/curves/secp256k1.js';+import { hkdf } from '@noble/hashes/hkdf.js';+import { sha256 } from '@noble/hashes/sha2.js';++const AES_ALG = 'aes-256-gcm';+const AES_KEY_LEN = 32; // AES-256+const GCM_IV_LEN = 12; // 96-bit nonce, NIST SP 800-38D recommended size+const GCM_TAG_LEN = 16;+const ECDH_SECRET_LEN = 32; // secp256k1 shared x-coordinate++/** HKDF `info` context string — versioned so a future v2 scheme can't collide. */+const ECIES_HKDF_INFO = 'three.ws/bnb-vault/ecies/v1';++/**+ * Typed error for every vault-crypto failure. `code` disambiguates the stage+ * so callers (upload/unlock APIs) can map to the right HTTP status without+ * string-matching messages.+ */+export class VaultCryptoError extends Error {+ /** @param {string} message @param {{ code?: string, cause?: unknown }} [info] */+ constructor(message, info = {}) {+ super(message);+ this.name = 'VaultCryptoError';+ this.code = info.code || 'vault_crypto_error';+ if (info.cause) this.cause = info.cause;+ }+}++/** Coerce a Buffer/Uint8Array/hex-string (with or without `0x`) into a Uint8Array. */+function toBytes(input, label) {+ if (input instanceof Uint8Array) return input;+ if (typeof input === 'string') {+ const hex = input.startsWith('0x') ? input.slice(2) : input;+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) {+ throw new VaultCryptoError(`${label} must be a Buffer/Uint8Array or hex string`, { code: 'bad_input' });+ }+ return Uint8Array.from(Buffer.from(hex, 'hex'));+ }+ throw new VaultCryptoError(`${label} must be a Buffer/Uint8Array or hex string`, { code: 'bad_input' });+}++function assertLen(bytes, len, label) {+ if (bytes.length !== len) {+ throw new VaultCryptoError(`${label} must be ${len} bytes, got ${bytes.length}`, { code: 'bad_length' });+ }+ return bytes;+}++/**+ * Normalize any valid secp256k1 public key encoding (33-byte compressed,+ * 65-byte uncompressed, hex string, `0x`-prefixed) to canonical 33-byte+ * compressed form via curve point validation — rejects off-curve/garbage+ * input before it ever reaches ECDH.+ */+function normalizePublicKey(pubKey) {+ const bytes = toBytes(pubKey, 'recipientPubKey');+ try {+ return secp256k1.Point.fromBytes(bytes).toBytes(true);+ } catch (err) {+ throw new VaultCryptoError('recipientPubKey is not a valid secp256k1 point', { code: 'bad_public_key', cause: err });+ }+}++/** Derive the AES-256-GCM key-encryption-key from an ECDH shared secret via HKDF-SHA256. */+function deriveWrapKey(sharedSecretX) {+ return hkdf(sha256, sharedSecretX, undefined, ECIES_HKDF_INFO, AES_KEY_LEN);+}++/**+ * Encrypt a GLB's raw bytes with a fresh random AES-256-GCM content key.+ * @param {Uint8Array} glbBytes+ * @returns {{ ciphertext: Buffer, contentKey: Buffer, iv: Buffer, authTag: Buffer, sha256OfPlaintext: string }}+ */+export function encryptGlb(glbBytes) {+ const plaintext = toBytes(glbBytes, 'glbBytes');+ if (plaintext.length === 0) {+ throw new VaultCryptoError('glbBytes must not be empty', { code: 'bad_input' });+ }+ const contentKey = randomBytes(AES_KEY_LEN);+ const iv = randomBytes(GCM_IV_LEN);+ const cipher = createCipheriv(AES_ALG, contentKey, iv);+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);+ const authTag = cipher.getAuthTag();+ const sha256OfPlaintext = createHash('sha256').update(plaintext).digest('hex');+ return { ciphertext, contentKey, iv, authTag, sha256OfPlaintext };+}++/**+ * Decrypt a GLB envelope. Verifies the GCM auth tag (tampered ciphertext or+ * wrong key throws a typed `VaultCryptoError{code:'auth_failed'}`, never+ * silent garbage) and the plaintext sha256 if `expectedSha256` is given.+ * @param {{ ciphertext: Uint8Array, contentKey: Uint8Array, iv: Uint8Array, authTag: Uint8Array }} envelope+ * @param {{ expectedSha256?: string }} [opts]+ * @returns {Buffer} the original glbBytes+ */+export function decryptGlb({ ciphertext, contentKey, iv, authTag }, opts = {}) {+ const key = assertLen(toBytes(contentKey, 'contentKey'), AES_KEY_LEN, 'contentKey');+ const nonce = assertLen(toBytes(iv, 'iv'), GCM_IV_LEN, 'iv');+ const tag = assertLen(toBytes(authTag, 'authTag'), GCM_TAG_LEN, 'authTag');+ const ct = toBytes(ciphertext, 'ciphertext');++ const decipher = createDecipheriv(AES_ALG, key, nonce);+ decipher.setAuthTag(tag);+ let plaintext;+ try {+ plaintext = Buffer.concat([decipher.update(ct), decipher.final()]);+ } catch (err) {+ throw new VaultCryptoError('GCM authentication failed — ciphertext or key tampered/incorrect', {+ code: 'auth_failed',+ cause: err,+ });+ }++ if (opts.expectedSha256) {+ const actual = createHash('sha256').update(plaintext).digest('hex');+ if (actual !== opts.expectedSha256) {+ throw new VaultCryptoError('Decrypted plaintext sha256 does not match expected value', {+ code: 'sha256_mismatch',+ });+ }+ }+ return plaintext;+}++/**+ * Wrap a 32-byte content key to a recipient's secp256k1 public key (ECIES):+ * generate an ephemeral keypair, ECDH with the recipient's public key,+ * HKDF-SHA256 the shared x-coordinate into an AES-256-GCM key, encrypt the+ * content key under it. Only the holder of the matching private key can+ * `unwrapKey` — the content key is never exposed publicly.+ * @param {Uint8Array} contentKey 32-byte AES key from `encryptGlb`.+ * @param {Uint8Array|string} recipientPubKey secp256k1 public key (compressed/uncompressed/hex).+ * @returns {{ ephemeralPublicKey: Buffer, iv: Buffer, authTag: Buffer, ciphertext: Buffer }}+ */+export function wrapKey(contentKey, recipientPubKey) {+ const key = assertLen(toBytes(contentKey, 'contentKey'), AES_KEY_LEN, 'contentKey');+ const recipientPub = normalizePublicKey(recipientPubKey);++ const ephemeral = secp256k1.keygen();+ const shared = secp256k1.getSharedSecret(ephemeral.secretKey, recipientPub, true);+ const sharedX = shared.subarray(1, 1 + ECDH_SECRET_LEN); // drop the 0x02/0x03 parity prefix+ const wrapKeyBytes = deriveWrapKey(sharedX);++ const iv = randomBytes(GCM_IV_LEN);+ const cipher = createCipheriv(AES_ALG, Buffer.from(wrapKeyBytes), iv);+ const ciphertext = Buffer.concat([cipher.update(Buffer.from(key)), cipher.final()]);+ const authTag = cipher.getAuthTag();++ return {+ ephemeralPublicKey: Buffer.from(ephemeral.publicKey), // compressed, 33 bytes+ iv,+ authTag,+ ciphertext,+ };+}++/**+ * Unwrap a content key previously wrapped by `wrapKey`, using the+ * recipient's secp256k1 private key. Wrong private key derives a different+ * shared secret and therefore a different AES key — GCM auth tag check+ * fails and this throws `VaultCryptoError{code:'auth_failed'}`, never+ * silently returning garbage bytes.+ * @param {{ ephemeralPublicKey: Uint8Array, iv: Uint8Array, authTag: Uint8Array, ciphertext: Uint8Array }} wrapped+ * @param {Uint8Array|string} recipientPrivKey 32-byte secp256k1 private key (hex or bytes).+ * @returns {Buffer} the original 32-byte content key+ */+export function unwrapKey(wrapped, recipientPrivKey) {+ const privKey = assertLen(toBytes(recipientPrivKey, 'recipientPrivKey'), AES_KEY_LEN, 'recipientPrivKey');+ const ephemeralPub = toBytes(wrapped.ephemeralPublicKey, 'ephemeralPublicKey');+ const iv = assertLen(toBytes(wrapped.iv, 'iv'), GCM_IV_LEN, 'iv');+ const authTag = assertLen(toBytes(wrapped.authTag, 'authTag'), GCM_TAG_LEN, 'authTag');+ const ciphertext = toBytes(wrapped.ciphertext, 'ciphertext');++ let shared;+ try {+ shared = secp256k1.getSharedSecret(privKey, ephemeralPub, true);+ } catch (err) {+ throw new VaultCryptoError('Invalid recipient private key or ephemeral public key', {+ code: 'bad_ecdh_input',+ cause: err,+ });+ }+ const sharedX = shared.subarray(1, 1 + ECDH_SECRET_LEN);+ const wrapKeyBytes = deriveWrapKey(sharedX);++ const decipher = createDecipheriv(AES_ALG, Buffer.from(wrapKeyBytes), Buffer.from(iv));+ decipher.setAuthTag(Buffer.from(authTag));+ try {+ return Buffer.concat([decipher.update(Buffer.from(ciphertext)), decipher.final()]);+ } catch (err) {+ throw new VaultCryptoError('Key-unwrap authentication failed — wrong recipient key or tampered wrapped key', {+ code: 'auth_failed',+ cause: err,+ });+ }+}++/**+ * Convenience: derive a secp256k1 keypair (compressed public key) suitable+ * for `wrapKey`/`unwrapKey` recipient testing and manifest examples. Not+ * used for BSC transaction signing — that stays in `chains.js`/callers'+ * own viem accounts; this is purely for the vault key-wrap layer.+ * @returns {{ privateKey: Buffer, publicKey: Buffer }}+ */+export function generateVaultKeypair() {+ const kp = secp256k1.keygen();+ return { privateKey: Buffer.from(kp.secretKey), publicKey: Buffer.from(kp.publicKey) };+}++export const VAULT_CRYPTO_PARAMS = Object.freeze({+ alg: 'AES-256-GCM',+ keyLenBytes: AES_KEY_LEN,+ ivLenBytes: GCM_IV_LEN,+ authTagLenBytes: GCM_TAG_LEN,+ ecies: {+ curve: 'secp256k1',+ kdf: 'HKDF-SHA256',+ info: ECIES_HKDF_INFO,+ },+});diff --git a/api/_lib/forge-job-options.js b/api/_lib/forge-job-options.jsnew file mode 100644index 000000000..ea7aa95b4--- /dev/null+++ b/api/_lib/forge-job-options.js@@ -0,0 +1,58 @@+// Job → output-options binding for the /forge generation pipeline.+//+// normalizeForgeOptions() (forge-options.js) parses a request's optional output+// controls (seed, output_format/compression, texture_size, target_polycount) in+// the SAME serverless invocation that submits the job. An asynchronous lane+// (Replicate/TRELLIS, Hunyuan3D, sketch, BYOK) completes in a LATER, separate+// invocation of pollJob(), which only has the job handle — not the original+// request body. This module remembers the request-affecting subset (today,+// just the post-generation compression choice) against the job handle for the+// lifetime of a single poll cycle, so a completed async job still gets the+// caller's requested output_format applied at materialize time.+//+// Mirrors the bindJobToCacheKey/cacheKeyForJob idiom in forge-cache.js exactly:+// best-effort, short-TTL, fail-open without Redis (a cache/store outage just+// means the completed GLB is delivered uncompressed — never a broken response).++import { getRedis } from './redis.js';++const PREFIX = 'fr:jobopt:';+// The binding only needs to outlive one generation's polling window.+const TTL_S = 3600;++function client(override) {+ return override || getRedis();+}++/**+ * Remember the compression choice a just-submitted job should apply at+ * completion. No-op (and safe to call unconditionally) when there is nothing+ * non-default to remember, or when Redis is unavailable.+ */+export async function bindJobToOptions(jobHandle, opts, { redis } = {}) {+ const r = client(redis);+ if (!r || !jobHandle || !opts) return;+ if (opts.compression === 'none') return; // default behavior needs no binding+ try {+ await r.set(`${PREFIX}${jobHandle}`, JSON.stringify({ compression: opts.compression }), { ex: TTL_S });+ } catch {+ /* best-effort */+ }+}++/**+ * Resolve the compression choice bound to a job handle, or null when none was+ * bound (the common case — no options requested, or Redis unavailable).+ */+export async function optionsForJob(jobHandle, { redis } = {}) {+ const r = client(redis);+ if (!r || !jobHandle) return null;+ try {+ const raw = await r.get(`${PREFIX}${jobHandle}`);+ if (!raw) return null;+ const value = typeof raw === 'string' ? JSON.parse(raw) : raw;+ return value && typeof value.compression === 'string' ? value : null;+ } catch {+ return null;+ }+}diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex fbf4271ac..ecfcbc21a 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -19,6 +19,8 @@ import { sql, isDbUnavailableError } from './db.js';import { databaseConfigured } from './env.js';import { putObject, publicUrl } from './r2.js';import { recordGenerationEvent } from './forge-events.js';+import { scoreGlbQuality } from './glb-quality.js';+import { compressGlb } from './glb-compress.js';// Stable, non-secret salt so a leaked DB row can't be trivially reversed to the// raw browser-local id. The id is anonymous to begin with; this is hygiene, not@@ -140,7 +142,45 @@ export async function findByJob({ replicateJobId, clientKey }) {const COPY_MAX_ATTEMPTS = 3;const COPY_RETRY_BASE_MS = 400;-async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes }) {+// Score + (optionally) compress a freshly-downloaded GLB before it lands in the+// bucket. Both steps are pure, local, and best-effort: a scoring/compression+// failure never blocks delivery — it just means the response carries no+// quality signal, or ships the original uncompressed bytes. `compress` is one+// of COMPRESSION_MODES ('draco' | 'meshopt') or falsy to skip.+async function scoreAndCompress(buf, { computeQuality, compress }) {+ let quality = null;+ let compression = null;+ if (computeQuality) {+ try {+ quality = scoreGlbQuality(buf);+ } catch (err) {+ console.warn('[forge-store] quality scoring failed:', err?.message);+ }+ }+ let outBuf = buf;+ if (compress) {+ try {+ const result = await compressGlb(buf, { mode: compress });+ if (result.grew) {+ compression = { mode: result.mode, skipped: true, reason: 'no_size_benefit' };+ } else {+ outBuf = result.buffer;+ compression = {+ mode: result.mode,+ input_bytes: result.inputBytes,+ output_bytes: result.outputBytes,+ ratio: result.ratio,+ };+ }+ } catch (err) {+ console.warn(`[forge-store] compression (${compress}) failed, delivering uncompressed:`, err?.message);+ compression = { mode: compress, skipped: true, reason: 'compression_failed' };+ }+ }+ return { buf: outBuf, quality, compression };+}++async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, computeQuality = false, compress = null }) {let lastErr;for (let attempt = 1; attempt <= COPY_MAX_ATTEMPTS; attempt++) {try {@@ -154,11 +194,19 @@ async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes }) {if (attempt < COPY_MAX_ATTEMPTS) { lastErr = err; }else throw err;} else {- const buf = Buffer.from(await resp.arrayBuffer());+ let buf = Buffer.from(await resp.arrayBuffer());if (buf.length > maxBytes) throw new Error(`asset too large: ${buf.length} bytes`);const contentType = resp.headers.get('content-type') || fallbackContentType;+ let quality = null;+ let compression = null;+ if (computeQuality || compress) {+ const scored = await scoreAndCompress(buf, { computeQuality, compress });+ buf = scored.buf;+ quality = scored.quality;+ compression = scored.compression;+ }await putObject({ key, body: buf, contentType, metadata: { source: 'forge' } });- return { bytes: buf.length, publicUrl: publicUrl(key) };+ return { bytes: buf.length, publicUrl: publicUrl(key), quality, compression };}} catch (err) {// Permanent (404/410) or too-large: surface immediately. Network errorsdiff --git a/api/_lib/http.js b/api/_lib/http.jsindex b41746e72..ac35c1e23 100644--- a/api/_lib/http.js+++ b/api/_lib/http.js@@ -327,6 +327,40 @@ export async function readForm(req, limit = 1_000_000) {}export function readBody(req, limit) {+ // The Cloud Run server (server/index.mjs) pre-parses JSON / urlencoded / text /+ // octet-stream bodies through Express body-parser middleware ahead of every+ // handler, fully draining the raw request stream in the process, and stores the+ // result on req.body. If we then attach 'data'/'end' listeners to that same+ // (already-ended) stream below, they never fire — the promise hangs forever.+ // This was a live production incident: every JSON POST handler using readJson+ // (MCP tools/call, /api/forge, etc.) deadlocked with zero response. When+ // req.body is already populated, reconstruct the equivalent raw bytes from it+ // instead of touching the stream. Vercel serverless, local dev, and mcp-server+ // never set req.body ahead of time, so the raw-stream path below is unchanged+ // there — this only short-circuits when a prior middleware already consumed+ // the stream for us.+ if (Buffer.isBuffer(req.rawBody)) {+ // express.json()/urlencoded()'s `verify` hook (server/index.mjs) captured the+ // exact bytes pre-parse — prefer this over req.body so anything depending on+ // byte-for-byte fidelity (HMAC signature checks) still works.+ if (req.rawBody.length > limit) {+ return Promise.reject(Object.assign(new Error('payload too large'), { status: 413 }));+ }+ return Promise.resolve(req.rawBody);+ }+ if (req.body !== undefined) {+ const ct = req.headers['content-type'] || '';+ let buf;+ if (Buffer.isBuffer(req.body)) buf = req.body;+ else if (typeof req.body === 'string') buf = Buffer.from(req.body, 'utf8');+ else if (ct.includes('application/x-www-form-urlencoded')) {+ buf = Buffer.from(new URLSearchParams(req.body).toString(), 'utf8');+ } else buf = Buffer.from(JSON.stringify(req.body ?? {}), 'utf8');+ if (buf.length > limit) {+ return Promise.reject(Object.assign(new Error('payload too large'), { status: 413 }));+ }+ return Promise.resolve(buf);+ }return new Promise((resolve, reject) => {const chunks = [];let total = 0;diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex d52a07346..a76652cd3 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -480,6 +480,16 @@ export const limits = {// the Upstash quota without buying any real protection here.mcp3dStatus: (key) =>getLimiter('mcp3d:status', { limit: 240, window: '1 m', local: true }).limit(key),+ // Persona wallet identity reads (balances, reputation, holdings, nameplate) —+ // several live RPC/HTTP calls per invocation, so a tighter ceiling than plain+ // status polling but generous enough for a chat turn to check before tipping.+ mcp3dPersonaIdentity: (key) =>+ getLimiter('mcp3d:persona:identity', { limit: 60, window: '1 m', local: true }).limit(key),+ // Persona value-movement (persona_tip / persona_send) — moves real USDC, so it+ // gets a hard, critical, low-throughput ceiling independent of the per-call and+ // per-session USDC spend caps enforced inside the handler.+ mcp3dPersonaSpend: (key) =>+ getLimiter('mcp3d:persona:spend', { limit: 20, window: '1 h', critical: true }).limit(key),// Platform-wide hourly circuit breaker across ALL free-studio IPs, so// distributed callers each under their own studioGenHourly cap can't// collectively flood the free NVIDIA / HF allocation. Enforced whenever Redis@@ -515,6 +525,13 @@ export const limits = {// for an agent screening a watchlist while capping a scripted enumeration flood.// Non-critical: a Redis blip degrades to the per-instance memory limiter.tokenSecurityIp: (ip) => getLimiter('token:security:ip', { limit: 20, window: '1 m' }).limit(ip),+ // Free name resolution (api/v1/resolve) — wraps the same ENS RPC failover+ // chain and SNS/Bonfida calls api/agents/ens/[name].js and api/sns.js already+ // make, all with their own in-process caches, so this only gates cache-miss+ // origin hits. 30/min per IP matches the spec's high-frequency-agent-primitive+ // budget without inviting a scripted enumeration flood. Non-critical: a Redis+ // blip degrades to the per-instance memory limiter, never blocks a resolution.+ resolveIp: (ip) => getLimiter('v1:resolve:ip', { limit: 30, window: '1 m' }).limit(ip),// Diorama composer (api/diorama action:compose) — one free-first LLM// completion per call that decomposes a sentence into a placed object set.// Paid upstream egress, so cap per IP and add a global hourly circuit breaker.@@ -1016,6 +1033,20 @@ export const limits = {// 10 per hour per IP is enough for manual setup; bots would need more.oracleFollowIp: (ip) =>getLimiter('oracle:follow:ip', { limit: 10, window: '1 h' }).limit(ip),++ // Aggregator free tier (api/v1/x/[...slug].js). Endpoints in api/v1/_providers.js+ // may carry a `free: { perMin, perDay }` quota — an unauthenticated caller (no+ // BYOK key, no three.ws credentials) gets real, no-signup data before the x402+ // 402 challenge kicks in. Two dynamic buckets, keyed per (provider/endpoint, IP)+ // so each endpoint's own quota sizes its own counter (mirrors the widgetChat /+ // embedLlmAgent per-resource-dynamic-limit pattern above). Non-critical: a Redis+ // outage must never turn a free call into a false 402 — it degrades to the+ // per-instance memory limiter, same posture as the other zero-marginal-cost free+ // lanes (mcp3dGenerateFree, studioGenBurst) in this file.+ apiV1FreeMin: (key, perMin) =>+ getLimiter('v1:free:min', { limit: Math.max(1, Number(perMin) || 30), window: '1 m' }).limit(key),+ apiV1FreeDay: (key, perDay) =>+ getLimiter('v1:free:day', { limit: Math.max(1, Number(perDay) || 1000), window: '1 d' }).limit(key),};// Trust only proxy headers that Vercel itself sets and signs. Naively readingdiff --git a/api/_lib/service-catalog/services/embody.js b/api/_lib/service-catalog/services/embody.jsnew file mode 100644index 000000000..ce8b68c63--- /dev/null+++ b/api/_lib/service-catalog/services/embody.js@@ -0,0 +1,47 @@+// Service-catalog descriptor — the single written-once listing for this+// service. api/wk.js derives its /.well-known/x402.json resource entry from+// this file via api/_lib/service-catalog/index.js (toBazaarDiscovery), and+// the OKX storefront projection reads the same record (toOkxCatalog).+// Contract: specs/service-catalog.md. Do not re-add a hand-written mirror+// for this route in api/wk.js — edit this descriptor instead.++export default {+ slug: 'embody',+ title: 'Embodiment',+ category: '3d',+ useCase:+ '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.',+ path: '/api/x402/embody',+ method: 'POST',+ free: false,+ status: 'live',+ priceAtomics: '1000000',+ acceptsBuilder: 'standard',+ serviceName: 'three.ws Embodiment',+ tags: ['3d', 'avatar', 'embed', 'agent', 'embodiment'],+ 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. POST { name, prompt | image_url, personality?, voice? } and get back ' ++ '{ agent_id, glb_url, viewer_url, profile_url, embed_html, voice }. The body is a ' ++ 'durable persona that reloads by id in any future session. $1 USDC, no account. ' ++ 'Generation failures never settle — you are only charged when a finished body is returned.',+ input: {+ name: 'Nova Scout',+ prompt: 'a friendly explorer in a teal jumpsuit',+ voice: 'nova',+ },+ inputSchema: {+ type: 'object',+ required: ['name'],+ oneOf: [{ required: ['prompt'] }, { required: ['image_url'] }],+ properties: {+ name: { type: 'string', minLength: 1, maxLength: 64 },+ prompt: { type: 'string', minLength: 1, maxLength: 600 },+ image_url: { type: 'string', format: 'uri' },+ personality: { type: 'string', maxLength: 600 },+ voice: { type: 'string' },+ },+ },+ storefronts: ['x402scan'],+};diff --git a/api/_lib/service-catalog/services/fact-check.js b/api/_lib/service-catalog/services/fact-check.jsnew file mode 100644index 000000000..91e94e762--- /dev/null+++ b/api/_lib/service-catalog/services/fact-check.js@@ -0,0 +1,51 @@+// Service-catalog descriptor — the single written-once listing for this+// service. api/wk.js derives its /.well-known/x402.json resource entry from+// this file via api/_lib/service-catalog/index.js (toBazaarDiscovery), and+// the OKX storefront projection reads the same record (toOkxCatalog).+// Contract: specs/service-catalog.md. Do not re-add a hand-written mirror+// for this route in api/wk.js — edit this descriptor instead.+//+// Re-listed per the 2026-07-08 storefront cleanup (prompt 18) — see+// api/x402/fact-check.js for the header note superseding the prior+// "internal-use only" de-listing.++export default {+ slug: 'fact-check',+ title: 'Real-Time Fact Checker',+ category: 'trust',+ useCase: '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.',+ path: '/api/x402/fact-check',+ method: 'POST',+ free: false,+ status: 'live',+ priceAtomics: '100000',+ acceptsBuilder: 'standard',+ serviceName: 'three.ws Fact Checker',+ tags: ['fact-check', 'search', 'verification'],+ 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. Each result includes source authority weights, a confidence score, and a cost breakdown. Strictness controls how aggressively low-authority sources are downweighted. Price: $0.10 base per check on Base or Solana USDC.',+ input: {+ claim: 'The Eiffel Tower is 330 meters tall.',+ strictness: 'high',+ },+ inputSchema: {+ type: 'object',+ required: ['claim'],+ properties: {+ claim: {+ type: 'string',+ minLength: 5,+ maxLength: 1000,+ },+ strictness: {+ type: 'string',+ enum: ['high', 'medium', 'low'],+ },+ imageUrl: {+ type: 'string',+ format: 'uri',+ maxLength: 2048,+ },+ },+ },+ storefronts: ['x402scan'],+};diff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.jsindex 3d9d68945..de307e7cd 100644--- a/api/_lib/service-catalog/services/index.js+++ b/api/_lib/service-catalog/services/index.js@@ -37,6 +37,7 @@ import pipelineGameready from './pipeline-gameready.js';import pipelineStylize from './pipeline-stylize.js';import pipelineRembg from './pipeline-rembg.js';import pipeline from './pipeline.js';+import embody from './embody.js';import bazaarFeed from './bazaar-feed.js';import billboard from './billboard.js';import crossChain from './cross-chain.js';@@ -84,6 +85,7 @@ export const PAID_SERVICES = Object.freeze([pipelineStylize,pipelineRembg,pipeline,+ embody,bazaarFeed,billboard,crossChain,diff --git a/api/_lib/spatial-mcp.js b/api/_lib/spatial-mcp.jsnew file mode 100644index 000000000..acacfbaed--- /dev/null+++ b/api/_lib/spatial-mcp.js@@ -0,0 +1,270 @@+// Spatial MCP — the open shape for 3D-native tool results, and its validator.+//+// MCP tool results are text/JSON today. A *spatial* MCP artifact carries a live,+// interactive 3D scene as a first-class structured-content field so a host can+// render it (orbit, animate, AR) instead of printing a URL. This module is the+// single source of truth for that shape:+//+// • buildSpatialArtifact(...) — assemble a conformant artifact from the+// fields a generation tool already has (glbUrl, kind, prompt, …).+// • validateSpatialArtifact(payload) — check conformance and return ACTIONABLE+// errors ({ path, message }), not a bare boolean. Used as the gate every+// three.ws 3D tool passes its artifact through, and callable by third-party+// servers adopting the shape.+//+// It is intentionally dependency-free (no Ajv, no fetch, no DB) so it loads+// unchanged in the Vercel api/ bundle, the published npm package, the free+// OpenAI studio, and the unit tests — and carries ZERO payment, wallet, coin, or+// token surface, so the renderer and validator drop cleanly into the crypto-free+// OpenAI app. Spec: specs/SPATIAL_MCP.md.++export const SPATIAL_MCP_VERSION = '0.1';++// Versions this validator accepts. New minor versions are added here as the+// shape evolves; a host reads spatialMcpVersion to pick its renderer.+const KNOWN_VERSIONS = new Set(['0.1']);++// The subject a 3D artifact describes. Open enum — a host that doesn't know a+// kind still renders scene.glbUrl; the kind only drives labelling/affordances.+const KNOWN_KINDS = new Set(['model', 'mesh', 'avatar', 'rigged-model', 'scene']);++const TOP_LEVEL_KEYS = new Set([+ 'spatialMcpVersion',+ 'kind',+ 'scene',+ 'camera',+ 'environment',+ 'animation',+ 'persona',+ 'ar',+ 'affordances',+ 'meta',+]);++// A conservative https check — the renderer only ever loads assets over https,+// and rejecting other schemes at the boundary keeps data: / javascript: / http+// out of a field a host will feed to <model-viewer src>.+function isHttpsUrl(v) {+ if (typeof v !== 'string' || !v) return false;+ try {+ return new URL(v).protocol === 'https:';+ } catch {+ return false;+ }+}++function isPlainObject(v) {+ return v != null && typeof v === 'object' && !Array.isArray(v);+}++/**+ * Assemble a spec-conformant spatial artifact from the fields a generation tool+ * already has. Only `glbUrl` is required; everything else is optional and only+ * emitted when provided, so the output is always valid and never carries empty+ * scaffolding. Pure and deterministic.+ *+ * @param {object} a+ * @param {string} a.glbUrl the generated asset (https)+ * @param {string} [a.kind] one of KNOWN_KINDS (default 'model')+ * @param {string} [a.viewerUrl] three.ws viewer link (meta)+ * @param {string} [a.poster] preview image (https)+ * @param {string} [a.prompt] the generating prompt (meta)+ * @param {string} [a.title] human title (meta)+ * @param {boolean}[a.autoRotate] camera auto-rotate (default true)+ * @param {string} [a.cameraOrbit] model-viewer camera-orbit string+ * @param {boolean}[a.rigged] true → animation hooks enabled+ * @param {string[]}[a.clips] named animation clips+ * @param {string} [a.personaId] persona binding (prompt 07)+ * @param {{usdzUrl?:string,glbUrl?:string,launchUrl?:string}} [a.ar] AR handoff (prompt 21)+ * @returns {object} a conformant spatial artifact+ */+export function buildSpatialArtifact(a = {}) {+ const kind = KNOWN_KINDS.has(a.kind) ? a.kind : 'model';+ const artifact = {+ spatialMcpVersion: SPATIAL_MCP_VERSION,+ kind,+ scene: {+ glbUrl: a.glbUrl,+ format: 'glb',+ ...(a.poster ? { poster: a.poster } : {}),+ ...(a.alt ? { alt: a.alt } : {}),+ },+ camera: {+ autoRotate: a.autoRotate !== false,+ ...(a.cameraOrbit ? { orbit: a.cameraOrbit } : {}),+ },+ environment: {+ image: a.environmentImage || 'neutral',+ exposure: typeof a.exposure === 'number' ? a.exposure : 1,+ shadowIntensity: typeof a.shadowIntensity === 'number' ? a.shadowIntensity : 1,+ },+ affordances: {+ orbit: true,+ zoom: true,+ fullscreen: true,+ download: a.download !== false,+ },+ };++ // Animation hooks only when the asset is actually rigged/animated.+ if (a.rigged || (Array.isArray(a.clips) && a.clips.length)) {+ artifact.animation = {+ autoplay: a.autoplay !== false,+ ...(Array.isArray(a.clips) && a.clips.length ? { clips: a.clips.slice(0, 64) } : {}),+ };+ }++ // Persona hook (prompt 07) — a speakable embodied body.+ if (a.personaId) {+ artifact.persona = { id: String(a.personaId), speakable: true };+ }++ // AR handoff (prompt 21). `supported` is true when any concrete AR asset/link+ // is present; a host without AR ignores this block and renders the WebGL scene.+ if (a.ar && isPlainObject(a.ar)) {+ const ar = {};+ if (isHttpsUrl(a.ar.usdzUrl)) ar.usdzUrl = a.ar.usdzUrl;+ if (isHttpsUrl(a.ar.glbUrl)) ar.glbUrl = a.ar.glbUrl;+ if (isHttpsUrl(a.ar.launchUrl)) ar.launchUrl = a.ar.launchUrl;+ if (Object.keys(ar).length) {+ ar.supported = true;+ artifact.ar = ar;+ }+ }++ const meta = {};+ if (a.prompt) meta.prompt = String(a.prompt);+ if (a.title) meta.title = String(a.title);+ if (isHttpsUrl(a.viewerUrl)) meta.viewerUrl = a.viewerUrl;+ if (Object.keys(meta).length) artifact.meta = meta;++ return artifact;+}++// ── Validator ────────────────────────────────────────────────────────────────++function err(errors, path, message) {+ errors.push({ path, message });+}+function warn(warnings, path, message) {+ warnings.push({ path, message });+}++/**+ * Validate a spatial artifact against the spec. Returns actionable diagnostics —+ * every problem names the offending `path` and how to fix it — so a caller (a+ * third-party server adopting the shape, or a three.ws tool's self-check) can+ * correct its output, not just learn that it's wrong.+ *+ * @param {any} payload+ * @returns {{ valid:boolean, version:(string|null), errors:Array<{path,message}>,+ * warnings:Array<{path,message}> }}+ */+export function validateSpatialArtifact(payload) {+ const errors = [];+ const warnings = [];++ if (!isPlainObject(payload)) {+ return {+ valid: false,+ version: null,+ errors: [{ path: '(root)', message: 'artifact must be a JSON object' }],+ warnings,+ };+ }++ // Version.+ const version = payload.spatialMcpVersion ?? null;+ if (version == null) {+ err(errors, 'spatialMcpVersion', `required — set it to "${SPATIAL_MCP_VERSION}"`);+ } else if (typeof version !== 'string' || !KNOWN_VERSIONS.has(version)) {+ err(errors, 'spatialMcpVersion', `unknown version ${JSON.stringify(version)} — supported: ${[...KNOWN_VERSIONS].join(', ')}`);+ }++ // Kind.+ if (payload.kind == null) {+ err(errors, 'kind', `required — one of ${[...KNOWN_KINDS].join(', ')}`);+ } else if (!KNOWN_KINDS.has(payload.kind)) {+ err(errors, 'kind', `unknown kind ${JSON.stringify(payload.kind)} — expected one of ${[...KNOWN_KINDS].join(', ')}`);+ }++ // Scene (required, with a required https glbUrl).+ if (!isPlainObject(payload.scene)) {+ err(errors, 'scene', 'required object with a `glbUrl`');+ } else {+ if (!isHttpsUrl(payload.scene.glbUrl)) {+ err(errors, 'scene.glbUrl', 'required — must be an https URL to a .glb asset');+ }+ if (payload.scene.format !== undefined && payload.scene.format !== 'glb') {+ err(errors, 'scene.format', 'only "glb" is supported in v0.1');+ } else if (payload.scene.format === undefined) {+ warn(warnings, 'scene.format', 'recommended — set to "glb"');+ }+ if (payload.scene.poster !== undefined && !isHttpsUrl(payload.scene.poster)) {+ err(errors, 'scene.poster', 'must be an https URL when present');+ }+ }++ // Optional blocks — validate shape/types only when present.+ if (payload.camera !== undefined) {+ if (!isPlainObject(payload.camera)) err(errors, 'camera', 'must be an object when present');+ else if (payload.camera.autoRotate !== undefined && typeof payload.camera.autoRotate !== 'boolean')+ err(errors, 'camera.autoRotate', 'must be a boolean');+ } else {+ warn(warnings, 'camera', 'recommended — include `{ autoRotate: true }` so hosts frame the model');+ }++ if (payload.environment !== undefined && !isPlainObject(payload.environment)) {+ err(errors, 'environment', 'must be an object when present');+ }++ if (payload.animation !== undefined) {+ if (!isPlainObject(payload.animation)) err(errors, 'animation', 'must be an object when present');+ else if (payload.animation.clips !== undefined && !Array.isArray(payload.animation.clips))+ err(errors, 'animation.clips', 'must be an array of clip names');+ }++ if (payload.persona !== undefined && !isPlainObject(payload.persona)) {+ err(errors, 'persona', 'must be an object when present');+ }++ if (payload.ar !== undefined) {+ if (!isPlainObject(payload.ar)) {+ err(errors, 'ar', 'must be an object when present');+ } else {+ for (const k of ['usdzUrl', 'glbUrl', 'launchUrl']) {+ if (payload.ar[k] !== undefined && !isHttpsUrl(payload.ar[k]))+ err(errors, `ar.${k}`, 'must be an https URL when present');+ }+ const hasAsset = ['usdzUrl', 'glbUrl', 'launchUrl'].some((k) => isHttpsUrl(payload.ar[k]));+ if (payload.ar.supported === true && !hasAsset)+ err(errors, 'ar.supported', 'true requires at least one of ar.usdzUrl / ar.glbUrl / ar.launchUrl');+ }+ }++ if (payload.affordances !== undefined && !isPlainObject(payload.affordances)) {+ err(errors, 'affordances', 'must be an object when present');+ }++ if (payload.meta !== undefined && !isPlainObject(payload.meta)) {+ err(errors, 'meta', 'must be an object when present');+ }++ // Unknown top-level keys are a warning, not an error — forward-compatibility+ // with hosts that carry extra fields, but flagged so typos surface.+ for (const key of Object.keys(payload)) {+ if (!TOP_LEVEL_KEYS.has(key)) warn(warnings, key, 'unknown top-level field — ignored by conformant renderers');+ }++ return {+ valid: errors.length === 0,+ version: typeof version === 'string' ? version : null,+ errors,+ warnings,+ };+}++/** Convenience: true iff `payload` is a conformant artifact. */+export function isConformantSpatialArtifact(payload) {+ return validateSpatialArtifact(payload).valid;+}diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.jsindex 28e4030f1..e6a420dfa 100644--- a/api/_lib/x402-spec.js+++ b/api/_lib/x402-spec.js@@ -379,7 +379,7 @@ export function solanaSettleable() {// sibling right after the Base accept.//// Replaces five byte-for-byte copies of this logic (model-check, mint-to-mesh,-// vanity, vanity-verifiable, revenue-vision) and matches the Solana-first ordering+// vanity, vanity-verifiable, mint-to-mesh-batch) and matches the Solana-first ordering// the discovery catalog (wk.js) already advertises, so live 402 and catalog agree.export function buildExactRequirements(resourceUrl, amount = env.X402_MAX_AMOUNT_REQUIRED) {const amt = String(amount);@@ -928,7 +928,7 @@ function buildIdempotencyKey({ paymentPayload, requirement }) {//// When the caller doesn't pass `builderCode`, we derive it from// X402_BUILDER_CODE_APP so the raw-verifyPayment routes (model-check,-// mint-to-mesh, revenue-vision, mcp/auth) get echo enforcement symmetric+// mint-to-mesh, mint-to-mesh-batch, mcp/auth) get echo enforcement symmetric// with build402Body's auto-declaration. Pass `builderCode: null`// explicitly to opt out (e.g. test harnesses).export async function verifyPayment({ paymentHeader, requirements, builderCode }) {diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex b77320233..458fa1c62 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -917,15 +917,19 @@ const SELF_ENDPOINTS = [// Pays $0.005 USDC every 30 min to POST /api/x402/symbol-availability with// the 5 highest-demand meme token symbols: MOON, ROCKET, FROG, CAT, DOG.// The batch endpoint checks each against pump_agent_mints for exact collisions- // and returns { available_count, taken_count, available_list, signal, headline }.- // As an `oracle` entry the signal (bullish/neutral/bearish) + headline dedup- // into oracle_intel_signals (topic 'symbol_availability') — actionable for the- // sniper gate: many available high-demand names = underexploited launch window;- // all taken = market saturated, raise launch-entry threshold. Cooldown 1800s- // (30 min) — symbol availability changes slowly as new mints land; 48- // calls/day × $0.005 = $0.24/day, well under the loop's $5/day cap.- // Downstream: oracle_intel_signals WHERE topic = 'symbol_availability' + the- // full batch breakdown in x402_autonomous_log.signal_data.+ // and returns { available_count, taken_count, available_list, headline } — the+ // 2026-07-08 storefront cleanup (prompt 18) removed the bullish/bearish/neutral+ // `signal` field from the wire response (it's a collision checker, not a market+ // oracle), so this consumer now derives its own coarse bucket locally from the+ // available/scanned ratio, same thresholds the endpoint used to apply. As an+ // `oracle` entry the bucket + headline dedup into oracle_intel_signals (topic+ // 'symbol_availability') — actionable for the sniper gate: many available+ // high-demand names = underexploited launch window; all taken = market+ // saturated, raise launch-entry threshold. Cooldown 1800s (30 min) — symbol+ // availability changes slowly as new mints land; 48 calls/day × $0.005 =+ // $0.24/day, well under the loop's $5/day cap. Downstream: oracle_intel_signals+ // WHERE topic = 'symbol_availability' + the full batch breakdown in+ // x402_autonomous_log.signal_data.{id: 'symbol-scan-common',name: 'Symbol Availability: Common Meme Scan',@@ -936,17 +940,23 @@ const SELF_ENDPOINTS = [priority: 86,pipeline: 'oracle',enabled: true,- extractSignal: (r) => ({- topic: 'symbol_availability',- signal: r?.signal ?? null,- headline: r?.headline ?? null,- confidence: r?.signal === 'bullish' ? 0.85 : r?.signal === 'neutral' ? 0.65 : 0.80,- available_count: r?.available_count ?? null,- taken_count: r?.taken_count ?? null,- scanned_count: r?.scanned_count ?? null,- available_list: Array.isArray(r?.available_list) ? r.available_list : [],- taken_list: Array.isArray(r?.taken_list) ? r.taken_list : [],- }),+ extractSignal: (r) => {+ const available = r?.available_count ?? 0;+ const scanned = r?.scanned_count ?? 0;+ const ratio = scanned > 0 ? available / scanned : 0;+ const signal = ratio >= 0.6 ? 'bullish' : ratio >= 0.3 ? 'neutral' : 'bearish';+ return {+ topic: 'symbol_availability',+ signal,+ headline: r?.headline ?? null,+ confidence: signal === 'bullish' ? 0.85 : signal === 'neutral' ? 0.65 : 0.80,+ available_count: r?.available_count ?? null,+ taken_count: r?.taken_count ?? null,+ scanned_count: r?.scanned_count ?? null,+ available_list: Array.isArray(r?.available_list) ? r.available_list : [],+ taken_list: Array.isArray(r?.taken_list) ? r.taken_list : [],+ };+ },},// ── Bazaar New-Listing Feed (USE-059) ──────────────────────────────────────diff --git a/api/_lib/x402/payment-identifier-server.js b/api/_lib/x402/payment-identifier-server.jsindex e34dea832..d01e09abc 100644--- a/api/_lib/x402/payment-identifier-server.js+++ b/api/_lib/x402/payment-identifier-server.js@@ -12,7 +12,7 @@// The functions here are deliberately framework-free — they operate on a// decoded payload + a small request descriptor — so they can be wired into// both the `paidEndpoint()` wrapper and the standalone endpoints that hand--// roll their 402 dance (model-check, mint-to-mesh, revenue-vision).+// roll their 402 dance (model-check, mint-to-mesh, mint-to-mesh-batch).import {PAYMENT_IDENTIFIER,diff --git a/api/_lib/x402/ring-catalog.js b/api/_lib/x402/ring-catalog.jsindex 58d7357be..4b1e57013 100644--- a/api/_lib/x402/ring-catalog.js+++ b/api/_lib/x402/ring-catalog.js@@ -49,6 +49,11 @@ const SOLANA_CAIP2 = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';// $THREE — the platform coin, guaranteed to resolve on the market data feed and// carry on-chain metadata; used wherever a canary needs a real, resolvable mint.const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+// A tiny (364-byte), well-formed 8kHz/mono/16-bit WAV of silence — base64. Used+// as the canary payload for the ASR endpoint so a one-time verification call has+// real, parseable audio bytes without shipping a binary fixture in this file.+const SILENT_WAV_B64 =+ 'UklGRmQBAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YUABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==';/*** @typedef {Object} CatalogEntry@@ -805,6 +810,156 @@ export const RING_CATALOG = [businessEffect: 'Settles a Base-mainnet Permit2/EIP-2612 USDC payment and returns the tx hash.',note: 'autobuy:false — Base-only, Permit2/EIP-2612-only (no Solana accept). The Solana ring payer structurally cannot pay it; verify with an @x402/evm wallet.',},++ // ── AI services (v1) — real provider compute per call ───────────────────────+ {+ slug: 'ai-asr',+ sourceFile: 'api/v1/ai/asr.js',+ path: '/api/v1/ai/asr',+ method: 'POST',+ body: () => ({ audio: SILENT_WAV_B64, format: 'wav', language: 'en-US' }),+ priceAtomicDefault: 10_000,+ priceSlug: 'ai-asr',+ tier: 'intel',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Transcribes the sample WAV clip via the NVIDIA NIM Riva ASR lane, paid over x402 (no state written).',+ note: 'autobuy:false — every call burns real NVIDIA NIM Riva ASR compute; not a free read-only ping.',+ },+ {+ slug: 'ai-image',+ sourceFile: 'api/v1/ai/image.js',+ path: '/api/v1/ai/image',+ method: 'POST',+ body: () => ({ prompt: 'a brass owl figurine on a plain white background', aspect_ratio: '1:1' }),+ priceAtomicDefault: 20_000,+ priceSlug: 'ai-image',+ tier: 'intel',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Generates one AI image via the NVIDIA NIM / Vertex / Replicate lane and persists it to R2, paid over x402.',+ note: 'autobuy:false — every call burns real NVIDIA/Vertex/Replicate image-generation compute and persists a new R2 object.',+ },+ {+ slug: 'ai-tts',+ sourceFile: 'api/v1/ai/tts.js',+ path: '/api/v1/ai/tts',+ method: 'POST',+ body: () => ({ text: 'Ring canary heartbeat check.', voice: 'nova' }),+ priceAtomicDefault: 5_000,+ priceSlug: 'ai-tts',+ tier: 'service',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Synthesizes speech via the NVIDIA NIM Magpie TTS lane, paid over x402 (no state written).',+ note: 'autobuy:false — every call burns real NVIDIA NIM Magpie TTS compute.',+ },++ // ── 3D Asset Pipeline stages — real Cloud Run GPU compute per call ──────────+ {+ slug: 'pipeline-rembg',+ sourceFile: 'api/x402/pipeline-rembg.js',+ path: '/api/x402/pipeline-rembg',+ method: 'POST',+ body: () => ({ image_url: 'https://three.ws/og-image.png', model: 'rmbg2' }),+ priceAtomicDefault: 10_000,+ priceSlug: 'pipeline-rembg',+ tier: 'intel',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Runs a background-removal job against the Cloud Run rembg worker on a real image and persists the cutout PNG.',+ note: 'autobuy:false — every call runs a real Cloud Run GPU rembg worker job and persists a new object; not a cheap read-only ping.',+ },+ {+ slug: 'pipeline-remesh',+ sourceFile: 'api/x402/pipeline-remesh.js',+ path: '/api/x402/pipeline-remesh',+ method: 'POST',+ body: () => ({ glb_url: 'https://three.ws/avatars/default.glb', remesh_mode: 'triangle', target_faces: 20_000 }),+ priceAtomicDefault: 30_000,+ priceSlug: 'pipeline-remesh',+ tier: 'commerce',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Runs a retopology/decimation job against the Cloud Run remesh worker on a real GLB and persists the output mesh.',+ note: 'autobuy:false — every call runs a real Cloud Run GPU remesh worker job and persists a new GLB.',+ },+ {+ slug: 'pipeline-rig',+ sourceFile: 'api/x402/pipeline-rig.js',+ path: '/api/x402/pipeline-rig',+ method: 'POST',+ body: () => ({ glb_url: 'https://three.ws/avatars/default.glb', rig_type: 'biped' }),+ priceAtomicDefault: 50_000,+ priceSlug: 'pipeline-rig',+ tier: 'commerce',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Runs an auto-rig job against the avatar-pipeline-controller and persists a skinned, animation-ready GLB.',+ note: 'autobuy:false — every call runs a real auto-rig worker job (the priciest pipeline stage) and persists a new GLB.',+ },+ {+ slug: 'pipeline-stylize',+ sourceFile: 'api/x402/pipeline-stylize.js',+ path: '/api/x402/pipeline-stylize',+ method: 'POST',+ body: () => ({ glb_url: 'https://three.ws/avatars/default.glb', style: 'voxel' }),+ priceAtomicDefault: 30_000,+ priceSlug: 'pipeline-stylize',+ tier: 'commerce',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Runs a geometric stylize job (voxel/brick/voronoi/lowpoly) against the Cloud Run stylize worker and persists the output GLB.',+ note: 'autobuy:false — every call runs a real Cloud Run GPU stylize worker job and persists a new GLB.',+ },+ {+ slug: 'pipeline-gameready',+ sourceFile: 'api/x402/pipeline-gameready.js',+ path: '/api/x402/pipeline-gameready',+ method: 'POST',+ body: () => ({ glb_url: 'https://three.ws/avatars/default.glb', topology: 'quad', poly_budget: 15_000 }),+ priceAtomicDefault: 30_000,+ priceSlug: 'pipeline-gameready',+ tier: 'commerce',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Runs a game-ready retopology job (quad/tri poly budget) against the Cloud Run remesh worker and persists the output GLB.',+ note: 'autobuy:false — every call runs a real Cloud Run GPU remesh worker job and persists a new GLB.',+ },++ // ── remix — real generation + on-chain creator royalty ──────────────────────+ {+ slug: 'remix-asset',+ sourceFile: 'api/x402/remix-asset.js',+ path: '/api/x402/remix-asset',+ method: 'POST',+ body: () => ({ source_creation_id: RING_CANARY_UUID, instruction: 'make it metallic' }),+ priceAtomicDefault: 250_000,+ priceSlug: 'remix-asset',+ tier: 'commerce',+ kind: 'commerce',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Generates a real GPU-derived remix of a published creation, records parent→child provenance, and routes a real on-chain USDC royalty to the source creator.',+ note: 'autobuy:false — every call is a real GPU generation plus a possible real on-chain USDC royalty transfer to a third-party creator wallet; requires a live, published remixable source creation id (the canary UUID resolves to source_not_found). Verify once against a known published remixable source.',+ },];// ── selectors ─────────────────────────────────────────────────────────────────diff --git a/api/_mcp-studio/tools.js b/api/_mcp-studio/tools.jsindex 587675420..e50e68632 100644--- a/api/_mcp-studio/tools.js+++ b/api/_mcp-studio/tools.js@@ -25,6 +25,7 @@ import {directPrompt,} from './forge-client.js';import { COMPONENT_URI } from './component.js';+import { buildSpatialArtifact } from '../_lib/spatial-mcp.js';// Pure, dependency-free lineage core — the SAME module the paid stdio server's// runRefineModel uses (mcp-server/src/tools/_lineage.js), so conversational// iteration behaves identically on both tracks and never drifts. It carries@@ -45,13 +46,24 @@ const VALID_TIER = new Set(['draft', 'standard', 'high']);// Minimal, identifier-free success envelope. structuredContent is the contract// the widget + model read; content is the human/agent-readable narration.function ok({ glbUrl, base, kind, prompt, rigged }) {+ const vUrl = viewerUrl(base, glbUrl);const structured = {kind,glbUrl,- viewerUrl: viewerUrl(base, glbUrl),+ viewerUrl: vUrl,format: 'glb',...(prompt ? { prompt } : {}),...(rigged ? { rigged: true } : {}),+ // Spatial MCP artifact — the open, coin-clean shape for a 3D-native tool+ // result (specs/SPATIAL_MCP.md). Additive to the fields the widget already+ // reads, so any Spatial-MCP renderer can display this model, not just ours.+ spatial: buildSpatialArtifact({+ glbUrl,+ kind: rigged ? 'rigged-model' : kind === 'avatar' ? 'avatar' : kind === 'mesh' ? 'mesh' : 'model',+ viewerUrl: vUrl,+ prompt: prompt || undefined,+ rigged: Boolean(rigged),+ }),};const label = rigged ? 'rigged 3D model' : '3D model';return {@@ -79,15 +91,18 @@ function toolError(message) {// the next refinement (parent_lineage) so branch/revert work without any// server-side session — a pointer move over an immutable array, never a mutation.function refineOk({ glbUrl, base, prompt, instruction, lineage, activeIndex }) {+ const vUrl = viewerUrl(base, glbUrl);const structured = {kind: 'refined model',glbUrl,- viewerUrl: viewerUrl(base, glbUrl),+ viewerUrl: vUrl,format: 'glb',...(prompt ? { prompt } : {}),...(instruction ? { instruction } : {}),lineage: summarizeLineage(lineage, activeIndex),activeIndex,+ // Conformant Spatial MCP artifact (specs/SPATIAL_MCP.md) for the refined model.+ spatial: buildSpatialArtifact({ glbUrl, kind: 'model', viewerUrl: vUrl, prompt: prompt || undefined, title: instruction || undefined }),};const versionNo = activeIndex; // 0 = original, 1 = first refinement, …return {@@ -188,10 +203,18 @@ async function handleTextToAvatar(args, _auth, req) {}const MESH_DIRECTOR =- "You are a 3D asset art director. Rewrite the user's idea into ONE concise prompt for a text-to-3D " +- 'generator. Describe a SINGLE isolated subject on a plain background, naming form, materials, color, and ' +- 'surface detail. No scenes, no multiple objects, no text or logos, no background. Output ONLY the rewritten ' +- 'prompt as a single line.';+ "You are a 3D asset art director briefing a text-to-3D reconstruction model. Rewrite the user's idea into " ++ 'ONE concise, information-dense prompt that maximizes mesh and texture quality. Cover, in order: (1) the ' ++ 'SINGLE subject and its overall silhouette/proportions, (2) construction — distinct parts, how they join, ' ++ 'any symmetry, (3) materials per part with explicit PBR cues (e.g. brushed steel, matte ceramic, worn ' ++ 'leather, glossy lacquer, rough stone) so surfaces reconstruct with the right roughness/metalness, (4) a ' ++ 'coherent, consistent art style held across the whole subject (pick one: photoreal, stylized, low-poly, ' ++ 'hand-painted — never mix styles), (5) fine surface detail (seams, panel lines, weathering, grain) that ' ++ 'gives the reconstructor texture to latch onto. Always end with these composition constraints so the ' ++ 'reference image reconstructs cleanly: full subject in frame, centered, isolated on a plain neutral ' ++ 'background, one camera angle, even studio lighting, no cropping, no motion blur, no text or watermark, no ' ++ 'collage or multi-view grid, no second subject. Output ONLY the rewritten prompt as a single line — no ' ++ 'preamble, no quotes.';async function handleMeshForge(args, _auth, req) {const base = originFromReq(req);@@ -247,11 +270,19 @@ async function handleRigMesh(args, _auth, req) {}const AVATAR_DIRECTOR =- "You are a 3D character art director. Rewrite the user's idea into ONE concise prompt for a text-to-3D " +- 'generator that will be auto-rigged. Describe a SINGLE full-body humanoid character standing in a neutral ' +- 'pose with arms slightly away from the body, on a plain background. Name body type, outfit, materials, ' +- 'colors, and key features. No scene, no props across the body, no multiple characters, no text. Output ONLY ' +- 'the rewritten prompt as a single line.';+ "You are a 3D character art director briefing a text-to-3D reconstruction model whose output will be " ++ "auto-rigged for animation. Rewrite the user's idea into ONE concise, information-dense prompt. Cover, in " ++ 'order: (1) a SINGLE full-body humanoid, standing in a neutral A/T-adjacent pose, arms slightly away from ' ++ 'the body and legs slightly apart so limbs are readable and separable for rigging, (2) body type and ' ++ 'proportions, (3) outfit and gear per body region (head, torso, arms, legs, feet) with explicit PBR ' ++ 'material cues (e.g. brushed metal armor, worn leather straps, matte cloth, glossy visor) so surfaces ' ++ 'reconstruct with correct roughness/metalness, (4) one coherent, consistent art style held across the ' ++ 'whole character (pick one: photoreal, stylized, low-poly, hand-painted — never mix styles), (5) key ' ++ 'identifying features (hair, face, color scheme, accessories). Always end with these composition ' ++ 'constraints: full body in frame head-to-toe, centered, isolated on a plain neutral background, no props ' ++ 'gripped or crossing the silhouette, one camera angle facing the character, even studio lighting, no ' ++ 'cropping, no motion blur, no text or watermark, no collage or multi-view grid, no second character. ' ++ 'Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';async function handleForgeAvatar(args, _auth, req) {const base = originFromReq(req);diff --git a/api/_mcp3d/catalog.js b/api/_mcp3d/catalog.jsindex 665b57fc1..3aa279a0b 100644--- a/api/_mcp3d/catalog.js+++ b/api/_mcp3d/catalog.js@@ -4,6 +4,7 @@ import addFormats from 'ajv-formats';import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';import { priceUsdcForTier } from '../_lib/forge-tiers.js';import { toolDefs as studioDefs } from './tools/studio.js';+import { toolDefs as spatialDefs } from './tools/spatial.js';import { toolDefs as modelDefs } from '../_mcp/tools/models.js';import { toolDefs as animationDefs } from '../_mcp/tools/animations.js';@@ -18,7 +19,7 @@ const reusedModelDefs = modelDefs.filter(// The animation library (list_animations + apply_animation) completes the// pipeline: text_to_3d → auto_rig_model → apply_animation. Same retarget engine// the main server exposes — reused here, not duplicated.-const baseDefs = [...studioDefs, ...reusedModelDefs, ...animationDefs];+const baseDefs = [...studioDefs, ...spatialDefs, ...reusedModelDefs, ...animationDefs];// Free, public entry point — listed first so discovery clients see it up top.// Annotations: a static, local overview built at module load — read-only,diff --git a/api/_mcp3d/tools/spatial.js b/api/_mcp3d/tools/spatial.jsnew file mode 100644index 000000000..747e7c614--- /dev/null+++ b/api/_mcp3d/tools/spatial.js@@ -0,0 +1,65 @@+// Spatial MCP conformance validator — the public gate for 3D-native tool results.+//+// `validate_spatial_response` checks that a structured-content payload conforms to+// the open Spatial MCP artifact shape (specs/SPATIAL_MCP.md) and returns+// ACTIONABLE diagnostics — every problem names the offending path and the fix —+// so a third-party MCP server adopting the shape (or a three.ws tool self-checking+// its own output) can correct it. Free, read-only, and crypto-clean: it carries+// no payment, wallet, coin, or token surface, so it drops cleanly into the free+// OpenAI track. The validation core lives in api/_lib/spatial-mcp.js and is shared+// with the emitting tools so the gate and the emitters never drift.++import { validateSpatialArtifact, SPATIAL_MCP_VERSION } from '../../_lib/spatial-mcp.js';++const SPEC_URL = 'https://three.ws/specs/spatial-mcp';++export const toolDefs = [+ {+ name: 'validate_spatial_response',+ title: 'Validate a Spatial MCP 3D artifact',+ annotations: {+ readOnlyHint: true, // pure check — creates and mutates nothing+ destructiveHint: false,+ idempotentHint: true, // same payload → same verdict+ openWorldHint: false, // fully local; no external calls+ },+ description:+ 'Check whether a structured-content payload conforms to the open Spatial MCP artifact shape — the ' ++ 'standard for returning a live, interactive 3D scene as a first-class MCP tool result (scene GLB, camera, ' ++ 'environment, animation, AR handoff, interaction affordances). Returns valid/invalid plus actionable ' ++ `errors and warnings (each naming the field and the fix), not just a boolean. Spec version ${SPATIAL_MCP_VERSION}. ` ++ 'Use it to conform a third-party 3D tool result to the shape so any Spatial-MCP renderer can display it.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ required: ['artifact'],+ properties: {+ artifact: {+ type: 'object',+ description: 'The Spatial MCP artifact to validate (the structuredContent a 3D tool returns, or one you are building).',+ },+ },+ },+ async handler(args) {+ const result = validateSpatialArtifact(args?.artifact);+ const errLines = result.errors.map((e) => ` • ${e.path}: ${e.message}`);+ const warnLines = result.warnings.map((w) => ` • ${w.path}: ${w.message}`);+ const text = result.valid+ ? `Conformant Spatial MCP artifact (v${result.version || SPATIAL_MCP_VERSION}).` ++ (warnLines.length ? `\nWarnings:\n${warnLines.join('\n')}` : '')+ : `Not conformant. Fix these:\n${errLines.join('\n')}` ++ (warnLines.length ? `\nWarnings:\n${warnLines.join('\n')}` : '');+ return {+ content: [{ type: 'text', text }],+ structuredContent: {+ valid: result.valid,+ specVersion: SPATIAL_MCP_VERSION,+ spec: SPEC_URL,+ version: result.version,+ errors: result.errors,+ warnings: result.warnings,+ },+ };+ },+ },+];diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex f4ba0ed6d..8c05f109f 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -40,6 +40,7 @@ import { watsonxConfig, watsonxChatComplete } from '../../_lib/watsonx.js';import { createAvatar, storageKeyFor } from '../../_lib/avatars.js';import { putObject } from '../../_lib/r2.js';import { isValidGlbHeader, inspectGlb } from '../../_lib/glb-inspect.js';+import { buildSpatialArtifact } from '../../_lib/spatial-mcp.js';import { env } from '../../_lib/env.js';import {createPersona,@@ -1080,7 +1081,18 @@ export const toolDefs = [},viewerArtifact({ glbUrl: args.glb_url, name: '3D model', options: args }),],- structuredContent: { glb_url: args.glb_url },+ structuredContent: {+ glb_url: args.glb_url,+ // Conformant Spatial MCP artifact (specs/SPATIAL_MCP.md) so any+ // Spatial-MCP renderer can display this model, not just ours.+ spatial: buildSpatialArtifact({+ glbUrl: args.glb_url,+ kind: 'model',+ autoRotate: args.auto_rotate !== false,+ cameraOrbit: typeof args.camera_orbit === 'string' ? args.camera_orbit : undefined,+ viewerUrl: `https://three.ws/viewer?src=${encodeURIComponent(args.glb_url)}`,+ }),+ },};},},diff --git a/api/_okx3d/rest-services.js b/api/_okx3d/rest-services.jsindex 0245b611b..6a50558aa 100644--- a/api/_okx3d/rest-services.js+++ b/api/_okx3d/rest-services.js@@ -89,10 +89,18 @@ function queuedResponse(job, extra = {}) {// Prompt used by text-to-3d-pro — the same single-subject art-director spec// mesh_forge uses (kept in sync with api/_mcp-studio/tools.js).const MESH_DIRECTOR =- "You are a 3D asset art director. Rewrite the user's idea into ONE concise prompt for a text-to-3D " +- 'generator. Describe a SINGLE isolated subject on a plain background, naming form, materials, color, and ' +- 'surface detail. No scenes, no multiple objects, no text or logos, no background. Output ONLY the rewritten ' +- 'prompt as a single line.';+ "You are a 3D asset art director briefing a text-to-3D reconstruction model. Rewrite the user's idea into " ++ 'ONE concise, information-dense prompt that maximizes mesh and texture quality. Cover, in order: (1) the ' ++ 'SINGLE subject and its overall silhouette/proportions, (2) construction — distinct parts, how they join, ' ++ 'any symmetry, (3) materials per part with explicit PBR cues (e.g. brushed steel, matte ceramic, worn ' ++ 'leather, glossy lacquer, rough stone) so surfaces reconstruct with the right roughness/metalness, (4) a ' ++ 'coherent, consistent art style held across the whole subject (pick one: photoreal, stylized, low-poly, ' ++ 'hand-painted — never mix styles), (5) fine surface detail (seams, panel lines, weathering, grain) that ' ++ 'gives the reconstructor texture to latch onto. Always end with these composition constraints so the ' ++ 'reference image reconstructs cleanly: full subject in frame, centered, isolated on a plain neutral ' ++ 'background, one camera angle, even studio lighting, no cropping, no motion blur, no text or watermark, no ' ++ 'collage or multi-view grid, no second subject. Output ONLY the rewritten prompt as a single line — no ' ++ 'preamble, no quotes.';// Humanoid gate for the avatar chain — mirror of the forge_avatar steer in// api/_mcp-studio/tools.js so both surfaces refuse the same obvious objects.diff --git a/api/bnb/babt-check.js b/api/bnb/babt-check.jsnew file mode 100644index 000000000..6f665124b--- /dev/null+++ b/api/bnb/babt-check.js@@ -0,0 +1,75 @@+// GET /api/bnb/babt-check?address=0x...&network=mainnet|testnet+// ---------------------------------------------------------------------------+// Free BABT (Binance Account Bound Token) holder check — a real, on-chain,+// KYC-backed uniqueness signal on BSC. Verified real + third-party-queryable+// 2026-07-08 (docs/bnb-babt-findings.md has the full research writeup + live+// probes). One `eth_call` to a verified public contract; no API key needed.+//+// Response: { address, network, holdsBabt, tokenId, contract, explorer, checkedAt }+// `network` defaults to mainnet, where the real 1.16M+ KYC'd holder base+// lives — pass `network=testnet` only to exercise integration code; testnet+// mints are real but are developer accounts, not KYC'd Binance users.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { hasBabt, BabtCheckError } from '../_lib/bnb/babt.js';+import { isEvmAddress, BNB_CHAINS } from '../_lib/bnb/chains.js';++function normalizeNetworkParam(raw) {+ const v = String(raw || '').trim().toLowerCase();+ if (v === 'testnet' || v === '97' || v === 'bsctestnet') return 'bscTestnet';+ if (v === '' || v === 'mainnet' || v === '56' || v === 'bscmainnet') return 'bscMainnet';+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const address = params.get('address') || '';+ const networkParam = params.get('network');++ if (!address) {+ return error(res, 400, 'bad_request', 'address query param is required (0x-prefixed BSC/EVM address)');+ }+ if (!isEvmAddress(address)) {+ return error(res, 400, 'bad_request', `not a valid BSC/EVM address: ${address.slice(0, 64)}`);+ }+ const network = normalizeNetworkParam(networkParam);+ if (network === null) {+ return error(res, 400, 'bad_request', `unknown network "${networkParam}" — use "mainnet" or "testnet"`);+ }++ try {+ const result = await hasBabt(address, network);+ const explorer = BNB_CHAINS[network].explorer;+ return json(+ res,+ 200,+ {+ ...result,+ explorer: `${explorer}/token/${result.contract}?a=${result.address}`,+ note:+ network === 'bscTestnet'+ ? 'testnet BABT mints are real but belong to developers testing the mint flow, not KYC\'d Binance users — do not treat this as a sybil-resistance signal, only as an integration test.'+ : 'a true result means this address is bound to a Binance-identity-verified account right now; Binance can revoke and re-mint to a different wallet, so this is a point-in-time check, not a permanent identity anchor.',+ },+ { 'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300' },+ );+ } catch (err) {+ if (err instanceof BabtCheckError) {+ return error(res, 502, 'contract_unreachable', 'could not read the BABT contract right now — retry shortly', {+ network: err.network,+ contract: err.contract,+ });+ }+ if (err instanceof TypeError) {+ return error(res, 400, 'bad_request', err.message);+ }+ throw err;+ }+});diff --git a/api/bnb/block-time.js b/api/bnb/block-time.jsnew file mode 100644index 000000000..1cdb1e746--- /dev/null+++ b/api/bnb/block-time.js@@ -0,0 +1,58 @@+// GET /api/bnb/block-time+// ---------------------------------------------------------------------------+// Live BNB Smart Chain block-time proof for the /bnb hub page. Wraps+// `probeBlockTime` from api/_lib/bnb/chains.js (prompt 01) — samples two real+// blocks off a public RPC (with failover) and returns the observed average+// interval. No mock, no hardcoded "0.45s" — the number is measured on every+// cache miss. `target` is the marketing reference (450ms on mainnet, Fermi+// hardfork BEP-619/590) so the client can show "measured vs target" honestly;+// it is null on testnet, which has no published target.+//+// Defaults to bscMainnet because that's the network the 0.45s claim is about+// (00-CONTEXT.md verified fact #3) — pass ?network=bscTestnet to probe the+// write network instead.++import { cors, json, method, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { probeBlockTime, BnbRpcError } from '../_lib/bnb/chains.js';++const TTL_MS = 10_000;+const _cache = new Map(); // network -> { value, expiresAt }++async function build(network) {+ const now = Date.now();+ const hit = _cache.get(network);+ if (hit && hit.expiresAt > now) return hit.value;++ const value = await probeBlockTime(network, 200);+ _cache.set(network, { value, expiresAt: now + TTL_MS });+ return value;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return json(res, 429, { error: 'rate_limited', error_description: 'too many requests' }, { 'cache-control': 'no-store' });++ const p = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;+ const requested = p.get('network');+ const network = requested === 'bscTestnet' || requested === 'testnet' || requested === '97' ? 'bscTestnet' : 'bscMainnet';++ try {+ const payload = await build(network);+ return json(res, 200, payload, {+ 'cache-control': 'public, max-age=5, s-maxage=10, stale-while-revalidate=30',+ });+ } catch (err) {+ const tried = err instanceof BnbRpcError ? err.tried : undefined;+ return error(+ res,+ 502,+ 'upstream_error',+ 'BNB Chain RPC is unavailable right now — retry shortly',+ tried ? { tried } : {},+ );+ }+});diff --git a/api/coin/categories.js b/api/coin/categories.jsnew file mode 100644index 000000000..383c0eb30--- /dev/null+++ b/api/coin/categories.js@@ -0,0 +1,59 @@+// GET /api/coin/categories+// ---------------------------------------------------------------------------+// Crypto category leaderboard for the /categories page. Proxies CoinGecko+// /coins/categories?order=market_cap_desc and shapes each row down to the+// fields the page renders — id, name, market cap, 24h market-cap change, 24h+// volume, and the top-3 coin icons for the avatar stack. Non-finite numbers+// collapse to null so the client never renders NaN. Cached 5 min in-memory+// + CDN, like the sibling coin endpoints.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { geckoFetch } from '../_lib/coingecko.js';++const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);++function shapeCategory(c) {+ return {+ id: c.id,+ name: c.name || c.id,+ market_cap: num(c.market_cap),+ market_cap_change_24h: num(c.market_cap_change_24h),+ volume_24h: num(c.volume_24h),+ top_3_coins: Array.isArray(c.top_3_coins)+ ? c.top_3_coins.filter((u) => typeof u === 'string' && u).slice(0, 3)+ : [],+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ 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 },+ {+ 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1800',+ },+ );+ } catch {+ return error(+ res,+ 502,+ 'upstream_error',+ 'category data is unavailable right now — retry shortly',+ );+ }+});diff --git a/api/coin/derivatives.js b/api/coin/derivatives.jsnew file mode 100644index 000000000..2f414a6b7--- /dev/null+++ b/api/coin/derivatives.js@@ -0,0 +1,72 @@+// GET /api/coin/derivatives+// ---------------------------------------------------------------------------+// Perpetual futures markets for the /derivatives page. Proxies CoinGecko+// `/derivatives?include_tickers=unexpired`, keeps only perpetual contracts,+// coerces the numeric fields (price, funding rate, open interest, 24h volume)+// and returns them sorted by 24h volume, capped at 100. Non-finite numbers+// become null so the client renders an em dash instead of NaN. Cached 60s+// in-memory + CDN.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { geckoFetch } from '../_lib/coingecko.js';++let _cache = null; // { value, expiresAt }+const TTL_MS = 60_000;++const num = (v) => {+ if (v == null || v === '') return null;+ const n = typeof v === 'number' ? v : Number(v);+ return Number.isFinite(n) ? n : null;+};++async function build() {+ const now = Date.now();+ if (_cache && _cache.expiresAt > now) return _cache.value;++ const raw = await geckoFetch('/derivatives?include_tickers=unexpired', { ttlMs: TTL_MS });+ const rows = Array.isArray(raw) ? raw : [];++ const tickers = rows+ .filter((t) => t && t.contract_type === 'perpetual')+ .map((t) => ({+ market: t.market || 'Unknown',+ symbol: t.symbol || '',+ index_id: t.index_id || null,+ price: num(t.price),+ change_24h: num(t.price_percentage_change_24h),+ funding_rate: num(t.funding_rate),+ open_interest: num(t.open_interest),+ volume_24h: num(t.volume_24h),+ }))+ .sort((a, b) => (b.volume_24h ?? 0) - (a.volume_24h ?? 0))+ .slice(0, 100);++ if (!tickers.length) throw new Error('empty derivatives payload');++ const value = { tickers, updated_at: now };+ _cache = { value, expiresAt: now + TTL_MS };+ return value;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ try {+ const payload = await build();+ return json(res, 200, payload, {+ 'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300',+ });+ } catch {+ return error(+ res,+ 502,+ 'upstream_error',+ 'derivatives data is unavailable right now — retry shortly',+ );+ }+});diff --git a/api/coin/exchanges.js b/api/coin/exchanges.jsnew file mode 100644index 000000000..2de3fe7c1--- /dev/null+++ b/api/coin/exchanges.js@@ -0,0 +1,80 @@+// GET /api/coin/exchanges+// ---------------------------------------------------------------------------+// The top crypto exchanges for the /exchanges page. Proxies CoinGecko+// `/exchanges` (ranked by trust score, with 24h BTC volume) and converts each+// venue's BTC volume to USD using the live BTC price so the table can lead with+// a dollar figure. The price fetch is best-effort (Promise.allSettled) — the+// exchange list still renders with a BTC-only volume fallback if it fails.+// Cached 5 min in-memory + CDN.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { geckoFetch } from '../_lib/coingecko.js';++let _cache = null; // { value, expiresAt }+const TTL_MS = 300_000;++const num = (v) => {+ const n = typeof v === 'number' ? v : Number(v);+ return Number.isFinite(n) ? n : null;+};++async function build() {+ const now = Date.now();+ if (_cache && _cache.expiresAt > now) return _cache.value;++ const [exResult, priceResult] = await Promise.allSettled([+ geckoFetch('/exchanges?per_page=100&page=1', { ttlMs: TTL_MS }),+ geckoFetch('/simple/price?ids=bitcoin&vs_currencies=usd', { ttlMs: 60_000 }),+ ]);+ if (exResult.status !== 'fulfilled') throw exResult.reason || new Error('no exchange data');++ const rows = Array.isArray(exResult.value) ? exResult.value : [];+ if (!rows.length) throw new Error('empty exchange payload');++ const btcUsdRaw =+ priceResult.status === 'fulfilled' ? num(priceResult.value?.bitcoin?.usd) : null;+ const btcUsd = btcUsdRaw != null && btcUsdRaw > 0 ? btcUsdRaw : null;++ const exchanges = rows.map((e) => {+ const volBtc = num(e.trade_volume_24h_btc);+ return {+ id: String(e.id ?? ''),+ name: e.name || e.id || 'Unknown exchange',+ image: e.image || null,+ trust_score: num(e.trust_score),+ trust_score_rank: num(e.trust_score_rank),+ volume_24h_btc: volBtc,+ volume_24h_usd: volBtc != null && btcUsd != null ? volBtc * btcUsd : null,+ year_established: num(e.year_established),+ country: e.country || null,+ url: typeof e.url === 'string' && /^https?:\/\//.test(e.url) ? e.url : null,+ };+ });++ const value = { exchanges, btc_usd: btcUsd, updated_at: now };+ _cache = { value, expiresAt: now + TTL_MS };+ return value;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ try {+ const payload = await build();+ return json(res, 200, payload, {+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=900',+ });+ } catch {+ return error(+ res,+ 502,+ 'upstream_error',+ 'exchange data is unavailable right now — retry shortly',+ );+ }+});diff --git a/api/coin/rates.js b/api/coin/rates.jsnew file mode 100644index 000000000..2b65324c0--- /dev/null+++ b/api/coin/rates.js@@ -0,0 +1,93 @@+// GET /api/coin/rates+// ---------------------------------------------------------------------------+// Live fiat exchange rates for the /converter page. Proxies CoinGecko+// /exchange_rates — which quotes every currency as "units per 1 BTC" — and+// slims it to a curated list of major fiat currencies (plus USD as the anchor+// the converter divides through). Each entry carries its display unit symbol+// and its per-BTC value so the client can derive any fiat⇄fiat / fiat⇄USD rate+// without a second call. Cached in-memory 5m + CDN.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { geckoFetch } from '../_lib/coingecko.js';++// Curated fiat set, in display order. USD is always first — it's the anchor the+// converter divides through to turn a per-BTC value into a per-USD rate. The+// rest are the most-traded/most-searched fiats; whichever the upstream returns+// are included, the rest are silently skipped so a currency dropping out of the+// feed never breaks the page.+const CURATED = [+ 'usd',+ 'eur',+ 'gbp',+ 'jpy',+ 'cny',+ 'inr',+ 'krw',+ 'brl',+ 'cad',+ 'aud',+ 'chf',+ 'rub',+ 'try',+ 'mxn',+ 'sgd',+ 'hkd',+ 'aed',+ 'zar',+];++let _cache = null; // { value, expiresAt }+const TTL_MS = 300_000;++async function build() {+ const now = Date.now();+ if (_cache && _cache.expiresAt > now) return _cache.value;++ const raw = await geckoFetch('/exchange_rates', { ttlMs: TTL_MS });+ const rates = raw?.rates;+ if (!rates || typeof rates !== 'object') throw new Error('unexpected upstream payload');++ const fiats = [];+ for (const code of CURATED) {+ const r = rates[code];+ if (!r || r.type !== 'fiat') continue;+ const perBtc = Number(r.value);+ if (!Number.isFinite(perBtc) || perBtc <= 0) continue;+ fiats.push({+ code: code.toUpperCase(),+ name: typeof r.name === 'string' ? r.name : code.toUpperCase(),+ unit: typeof r.unit === 'string' && r.unit.trim() ? r.unit.trim() : '',+ per_btc: perBtc,+ });+ }+ // USD is load-bearing — without it the client can't convert a per-BTC value+ // into a per-USD rate. If the upstream ever omits it, that's an upstream fault.+ if (!fiats.some((f) => f.code === 'USD')) throw new Error('missing USD anchor rate');++ const value = { fiats, updated_at: now };+ _cache = { value, expiresAt: now + TTL_MS };+ return value;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ try {+ const payload = await build();+ return json(res, 200, payload, {+ 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=1800',+ });+ } catch {+ return error(+ res,+ 502,+ 'upstream_error',+ 'exchange rates are unavailable right now — retry shortly',+ );+ }+});diff --git a/api/defi/chains.js b/api/defi/chains.jsnew file mode 100644index 000000000..0f6fcc7dd--- /dev/null+++ b/api/defi/chains.js@@ -0,0 +1,80 @@+// GET /api/defi/chains+// ---------------------------------------------------------------------------+// Cross-chain TVL leaderboard for the /chains page. Fetches DeFiLlama's keyless+// /v2/chains feed (no API key), normalizes each chain to name + TVL + native+// token, computes each chain's share of total TVL, and returns the top 100 by+// TVL plus the whole-market total. Cached 5 min in-memory + CDN. DeFiLlama is+// the data source — see the page's attribution line.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const UPSTREAM = 'https://api.llama.fi/v2/chains';+const TTL_MS = 300_000;++let _cache = null; // { value, expiresAt }++async function build() {+ const now = Date.now();+ if (_cache && _cache.expiresAt > now) return _cache.value;++ const resp = await fetch(UPSTREAM, {+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(10_000),+ });+ if (!resp.ok) throw new Error(`llama ${resp.status}`);+ const raw = await resp.json();+ if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');++ let totalTvl = 0;+ const eligible = [];+ for (const c of raw) {+ const tvl = Number(c?.tvl);+ if (!Number.isFinite(tvl) || tvl <= 0) continue;+ totalTvl += tvl;+ eligible.push(c);+ }++ eligible.sort((a, b) => Number(b.tvl) - Number(a.tvl));++ const chains = eligible.slice(0, 100).map((c) => {+ const tvl = Number(c.tvl);+ return {+ name: typeof c.name === 'string' ? c.name : 'Unknown',+ tvl,+ token_symbol: typeof c.tokenSymbol === 'string' && c.tokenSymbol ? c.tokenSymbol : null,+ share_pct: totalTvl > 0 ? (tvl / totalTvl) * 100 : 0,+ };+ });++ const value = {+ total_tvl: totalTvl,+ chain_count: eligible.length,+ chains,+ updated_at: now,+ };+ _cache = { value, expiresAt: now + TTL_MS };+ return value;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ try {+ const payload = await build();+ return json(res, 200, payload, {+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',+ });+ } catch {+ return error(+ res,+ 502,+ 'upstream_error',+ 'Cross-chain TVL data is unavailable right now — retry shortly',+ );+ }+});diff --git a/api/defi/protocols.js b/api/defi/protocols.jsnew file mode 100644index 000000000..acba36eab--- /dev/null+++ b/api/defi/protocols.js@@ -0,0 +1,96 @@+// GET /api/defi/protocols+// ---------------------------------------------------------------------------+// Top DeFi protocols by TVL for the /defi page. Fetches DeFiLlama's keyless+// /protocols feed (no API key), normalizes each entry to the fields the page+// renders, and returns the top 100 by TVL plus whole-market totals. Cached+// 5 min in-memory + CDN. DeFiLlama is the data source — see the page's+// attribution line.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const UPSTREAM = 'https://api.llama.fi/protocols';+const TTL_MS = 300_000;++let _cache = null; // { value, expiresAt }++const finite = (n) => (Number.isFinite(n) ? n : null);++async function build() {+ const now = Date.now();+ if (_cache && _cache.expiresAt > now) return _cache.value;++ const resp = await fetch(UPSTREAM, {+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(10_000),+ });+ if (!resp.ok) throw new Error(`llama ${resp.status}`);+ const raw = await resp.json();+ if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');++ // Whole-market totals span every protocol with a positive TVL, not just the+ // top 100 we return for the table.+ let totalTvl = 0;+ let protocolCount = 0;+ const eligible = [];+ for (const p of raw) {+ const tvl = Number(p?.tvl);+ if (!Number.isFinite(tvl) || tvl <= 0) continue;+ // DeFiLlama's /protocols feed mixes centralized-exchange reserves+ // (category "CEX") in with real DeFi protocols; a DeFi TVL page must+ // exclude them or Binance/OKX dwarf every actual protocol.+ if (typeof p.category === 'string' && p.category.toUpperCase() === 'CEX') continue;+ totalTvl += tvl;+ protocolCount += 1;+ eligible.push(p);+ }++ eligible.sort((a, b) => Number(b.tvl) - Number(a.tvl));++ const protocols = eligible.slice(0, 100).map((p) => {+ const chains = Array.isArray(p.chains) ? p.chains.filter((c) => typeof c === 'string') : [];+ return {+ name: typeof p.name === 'string' ? p.name : 'Unknown',+ logo: typeof p.logo === 'string' ? p.logo : null,+ symbol: typeof p.symbol === 'string' && p.symbol !== '-' ? p.symbol : null,+ category: typeof p.category === 'string' ? p.category : null,+ chains,+ chain_count: chains.length,+ tvl: Number(p.tvl),+ change_1d: finite(Number(p.change_1d)),+ change_7d: finite(Number(p.change_7d)),+ mcap: finite(Number(p.mcap)),+ };+ });++ const value = {+ total_tvl: totalTvl,+ protocol_count: protocolCount,+ protocols,+ updated_at: now,+ };+ _cache = { value, expiresAt: now + TTL_MS };+ return value;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ try {+ const payload = await build();+ return json(res, 200, payload, {+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',+ });+ } catch {+ return error(+ res,+ 502,+ 'upstream_error',+ 'DeFi protocol data is unavailable right now — retry shortly',+ );+ }+});diff --git a/api/defi/stablecoins.js b/api/defi/stablecoins.jsnew file mode 100644index 000000000..dd9074de4--- /dev/null+++ b/api/defi/stablecoins.js@@ -0,0 +1,101 @@+// GET /api/defi/stablecoins+// ---------------------------------------------------------------------------+// Live stablecoin market-cap board for the /stablecoins page. Reads the free,+// keyless DeFiLlama stablecoins API and reshapes it into a lean, ranked list:+// each pegged asset's circulating supply (denominated in its own peg unit) is+// its on-chain market cap. We surface price (for peg-health), peg mechanism,+// and the chains it lives on. Aggregate market cap sums every finite asset,+// then the list is sorted by size and capped at the top 100. Cached 5m+// in-memory + CDN — the source refreshes on the order of minutes, not seconds.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const UPSTREAM = 'https://stablecoins.llama.fi/stablecoins?includePrices=true';+const TTL_MS = 300_000; // 5 minutes — matches the CDN s-maxage below.+const TOP_N = 100;++let _cache = null; // { value, expiresAt }++// peg_type keeps DeFiLlama's raw token (`peggedUSD`, `peggedEUR`, …) so the+// client can render the pegged currency (USD, EUR) without a lossy remap; the+// "pegged" prefix is stripped for display client-side.+function shape(assets) {+ const rows = [];+ let totalMcap = 0;++ for (const a of assets) {+ if (!a || typeof a !== 'object') continue;+ const pegType = typeof a.pegType === 'string' ? a.pegType : null;+ // Circulating is nested under the asset's own peg unit, e.g.+ // circulating.peggedUSD. No peg type → no way to read it; skip.+ const circulating = pegType && a.circulating ? Number(a.circulating[pegType]) : NaN;+ if (!Number.isFinite(circulating)) continue;++ totalMcap += circulating;++ const price = Number(a.price);+ const chains = Array.isArray(a.chains) ? a.chains.filter((c) => typeof c === 'string') : [];++ rows.push({+ name: typeof a.name === 'string' ? a.name : 'Unknown',+ symbol: typeof a.symbol === 'string' ? a.symbol : '',+ price: Number.isFinite(price) ? price : null,+ peg_type: pegType,+ peg_mechanism: typeof a.pegMechanism === 'string' ? a.pegMechanism : null,+ circulating_usd: circulating,+ chains,+ chain_count: chains.length,+ });+ }++ rows.sort((x, y) => y.circulating_usd - x.circulating_usd);++ return {+ total_mcap: totalMcap,+ count: rows.length,+ stablecoins: rows.slice(0, TOP_N),+ updated_at: Date.now(),+ };+}++async function build() {+ const now = Date.now();+ if (_cache && _cache.expiresAt > now) return _cache.value;++ const resp = await fetch(UPSTREAM, {+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(10_000),+ });+ if (!resp.ok) throw new Error(`llama ${resp.status}`);++ const body = await resp.json();+ const assets = Array.isArray(body?.peggedAssets) ? body.peggedAssets : null;+ if (!assets) throw new Error('unexpected upstream shape');++ const value = shape(assets);+ _cache = { value, expiresAt: now + TTL_MS };+ return value;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ try {+ const payload = await build();+ return json(res, 200, payload, {+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',+ });+ } catch {+ return error(+ res,+ 502,+ 'upstream_error',+ 'stablecoin data is unavailable right now — retry shortly',+ );+ }+});diff --git a/api/forge.js b/api/forge.jsindex 334e06c25..ea5af9ba4 100644--- a/api/forge.js+++ b/api/forge.js@@ -94,6 +94,17 @@ import {} from './_lib/credits.js';import { markProviderCooldown, providersInCooldown } from './_lib/provider-health.js';import { sanitizeJobError } from './_lib/provider-job-error.js';+import { normalizeForgeOptions, providerReconstructParams, summarizeForgeOptions } from './_lib/forge-options.js';+import { bindJobToOptions, optionsForJob } from './_lib/forge-job-options.js';+import {+ forgeResultCacheKey,+ getCachedForgeResult,+ putCachedForgeResult,+ bindJobToCacheKey,+ cacheKeyForJob,+} from './_lib/forge-cache.js';+import { shouldRetryForQuality } from './_lib/glb-quality.js';+import { directPrompt, originFromReq } from './_mcp-studio/forge-client.js';// Circuit-breaker key + window for the free NVIDIA NIM TRELLIS text→3D lane. The// hosted NVCF gateway can degrade so a submit neither completes nor hands back a@@ -529,6 +540,20 @@ async function startJob(req, res) {const isImageMode = imageUrls.length > 0;const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';+ // Optional, additive output controls (seed, output_format/compression,+ // texture_size, target_polycount) — see _lib/forge-options.js. Every field is+ // off by default, so a request that never sends them behaves exactly as+ // before. An explicitly-present but invalid value is a 400 with an actionable+ // message; an absent field is never an error.+ const opts = normalizeForgeOptions(body);+ if (opts.errors.length) {+ return json(res, 400, {+ error: 'invalid_options',+ errors: opts.errors,+ message: opts.errors.map((e) => e.message).join(' '),+ });+ }+// Resolve the generation path + tier + backend BEFORE the rate check so the// limiter can be lane-aware. The free NVIDIA NIM lane (draft, no vendor spend)// gets a generous fail-open bucket; the paid Replicate/BYOK lanes keep the@@ -622,6 +647,43 @@ async function startJob(req, res) {}};+ // Content-addressed result cache (see _lib/forge-cache.js): a text→3D request+ // on a platform-keyed lane (never BYOK — that spends the caller's own account,+ // so it must never be replayed to a stranger) can be served instantly from a+ // prior identical generation instead of re-running the GPU pipeline. Captured+ // once, before any lane-failover churn reassigns `backendId` below, so the+ // same cache key is used to both look up and (on completion) store this+ // request's result — a failover to a different lane just means a miss, never+ // a wrong hit. `force_regenerate: true` skips the read (a fresh run is still+ // written back, keeping the cache warm). High tier is paid/gated per caller+ // and is never cached, matching the module's own privacy boundary.+ const cacheEligible = !isImageMode && tier.id !== 'high' && BACKENDS[backendId]?.byok === false;+ const forceRegenerate = body?.force_regenerate === true;+ const cacheKey = cacheEligible+ ? forgeResultCacheKey({ path, tier, backend: backendId, prompt, options: opts })+ : null;+ if (cacheKey && !forceRegenerate) {+ const cached = await getCachedForgeResult(cacheKey);+ if (cached) {+ return json(res, 200, {+ job_id: null,+ creation_id: null,+ status: 'done',+ glb_url: cached.glb_url,+ durable: true,+ cached: true,+ cached_at: cached.cached_at,+ mode: 'text_to_3d',+ path: cached.path || path,+ tier: cached.tier || tier.id,+ backend: cached.backend || backendId,+ prompt: prompt || null,+ quality: cached.quality || null,+ options: opts.hasOptions ? summarizeForgeOptions(opts) : undefined,+ });+ }+ }+// $THREE hold-to-access gate (Token Utility v1) — the High tier (200k poly +// PBR, textured) is the platform's premium quality tier. It now runs on a// free-for-us engine (HuggingFace Hunyuan3D) like every other tier, so this isdiff --git a/api/insights/revenue-vision.js b/api/insights/revenue-vision.jsdeleted file mode 100644index 3db4688e6..000000000--- a/api/insights/revenue-vision.js+++ /dev/null@@ -1,266 +0,0 @@-// INTERNAL-USE ONLY; not an agent product. De-listed from the x402 discovery-// catalog (api/wk.js) in the 2026-07 overhaul: the x402 demo pages consume it.-// The route stays live for those consumers; do not re-add it to the catalog.-// GET /api/insights/revenue-vision-//-// Paid endpoint cataloged by the CDP x402 Bazaar (agentic.market) and the-// pay-skills registry. For $0.001 USDC the server hands the caller's-// mission_brief to Claude and returns a structured-// { power_mode, insight, recommended_move, confidence } object. Buyers pay-// programmatically with @x402/fetch — no API keys.-//-// Networks: Base mainnet (EIP-3009 + Permit2 sibling) and Solana mainnet-// (USDC). verifyPayment / settlePayment in x402-spec.js routes per-network:-// Base via X402_FACILITATOR_URL_BASE and Solana via X402_FACILITATOR_URL_SOLANA-// (PayAI by default). The Solana entry is omitted when X402_PAY_TO_SOLANA is-// unset so the 402 challenge stays valid.--import { wrap, cors, error } from '../_lib/http.js';-import {- send402,- verifyPayment,- settlePayment,- encodePaymentResponseHeader,- buildExactRequirements,- resolveResourceUrl,- buildBazaarSchema,-} from '../_lib/x402-spec.js';-import { env } from '../_lib/env.js';-import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';-import {- PAYMENT_IDENTIFIER,- checkCache,- extractIdFromHeader,- hashPaymentProof,- hashRequestPayload,- paymentIdentifierExtension,- storeResponse,- writeCachedResponse,- writeConflict,-} from '../_lib/x402/payment-identifier-server.js';-import { withService } from '../_lib/x402/bazaar-helpers.js';--const ROUTE = '/api/insights/revenue-vision';--const ROUTE_DESCRIPTION =- 'Revenue Vision — agentic growth analysis for AI buyers. Hand over a mission_brief ' +- '(a free-text growth question or hypothesis) and get back a single prioritized next-best ' +- 'tactical move, a specific data-grounded insight, and an honestly-calibrated confidence ' +- 'rating. Powered by Claude. Pay-per-call in USDC on Base mainnet.';--const DISCOVERY_INPUT_EXAMPLE = {- agent_codename: 'ledger-bot',- power_request: 'revenue-vision',- mission_brief: 'Find the highest-converting buyer segment this week.',-};--const DISCOVERY_INPUT_SCHEMA = {- $schema: 'https://json-schema.org/draft/2020-12/schema',- type: 'object',- required: ['agent_codename', 'power_request', 'mission_brief'],- properties: {- agent_codename: {- type: 'string',- description: 'Caller agent name for attribution and rate-limit telemetry.',- },- power_request: {- type: 'string',- enum: ['revenue-vision'],- description: 'Power mode requested. Currently only "revenue-vision".',- },- mission_brief: {- type: 'string',- minLength: 4,- maxLength: 4000,- description: 'Free-text growth question or hypothesis to analyze.',- },- },-};--const DISCOVERY_OUTPUT_EXAMPLE = {- power_mode: 'revenue-vision',- insight:- 'Developer teams at 10–50 employees convert 2.4x better than enterprise prospects on the current funnel.',- recommended_move:- 'Shift 30% of the paid-acquisition budget to builder-focused onboarding campaigns this sprint.',- confidence: 'high',-};--const DISCOVERY_OUTPUT_SCHEMA = {- $schema: 'https://json-schema.org/draft/2020-12/schema',- type: 'object',- required: ['power_mode', 'insight', 'recommended_move', 'confidence'],- properties: {- power_mode: { type: 'string', enum: ['revenue-vision'] },- insight: {- type: 'string',- description: 'A specific, data-grounded observation about the mission.',- },- recommended_move: {- type: 'string',- description: 'A single tactical action the caller should take next.',- },- confidence: { type: 'string', enum: ['high', 'medium', 'low'] },- },-};--const ROUTE_BAZAAR = {- discoverable: true,- info: {- input: {- type: 'http',- method: 'GET',- queryParams: DISCOVERY_INPUT_EXAMPLE,- queryParamsSchema: DISCOVERY_INPUT_SCHEMA,- },- output: { type: 'json', example: DISCOVERY_OUTPUT_EXAMPLE },- },- // Bazaar meta-schema describing the {input, output} envelope (NOT the raw- // response body). buildBazaarSchema nests DISCOVERY_OUTPUT_SCHEMA under- // schema.properties.output.properties.example, which is exactly where the- // AgentCash / x402scan discovery validators read it from. Setting `schema`- // to the raw output schema instead makes those validators report the input- // and output schemas as missing (extensions.bazaar.schema.properties.input- // and .output absent), so this must mirror the other paid routes.- schema: buildBazaarSchema({- method: 'GET',- queryParamsSchema: DISCOVERY_INPUT_SCHEMA,- outputSchema: DISCOVERY_OUTPUT_SCHEMA,- }),-};--function buildRequirements(resourceUrl) {- // Solana-first accepts, Base gated on baseSettleable() — see buildExactRequirements.- return buildExactRequirements(resourceUrl);-}--const SYSTEM_PROMPT =- 'You are Revenue Vision, an agentic growth analyst. Reply with a single JSON object ' +- 'exactly matching the schema {"power_mode":"revenue-vision","insight":string,"recommended_move":string,"confidence":"high"|"medium"|"low"}. ' +- 'The insight should be specific and quantitative when possible. The recommended_move should be one concrete tactical action. ' +- 'Calibrate confidence honestly: "high" only when you can defend the claim, otherwise "medium" or "low". ' +- 'No prose, no markdown, no preamble.';--async function callLlm(missionBrief, agentCodename) {- const { text } = await llmComplete({- system: SYSTEM_PROMPT,- user: `Caller agent: ${agentCodename}\nMission brief: ${missionBrief}\n\nReturn the JSON object only.`,- maxTokens: 800,- });- const match = text.match(/\{[\s\S]*\}/);- const parsed = JSON.parse(match ? match[0] : text);- const allowedConfidence = new Set(['high', 'medium', 'low']);- return {- power_mode: 'revenue-vision',- insight: String(parsed.insight || '').trim(),- recommended_move: String(parsed.recommended_move || '').trim(),- confidence: allowedConfidence.has(parsed.confidence) ? parsed.confidence : 'medium',- };-}--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (req.method !== 'GET') {- res.setHeader('allow', 'GET');- return error(res, 405, 'method_not_allowed', 'use GET');- }-- const resourceUrl = resolveResourceUrl(req, ROUTE);- const requirements = buildRequirements(resourceUrl);- const service = withService({- serviceName: 'three.ws Revenue Vision',- tags: ['ai', 'analysis', 'growth', 'insight', 'claude'],- });- const challenge = {- resourceUrl,- accepts: requirements,- description: ROUTE_DESCRIPTION,- bazaar: ROUTE_BAZAAR,- extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },- serviceName: service.serviceName,- tags: service.tags,- iconUrl: service.iconUrl,- };-- const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];- if (!paymentHeader) return await send402(res, challenge);-- // USE-15: idempotency cache lookup before paying for /verify.- const paymentId = extractIdFromHeader(paymentHeader);- const payloadHash = hashRequestPayload({- method: req.method,- url: req.url,- body: null,- });- const paymentHash = hashPaymentProof(paymentHeader);- if (paymentId) {- const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });- if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);- if (lookup.kind === 'conflict') {- return writeConflict(res, {- route: ROUTE,- attemptedHash: lookup.attemptedHash,- existingHash: lookup.existingHash,- reason: lookup.reason,- });- }- }-- let verified;- try {- verified = await verifyPayment({ paymentHeader, requirements });- } catch (err) {- if (err.status === 402) return await send402(res, { ...challenge, error: err.message });- return error(res, err.status || 502, err.code || 'verify_failed', err.message);- }-- const agentCodename = String(req.query?.agent_codename || '').trim();- const powerRequest = String(req.query?.power_request || '').trim();- const missionBrief = String(req.query?.mission_brief || '').trim();-- if (!agentCodename || agentCodename.length > 120)- return error(res, 400, 'invalid_agent_codename', 'agent_codename is required (≤120 chars)');- if (powerRequest !== 'revenue-vision')- return error(res, 400, 'invalid_power_request', 'power_request must be "revenue-vision"');- if (missionBrief.length < 4 || missionBrief.length > 4000)- return error(res, 400, 'invalid_mission_brief', 'mission_brief must be 4–4000 chars');-- let result;- try {- result = await callLlm(missionBrief, agentCodename);- } catch (err) {- if (err instanceof LlmUnavailableError) {- return error(res, 503, 'llm_unavailable', 'revenue vision is not available right now');- }- return error(res, err.status || 502, err.code || 'upstream_error', err.message);- }-- let settled;- try {- settled = await settlePayment({ verified });- } catch (err) {- return error(res, err.status || 502, err.code || 'settle_failed', err.message);- }-- const paymentResponseHeader = encodePaymentResponseHeader(settled);- const contentType = 'application/json; charset=utf-8';- const body = JSON.stringify(result);-- res.setHeader('x-payment-response', paymentResponseHeader);- res.setHeader('cache-control', 'no-store');- res.setHeader('content-type', contentType);- res.end(body);-- if (paymentId) {- await storeResponse({- route: ROUTE,- paymentId,- payloadHash,- paymentHash,- status: 200,- body,- contentType,- paymentResponseHeader,- });- }-});diff --git a/api/openapi-json.js b/api/openapi-json.jsindex 07db443bd..19207e5b8 100644--- a/api/openapi-json.js+++ b/api/openapi-json.js@@ -591,45 +591,6 @@ export default wrap(async (req, res) => {},},},- '/api/insights/revenue-vision': {- get: {- operationId: 'insights_revenue_vision',- summary: 'Paid: Claude-powered next-best-move for a mission brief',- description:- 'Pay $0.001 USDC to receive a single prioritized next-best move, a data-grounded insight, and an honestly-calibrated confidence rating for the supplied mission brief.',- parameters: [- {- name: 'agent_codename',- in: 'query',- required: true,- schema: { type: 'string' },- },- {- name: 'power_request',- in: 'query',- required: true,- description:- 'Analysis mode. Currently only "revenue-vision" is available; the parameter is required so additional modes can be added without a breaking change.',- schema: { type: 'string', enum: ['revenue-vision'] },- },- {- name: 'mission_brief',- in: 'query',- required: true,- schema: { type: 'string', minLength: 4, maxLength: 4000 },- },- ],- responses: {- 200: { description: 'Next-best-move JSON' },- 400: { description: 'Missing or invalid parameters' },- 402: { description: 'Payment Required (x402)' },- },- 'x-payment-info': {- price: { mode: 'fixed', currency: 'USD', amount: '0.001' },- protocols: X402_PROTOCOLS,- },- },- },'/api/x402/permit2-paid-demo': {get: {operationId: 'x402_permit2_paid_demo',diff --git a/api/v1/_catalog.js b/api/v1/_catalog.jsindex 3b7b47454..94499702f 100644--- a/api/v1/_catalog.js+++ b/api/v1/_catalog.js@@ -162,4 +162,19 @@ export const CATALOG = [address: 'string — base58 Solana mint address (required; EVM 0x… returns 400)',},},+ {+ id: 'v1.resolve',+ method: 'GET',+ path: '/api/v1/resolve',+ auth: 'public',+ summary:+ 'Free name resolution — a high-frequency agent primitive. Resolve a .eth name to its ' ++ 'Ethereum address via ENS, or a .sol name to its Solana owner via SNS; reverse-resolve an ' ++ 'address back to its primary name in either direction. No key, no wallet; 30/min per IP.',+ params: {+ name: 'string — a name ending in .eth (ENS) or .sol (SNS) to resolve (required unless address is passed)',+ address: 'string — 0x… Ethereum or base58 Solana address to reverse-resolve (required unless name is passed)',+ chain: 'string — "ethereum" | "solana", optional hint validated against address (auto-detected from format when omitted)',+ },+ },];diff --git a/api/v1/_providers.js b/api/v1/_providers.jsindex c63b00d88..790423105 100644--- a/api/v1/_providers.js+++ b/api/v1/_providers.js@@ -18,16 +18,29 @@// applyKey (headers, url, key) => void — places a key where the upstream wants it// endpoints array of endpoint descriptors:// id url-safe slug (second path segment)-// method 'GET' | 'POST'+// method 'GET' | 'POST' — the CALLER-facing verb the aggregator front+// door requires (api/v1/x/[...slug].js rejects any other verb).+// upstreamMethod optional; only set when the upstream verb differs from+// `method` — e.g. a caller-side GET that drives a POST-only+// JSON-RPC upstream (see the `solana` provider below). Handled+// in api/_lib/aggregator.js (`executeUpstream`): when set to+// 'POST', the endpoint's `body()` builder receives the+// caller's query params (a GET has no caller body to forward).// path string, or (query) => string for path params// query (query) => object of upstream query params (GET)-// body (body) => object forwarded as the upstream JSON body (POST)+// body (body) => object forwarded as the upstream JSON body (POST,+// or as the caller's query params when `upstreamMethod` lifts+// a caller-side GET to an upstream POST)// transform (data) => normalized response (default: passthrough)+// free optional { perMin, perDay } — unauthenticated per-IP quota+// served before the x402 402 challenge kicks in// priceAtomics x402 price in USDC atomics (6 decimals; "1000" = $0.001)// scope three.ws OAuth scope required for the plan-billing path// summary one line for discovery// params documented inputs for discovery+import { env } from '../_lib/env.js';+function required(value, name) {const v = value == null ? '' : String(value).trim();if (!v) {@@ -39,6 +52,117 @@ function required(value, name) {return v;}+// ── DexScreener helpers ──────────────────────────────────────────────────────++// Cap a comma-separated address list at `cap` entries (DexScreener's own+// /latest/dex/tokens/ limit is 30) — trims whitespace, drops empties.+function capAddressList(csv, cap = 30) {+ return csv+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)+ .slice(0, cap)+ .join(',');+}++// DexScreener pairs are large (~30 fields incl. boosts/presale/social info);+// slim to the fields an agent actually reasons over. Shared by token/search/pair.+function slimDexPair(p) {+ if (!p || typeof p !== 'object') return null;+ return {+ chainId: p.chainId ?? null,+ dexId: p.dexId ?? null,+ pairAddress: p.pairAddress ?? null,+ baseToken: p.baseToken+ ? { address: p.baseToken.address ?? null, name: p.baseToken.name ?? null, symbol: p.baseToken.symbol ?? null }+ : null,+ quoteToken: p.quoteToken ? { symbol: p.quoteToken.symbol ?? null } : null,+ priceUsd: p.priceUsd ?? null,+ priceNative: p.priceNative ?? null,+ liquidity: { usd: p.liquidity?.usd ?? null },+ fdv: p.fdv ?? null,+ marketCap: p.marketCap ?? null,+ volume: { h24: p.volume?.h24 ?? null },+ priceChange: { h1: p.priceChange?.h1 ?? null, h6: p.priceChange?.h6 ?? null, h24: p.priceChange?.h24 ?? null },+ txns: { h24: p.txns?.h24 ?? null },+ pairCreatedAt: p.pairCreatedAt ?? null,+ url: p.url ?? null,+ };+}++// token/search/pair all return `{ schemaVersion, pairs: [...] }` — slim + sort+// by liquidity desc + cap so one call never ships a multi-MB payload.+function slimDexPairs(data, cap) {+ const pairs = Array.isArray(data?.pairs) ? data.pairs : [];+ return pairs+ .map(slimDexPair)+ .filter(Boolean)+ .sort((a, b) => (b.liquidity?.usd || 0) - (a.liquidity?.usd || 0))+ .slice(0, cap);+}++// profiles/boosts are flat arrays of the same shape; slim to the identity ++// social fields agents actually use.+function slimDexProfile(entry) {+ if (!entry || typeof entry !== 'object') return null;+ return {+ chainId: entry.chainId ?? null,+ tokenAddress: entry.tokenAddress ?? null,+ description: entry.description ?? null,+ links: Array.isArray(entry.links) ? entry.links : [],+ };+}++function slimDexProfileList(data, cap = 30) {+ return Array.isArray(data) ? data.slice(0, cap).map(slimDexProfile).filter(Boolean) : [];+}++// ── Solana JSON-RPC helpers ──────────────────────────────────────────────────++// Solana RPC URL — same env resolution the rest of the platform uses+// (api/_lib/env.js SOLANA_RPC_URL: configured Helius/QuickNode/Triton URL, or+// the public mainnet endpoint). Computed once at module load per the registry+// contract — a deploy that sets SOLANA_RPC_URL later needs a redeploy to pick+// it up, same as every other provider `base`.+const SOLANA_RPC_BASE = env.SOLANA_RPC_URL;++function rpcBody(method, params) {+ return { jsonrpc: '2.0', id: 1, method, params };+}++// Solana JSON-RPC returns errors as HTTP 200 with an `error` envelope — surface+// that as a real HTTP error (never as a 200 payload) before any transform runs.+// -32602/-32601/-32600 are caller mistakes (bad address, bad method/params);+// everything else (rate limits, internal errors) maps to a proxy 502.+function rpcResult(data) {+ if (data && typeof data === 'object' && data.error) {+ const code = data.error.code;+ const isCallerFault = code === -32602 || code === -32601 || code === -32600;+ const e = new Error(data.error.message || 'Solana RPC error');+ e.status = isCallerFault ? 400 : 502;+ e.code = isCallerFault ? 'rpc_invalid_request' : 'rpc_upstream_error';+ e.detail = data.error;+ throw e;+ }+ return data && typeof data === 'object' ? data.result : undefined;+}++function rpcNotFound(message, code) {+ const e = new Error(message);+ e.status = 404;+ e.code = code;+ throw e;+}++// p50/p75/p95/max over a numeric array — nearest-rank method (deterministic,+// no interpolation), sorted ascending internally so callers can pass raw order.+function percentiles(values) {+ const sorted = [...values].sort((a, b) => a - b);+ if (!sorted.length) return { p50: 0, p75: 0, p95: 0, max: 0 };+ const at = (p) => sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)];+ return { p50: at(50), p75: at(75), p95: at(95), max: sorted[sorted.length - 1] };+}+export const PROVIDERS = [{id: 'coingecko',@@ -63,6 +187,8 @@ export const PROVIDERS = [include_24hr_change: q.include_24hr_change,include_market_cap: q.include_market_cap,}),+ // Keyless CoinGecko public tier — generous free quota, funnel-sized.+ free: { perMin: 30, perDay: 2000 },priceAtomics: '1000',scope: 'agents:read',summary: 'Spot price for one or more coins in any fiat/crypto.',@@ -85,6 +211,7 @@ export const PROVIDERS = [page: Number(q.page) || 1,price_change_percentage: q.price_change_percentage,}),+ free: { perMin: 30, perDay: 2000 },priceAtomics: '2000',scope: 'agents:read',summary: 'Ranked market data (price, market cap, volume, change) per coin.',@@ -96,6 +223,157 @@ export const PROVIDERS = [page: 'page number (default 1)',},},+ {+ id: 'coin',+ method: 'GET',+ // Verified live 2026-07-08: /coins/{id} with the four heavy flags off+ // still returns a full market_data block + a per-language description.+ path: (q) => `/coins/${encodeURIComponent(required(q.id, 'id'))}`,+ query: () => ({+ localization: 'false',+ tickers: 'false',+ community_data: 'false',+ developer_data: 'false',+ }),+ // Full response is heavy (per-currency market_data + multi-language+ // descriptions); keep only USD market essentials + a truncated English+ // description so one call stays small.+ transform: (data) => {+ if (!data || typeof data !== 'object') return data;+ const md = data.market_data || {};+ const usd = (obj) => (obj && typeof obj === 'object' ? obj.usd : undefined);+ const description = typeof data.description?.en === 'string' ? data.description.en.slice(0, 500) : null;+ return {+ id: data.id,+ symbol: data.symbol,+ name: data.name,+ description,+ market_cap_rank: data.market_cap_rank,+ price_usd: usd(md.current_price),+ ath_usd: usd(md.ath),+ ath_change_percentage: usd(md.ath_change_percentage),+ atl_usd: usd(md.atl),+ atl_change_percentage: usd(md.atl_change_percentage),+ market_cap_usd: usd(md.market_cap),+ fully_diluted_valuation_usd: usd(md.fully_diluted_valuation),+ total_volume_usd: usd(md.total_volume),+ circulating_supply: md.circulating_supply,+ total_supply: md.total_supply,+ max_supply: md.max_supply,+ price_change_percentage_24h: md.price_change_percentage_24h,+ price_change_percentage_7d: md.price_change_percentage_7d,+ price_change_percentage_30d: md.price_change_percentage_30d,+ last_updated: md.last_updated,+ };+ },+ free: { perMin: 20, perDay: 1500 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Full market snapshot for one coin — price, ATH/ATL, supply, multi-window change, truncated description.',+ params: { id: 'CoinGecko coin id, e.g. "solana" (required)' },+ },+ {+ id: 'trending',+ method: 'GET',+ // Verified live 2026-07-08: /search/trending → { coins, nfts, categories }.+ path: '/search/trending',+ query: () => ({}),+ transform: (data) => {+ if (!data || typeof data !== 'object') return { coins: [], categories: [] };+ const coins = Array.isArray(data.coins)+ ? data.coins.map((c) => ({+ id: c?.item?.id,+ symbol: c?.item?.symbol,+ name: c?.item?.name,+ market_cap_rank: c?.item?.market_cap_rank,+ price_btc: c?.item?.price_btc,+ }))+ : [];+ const categories = Array.isArray(data.categories)+ ? data.categories.map((c) => ({+ id: c?.id,+ name: c?.name,+ slug: c?.slug,+ coins_count: c?.coins_count,+ market_cap_usd: c?.data?.market_cap,+ }))+ : [];+ return { coins, categories };+ },+ free: { perMin: 20, perDay: 1500 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Top trending searched coins and hot categories right now.',+ params: {},+ },+ {+ id: 'token-price',+ method: 'GET',+ // Verified live 2026-07-08: /simple/token_price/solana?contract_addresses=…+ path: (q) => `/simple/token_price/${encodeURIComponent(q.platform || 'solana')}`,+ query: (q) => ({+ contract_addresses: required(q.addresses, 'addresses'),+ vs_currencies: q.vs_currencies || 'usd',+ }),+ free: { perMin: 20, perDay: 1500 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Spot price for one or more token contract addresses on a given chain (default Solana).',+ params: {+ platform: 'CoinGecko asset platform id, e.g. "solana" or "ethereum" (default "solana")',+ addresses: 'comma-separated contract addresses, e.g. "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" (required)',+ vs_currencies: 'comma-separated quote currencies (default "usd")',+ },+ },+ {+ id: 'global',+ method: 'GET',+ // Verified live 2026-07-08: /global → { data: { ... } }.+ path: '/global',+ query: () => ({}),+ transform: (data) => {+ const d = data?.data || {};+ return {+ active_cryptocurrencies: d.active_cryptocurrencies,+ markets: d.markets,+ total_market_cap_usd: d.total_market_cap?.usd,+ total_volume_usd: d.total_volume?.usd,+ btc_dominance: d.market_cap_percentage?.btc,+ eth_dominance: d.market_cap_percentage?.eth,+ market_cap_change_percentage_24h_usd: d.market_cap_change_percentage_24h_usd,+ updated_at: d.updated_at,+ };+ },+ free: { perMin: 20, perDay: 1500 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Global crypto market snapshot — total market cap/volume, BTC/ETH dominance, active coin count.',+ params: {},+ },+ {+ id: 'ohlc',+ method: 'GET',+ // Verified live 2026-07-08: /coins/{id}/ohlc?vs_currency=usd&days=1 →+ // [[time_ms, open, high, low, close], …].+ path: (q) => `/coins/${encodeURIComponent(required(q.id, 'id'))}/ohlc`,+ query: (q) => ({+ vs_currency: q.vs_currency || 'usd',+ days: [1, 7, 14, 30].includes(Number(q.days)) ? String(Number(q.days)) : '1',+ }),+ transform: (data) =>+ Array.isArray(data)+ ? data.map(([t, o, h, l, c]) => ({ t, o, h, l, c }))+ : [],+ free: { perMin: 20, perDay: 1500 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'OHLC candles for one coin over 1/7/14/30 days.',+ params: {+ id: 'CoinGecko coin id, e.g. "solana" (required)',+ vs_currency: 'quote currency (default "usd")',+ days: 'candle window: 1, 7, 14, or 30 (default 1)',+ },+ },],},{@@ -130,6 +408,8 @@ export const PROVIDERS = [})).sort((a, b) => (b.tvl || 0) - (a.tvl || 0)): data,+ // Keyless DefiLlama public tier — generous free quota, funnel-sized.+ free: { perMin: 30, perDay: 2000 },priceAtomics: '1000',scope: 'agents:read',summary: 'All DeFi protocols with current TVL, ranked.',@@ -141,11 +421,155 @@ export const PROVIDERS = [path: (q) => `/tvl/${encodeURIComponent(required(q.protocol, 'protocol'))}`,query: () => ({}),transform: (data) => ({ tvl_usd: typeof data === 'number' ? data : Number(data) }),+ free: { perMin: 30, perDay: 2000 },priceAtomics: '1000',scope: 'agents:read',summary: 'Current total value locked (USD) for a single protocol.',params: { protocol: 'DefiLlama protocol slug, e.g. "uniswap" (required)' },},+ {+ id: 'chains',+ method: 'GET',+ // Verified live 2026-07-08: /v2/chains → flat array of every tracked chain.+ path: '/v2/chains',+ query: () => ({}),+ transform: (data) =>+ Array.isArray(data)+ ? data+ .map((c) => ({ name: c.name, tvl: c.tvl, tokenSymbol: c.tokenSymbol, chainId: c.chainId }))+ .sort((a, b) => (b.tvl || 0) - (a.tvl || 0))+ : [],+ free: { perMin: 30, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Every chain DefiLlama tracks, with current TVL, ranked.',+ params: {},+ },+ {+ id: 'protocol',+ method: 'GET',+ // Verified live 2026-07-08: /protocol/{slug} → a HUGE object (full daily+ // TVL history per chain since inception); slim hard.+ path: (q) => `/protocol/${encodeURIComponent(required(q.slug, 'slug'))}`,+ query: () => ({}),+ transform: (data) => {+ if (!data || typeof data !== 'object') return data;+ const series = Array.isArray(data.tvl) ? data.tvl.slice(-30) : [];+ return {+ name: data.name,+ category: data.category,+ chains: data.chains,+ current_chain_tvls_usd: data.currentChainTvls,+ tvl_usd: series.map((p) => ({ date: p.date, tvl: p.totalLiquidityUSD })),+ mcap_usd: data.mcap,+ };+ },+ free: { perMin: 30, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'One protocol: category, per-chain current TVL, and the last 30 points of its total TVL series.',+ params: { slug: 'DefiLlama protocol slug, e.g. "uniswap" (required)' },+ },+ {+ id: 'chain-tvl',+ method: 'GET',+ // Verified live 2026-07-08: /v2/historicalChainTvl/{chain} → full daily+ // series since inception; slim to the last 90 points.+ path: (q) => `/v2/historicalChainTvl/${encodeURIComponent(required(q.chain, 'chain'))}`,+ query: () => ({}),+ transform: (data) =>+ Array.isArray(data) ? data.slice(-90).map((p) => ({ date: p.date, tvl: p.tvl })) : [],+ free: { perMin: 30, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Last 90 days of historical total TVL for one chain.',+ params: { chain: 'DefiLlama chain name, e.g. "Solana" (required)' },+ },+ ],+ },+ {+ id: 'llama-prices',+ name: 'DefiLlama Prices',+ category: 'crypto-market-data',+ // Sibling API on its own base — separate provider so the descriptor `base`+ // stays a single static URL per the registry contract.+ base: 'https://coins.llama.fi',+ requiresKey: false,+ envVar: null,+ byokHeader: null,+ applyKey: () => {},+ endpoints: [+ {+ id: 'current',+ method: 'GET',+ // Verified live 2026-07-08: /prices/current/{chain:address,…} →+ // { coins: { "chain:address": { decimals, symbol, price, timestamp, confidence } } }.+ path: (q) => `/prices/current/${encodeURIComponent(required(q.coins, 'coins'))}`,+ query: () => ({}),+ transform: (data) => {+ const coins = data?.coins;+ if (!coins || typeof coins !== 'object') return {};+ const out = {};+ for (const [key, v] of Object.entries(coins)) {+ if (!v || typeof v !== 'object') continue;+ out[key] = {+ price: v.price,+ symbol: v.symbol,+ decimals: v.decimals,+ timestamp: v.timestamp,+ confidence: v.confidence,+ };+ }+ return out;+ },+ free: { perMin: 30, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Current price for one or more chain:address tokens (DefiLlama coin-price oracle — covers tokens CoinGecko/Jupiter don\'t index).',+ params: {+ coins: 'comma-separated "chain:address" pairs, e.g. "solana:FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" (required)',+ },+ },+ ],+ },+ {+ id: 'llama-stablecoins',+ name: 'DefiLlama Stablecoins',+ category: 'defi-data',+ base: 'https://stablecoins.llama.fi',+ requiresKey: false,+ envVar: null,+ byokHeader: null,+ applyKey: () => {},+ endpoints: [+ {+ id: 'list',+ method: 'GET',+ // Verified live 2026-07-08: /stablecoins?includePrices=true →+ // { peggedAssets: [...] }.+ path: '/stablecoins',+ query: () => ({ includePrices: 'true' }),+ transform: (data) => {+ const assets = data?.peggedAssets;+ if (!Array.isArray(assets)) return [];+ return assets+ .map((a) => ({+ name: a.name,+ symbol: a.symbol,+ pegType: a.pegType,+ price: a.price,+ circulating_usd: a.circulating?.peggedUSD,+ circulating_prev_day_usd: a.circulatingPrevDay?.peggedUSD,+ }))+ .sort((a, b) => (b.circulating_usd || 0) - (a.circulating_usd || 0))+ .slice(0, 50);+ },+ free: { perMin: 30, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Every tracked stablecoin — peg type, price, circulating supply — ranked by circulating USD.',+ params: {},+ },],},{@@ -313,6 +737,326 @@ export const PROVIDERS = [},],},+ {+ id: 'dexscreener',+ name: 'DexScreener',+ category: 'crypto-market-data',+ // Keyless public API — no key, no BYOK header, no envVar. Upstream limits+ // are ~300/min for token/search/pair and ~60/min shared for profiles/+ // boosts; our `free` quotas below stay well under both.+ base: 'https://api.dexscreener.com',+ requiresKey: false,+ envVar: null,+ byokHeader: null,+ applyKey: () => {},+ endpoints: [+ {+ id: 'token',+ method: 'GET',+ // Verified live 2026-07-08: /latest/dex/tokens/{addresses} →+ // { schemaVersion, pairs: [...] } for the $THREE mint.+ path: (q) => `/latest/dex/tokens/${encodeURIComponent(capAddressList(required(q.addresses, 'addresses')))}`,+ query: () => ({}),+ transform: (data) => slimDexPairs(data, 30),+ free: { perMin: 30, perDay: 3000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Live DEX pairs (price, liquidity, volume, txns) for one or more token addresses, deepest liquidity first.',+ params: {+ addresses: 'comma-separated token contract addresses, up to 30, e.g. "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" (required)',+ },+ },+ {+ id: 'search',+ method: 'GET',+ // Verified live 2026-07-08: /latest/dex/search?q= → same { pairs: [...] } shape.+ path: '/latest/dex/search',+ query: (q) => ({ q: required(q.q, 'q') }),+ transform: (data) => slimDexPairs(data, 20),+ free: { perMin: 30, perDay: 3000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Search DEX pairs by token name, symbol, or address, deepest liquidity first.',+ params: {+ q: 'search text — token name, symbol, or address, e.g. "three.ws" or "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" (required)',+ },+ },+ {+ id: 'pair',+ method: 'GET',+ // Verified live 2026-07-08: /latest/dex/pairs/{chain}/{pair} → same { pairs: [...] } shape.+ path: (q) =>+ `/latest/dex/pairs/${encodeURIComponent(required(q.chain, 'chain'))}/${encodeURIComponent(required(q.pair, 'pair'))}`,+ query: () => ({}),+ transform: (data) => slimDexPairs(data, 30),+ free: { perMin: 30, perDay: 3000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Live pair data for one DexScreener chainId + on-chain pair address.',+ params: {+ chain: 'DexScreener chainId, e.g. "solana" (required)',+ pair: 'on-chain pair/pool address, e.g. the $THREE/SOL pumpswap pair "5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z" (required)',+ },+ },+ {+ id: 'profiles',+ method: 'GET',+ // Verified live 2026-07-08: /token-profiles/latest/v1 → flat array.+ path: '/token-profiles/latest/v1',+ query: () => ({}),+ transform: (data) => slimDexProfileList(data, 30),+ free: { perMin: 10, perDay: 500 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Latest DexScreener token profiles — freshly listed projects with descriptions and social links.',+ params: {},+ },+ {+ id: 'boosts',+ method: 'GET',+ // Verified live 2026-07-08: /token-boosts/latest/v1 → flat array.+ path: '/token-boosts/latest/v1',+ query: () => ({}),+ transform: (data) => slimDexProfileList(data, 30),+ free: { perMin: 10, perDay: 500 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Latest DexScreener boosted tokens — paid promotion signal, not an endorsement or ranking by quality.',+ params: {},+ },+ ],+ },+ {+ id: 'solana',+ name: 'Solana RPC',+ category: 'onchain-data',+ // Same env resolution every other Solana caller on the platform uses+ // (api/_lib/env.js) — a configured Helius/QuickNode/Triton URL, or the+ // public mainnet endpoint as a working fallback.+ base: SOLANA_RPC_BASE,+ requiresKey: false,+ envVar: null,+ byokHeader: null,+ applyKey: () => {},+ endpoints: [+ {+ id: 'balance',+ method: 'GET',+ // GET caller-side; the upstream is Solana's single JSON-RPC POST+ // endpoint. See `upstreamMethod` in the descriptor contract above.+ upstreamMethod: 'POST',+ path: '',+ body: (q) => rpcBody('getBalance', [required(q.address, 'address')]),+ // Verified live 2026-07-08: { result: { context, value: <lamports> } }.+ transform: (data) => {+ const result = rpcResult(data);+ const lamports = typeof result?.value === 'number' ? result.value : null;+ return { lamports, sol: lamports != null ? lamports / 1e9 : null };+ },+ free: { perMin: 20, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Native SOL balance of any wallet address.',+ params: {+ address: 'Solana base58 wallet address, e.g. "11111111111111111111111111111111" (required)',+ },+ },+ {+ id: 'token-holdings',+ method: 'GET',+ upstreamMethod: 'POST',+ path: '',+ body: (q) =>+ rpcBody('getTokenAccountsByOwner', [+ required(q.owner, 'owner'),+ { programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' },+ { encoding: 'jsonParsed' },+ ]),+ // Verified live 2026-07-08: { result: { value: [{ pubkey, account: {+ // data: { parsed: { info: { mint, tokenAmount: { amount, decimals,+ // uiAmount } } } } } }] } }.+ transform: (data) => {+ const result = rpcResult(data);+ const value = Array.isArray(result?.value) ? result.value : [];+ return value+ .map((entry) => {+ const info = entry?.account?.data?.parsed?.info;+ const amt = info?.tokenAmount;+ if (!info || !amt) return null;+ return {+ mint: info.mint ?? null,+ amount: amt.amount ?? null,+ decimals: amt.decimals ?? null,+ uiAmount: amt.uiAmount ?? null,+ };+ })+ .filter((t) => t && t.uiAmount)+ .sort((a, b) => (b.uiAmount || 0) - (a.uiAmount || 0));+ },+ free: { perMin: 20, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'SPL token holdings of a wallet (mint, amount, decimals), zero balances filtered, largest first.',+ params: {+ owner: 'Solana base58 wallet address, e.g. "11111111111111111111111111111111" (required)',+ },+ },+ {+ id: 'token-supply',+ method: 'GET',+ upstreamMethod: 'POST',+ path: '',+ body: (q) => rpcBody('getTokenSupply', [required(q.mint, 'mint')]),+ // Verified live 2026-07-08 ($THREE mint): { result: { value: {+ // amount, decimals, uiAmount, uiAmountString } } }.+ transform: (data) => {+ const result = rpcResult(data);+ const v = result?.value;+ if (!v) rpcNotFound('mint not found or not an SPL token', 'mint_not_found');+ return { amount: v.amount ?? null, decimals: v.decimals ?? null, uiAmount: v.uiAmount ?? null };+ },+ free: { perMin: 20, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Total circulating supply of an SPL token mint.',+ params: {+ mint: 'Solana token mint address, e.g. "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" (required)',+ },+ },+ {+ id: 'largest-holders',+ method: 'GET',+ upstreamMethod: 'POST',+ path: '',+ body: (q) => rpcBody('getTokenLargestAccounts', [required(q.mint, 'mint')]),+ // Documented shape (getTokenLargestAccounts, top 20 by protocol limit):+ // { result: { value: [{ address, amount, decimals, uiAmount,+ // uiAmountString }] } }.+ transform: (data) => {+ const result = rpcResult(data);+ const value = Array.isArray(result?.value) ? result.value : [];+ return value+ .slice(0, 20)+ .map((v) => ({ address: v.address ?? null, uiAmount: v.uiAmount ?? null }));+ },+ free: { perMin: 20, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Top 20 holder token-accounts of an SPL token mint by balance.',+ params: {+ mint: 'Solana token mint address, e.g. "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" (required)',+ },+ },+ {+ id: 'transaction',+ method: 'GET',+ upstreamMethod: 'POST',+ path: '',+ body: (q) =>+ rpcBody('getTransaction', [+ required(q.signature, 'signature'),+ { encoding: 'jsonParsed', maxSupportedTransactionVersion: 0 },+ ]),+ // Verified live 2026-07-08 (real $THREE transfer signature): { result: {+ // slot, blockTime, transaction: { message: { accountKeys: [{ pubkey,+ // signer }] }, signatures }, meta: { fee, err, logMessages,+ // preTokenBalances, postTokenBalances } } }. result is null when the+ // signature is unknown/not yet finalized — surfaced as 404, not a+ // payload of nulls.+ transform: (data) => {+ const result = rpcResult(data);+ if (!result) rpcNotFound('transaction not found (unknown signature or not yet finalized)', 'transaction_not_found');+ const meta = result.meta || {};+ const accountKeys = Array.isArray(result.transaction?.message?.accountKeys)+ ? result.transaction.message.accountKeys+ : [];+ const signers = accountKeys.filter((k) => k?.signer).map((k) => k.pubkey);++ // Pre/post SPL token balance deltas keyed by accountIndex+mint — the+ // one number an agent actually wants ("how much moved"), not two+ // snapshots it has to diff itself.+ const byKey = new Map();+ for (const b of Array.isArray(meta.preTokenBalances) ? meta.preTokenBalances : []) {+ byKey.set(`${b.accountIndex}:${b.mint}`, { mint: b.mint, owner: b.owner ?? null, pre: b.uiTokenAmount?.uiAmount ?? 0, post: 0 });+ }+ for (const b of Array.isArray(meta.postTokenBalances) ? meta.postTokenBalances : []) {+ const key = `${b.accountIndex}:${b.mint}`;+ const existing = byKey.get(key);+ if (existing) existing.post = b.uiTokenAmount?.uiAmount ?? 0;+ else byKey.set(key, { mint: b.mint, owner: b.owner ?? null, pre: 0, post: b.uiTokenAmount?.uiAmount ?? 0 });+ }+ const tokenBalanceChanges = [...byKey.values()]+ .map((v) => ({ mint: v.mint, owner: v.owner, delta: (v.post || 0) - (v.pre || 0) }))+ .filter((v) => v.delta !== 0);++ return {+ slot: result.slot ?? null,+ blockTime: result.blockTime ?? null,+ fee: meta.fee ?? null,+ err: meta.err ?? null,+ signers,+ logMessages: Array.isArray(meta.logMessages) ? meta.logMessages.slice(0, 20) : [],+ tokenBalanceChanges,+ };+ },+ free: { perMin: 20, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Confirmed transaction detail by signature — fee, error, signers, log lines, and SPL token balance deltas.',+ params: {+ signature: 'base58 transaction signature (required)',+ },+ },+ {+ id: 'account',+ method: 'GET',+ upstreamMethod: 'POST',+ path: '',+ body: (q) => rpcBody('getAccountInfo', [required(q.address, 'address'), { encoding: 'jsonParsed' }]),+ // Verified live 2026-07-08 ($THREE mint): { result: { value: {+ // owner, lamports, executable, data: { program, parsed: { type } } } } }.+ // result.value is null for an unfunded/nonexistent address.+ transform: (data) => {+ const result = rpcResult(data);+ if (!result?.value) rpcNotFound('account not found (unfunded or nonexistent address)', 'account_not_found');+ const v = result.value;+ return {+ owner: v.owner ?? null,+ lamports: v.lamports ?? null,+ executable: Boolean(v.executable),+ program: v.data?.program ?? null,+ parsedType: v.data?.parsed?.type ?? null,+ };+ },+ free: { perMin: 20, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Account info for any address — owning program, lamports, executable flag, parsed data type.',+ params: {+ address: 'Solana base58 address, e.g. "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" (required)',+ },+ },+ {+ id: 'priority-fees',+ method: 'GET',+ upstreamMethod: 'POST',+ path: '',+ body: () => rpcBody('getRecentPrioritizationFees', []),+ // Verified live 2026-07-08: { result: [{ slot, prioritizationFee }, ...] }+ // for the last ~150 slots.+ transform: (data) => {+ const result = rpcResult(data);+ const fees = Array.isArray(result) ? result.map((r) => Number(r.prioritizationFee) || 0) : [];+ return percentiles(fees);+ },+ free: { perMin: 20, perDay: 2000 },+ priceAtomics: '1000',+ scope: 'agents:read',+ summary: 'Recent prioritization fee landscape (p50/p75/p95/max micro-lamports) over the last ~150 slots.',+ params: {},+ },+ ],+ },];// Flat lookup map: "provider/endpoint" → { provider, endpoint }.@@ -339,6 +1083,7 @@ export function providerCatalog() {price_usdc_atomics: e.priceAtomics,summary: e.summary,params: e.params,+ free: e.free || false,})),}));}diff --git a/api/v1/ai/image.js b/api/v1/ai/image.jsindex 79f98363a..b54b52c0a 100644--- a/api/v1/ai/image.js+++ b/api/v1/ai/image.js@@ -25,7 +25,7 @@ import { buildBazaarSchema } from '../../_lib/x402-spec.js';import { installAccessControl } from '../../_lib/x402/access-control.js';import { withService, declareHttpDiscovery } from '../../_lib/x402/bazaar-helpers.js';import { priceFor } from '../../_lib/x402-prices.js';-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, readBody } from '../../_lib/http.js';import { clientIp } from '../../_lib/rate-limit.js';import { textToImage } from '../../_mcp3d/text-to-image.js';import {@@ -45,6 +45,7 @@ const PRICE_ATOMICS = priceFor('ai-image', '20000'); // $0.02 USDC per image aboconst MAX_PROMPT = 2000;const MIN_PROMPT = 3;const MAX_SEED = 4_294_967_295; // uint32 — the widest seed the flux lanes accept+const MAX_BODY_BYTES = 16_384; // generous ceiling for a { prompt, aspect_ratio, seed } JSON body// ── Bazaar discovery (uniqueness first) ──────────────────────────────────────@@ -248,12 +249,6 @@ async function generateAndRespond({ prompt, aspectRatio, seed }, { free, ip }) {};}-async function readBody(req) {- const chunks = [];- for await (const c of req) chunks.push(c);- return Buffer.concat(chunks).toString('utf8');-}-// ── Paid endpoint (free-quota funnel → x402) ─────────────────────────────────const paidImage = paidEndpoint({@@ -285,7 +280,8 @@ const paidImage = paidEndpoint({}),async handler({ req, bypass }) {- const parsed = parseImageRequest(await readBody(req));+ const buf = await readBody(req, MAX_BODY_BYTES);+ const parsed = parseImageRequest(buf.toString('utf8'));const free = bypass?.reason === 'ai_image_free_daily';return generateAndRespond(parsed, { free, ip: clientIp(req) });},diff --git a/api/v1/market/intel.js b/api/v1/market/intel.jsindex fc85c90d0..639c371ca 100644--- a/api/v1/market/intel.js+++ b/api/v1/market/intel.js@@ -15,8 +15,12 @@ export default defineEndpoint({auth: 'optional',scope: 'agents:read',handler: async ({ query }) => {- if (!aixbtEnabled())- fail(503, 'not_configured', 'market intelligence is not enabled on this deployment');+ // Throw the platform's canonical missing-env error (matches wrap()'s+ // `missingEnv` regex in api/_lib/http.js) so the client actually gets+ // "this endpoint is not configured on this deployment" — a hand-rolled+ // fail(503, 'not_configured', <message>) instead falls into wrap's+ // generic sanitized-5xx branch and the message never reaches the caller.+ if (!aixbtEnabled()) throw new Error('Missing required env var: AIXBT_API_KEY');const g = await limits.aixbtGlobal();if (!g.success) fail(429, 'rate_limited', 'market intelligence is busy — retry shortly');diff --git a/api/v1/market/projects.js b/api/v1/market/projects.jsindex 68296a931..f93d2e7f1 100644--- a/api/v1/market/projects.js+++ b/api/v1/market/projects.js@@ -14,8 +14,9 @@ export default defineEndpoint({auth: 'optional',scope: 'agents:read',handler: async ({ query }) => {- if (!aixbtEnabled())- fail(503, 'not_configured', 'market intelligence is not enabled on this deployment');+ // See api/v1/market/intel.js — thrown as the canonical missing-env error+ // so wrap() names it to the client instead of sanitizing the message away.+ if (!aixbtEnabled()) throw new Error('Missing required env var: AIXBT_API_KEY');const g = await limits.aixbtGlobal();if (!g.success) fail(429, 'rate_limited', 'market intelligence is busy — retry shortly');diff --git a/api/v1/resolve.js b/api/v1/resolve.jsnew file mode 100644index 000000000..38767d4bf--- /dev/null+++ b/api/v1/resolve.js@@ -0,0 +1,152 @@+// GET /api/v1/resolve — free, keyless name resolution across ENS + SNS.+//+// Wraps the platform's existing resolvers instead of reimplementing them:+// - .eth (ENS) → ethers `resolveName` / `lookupAddress` via the shared EVM+// failover provider (api/_lib/evm/rpc.js `evmFallbackProvider`) — the same+// RPC chain api/agents/ens/[name].js already resolves ENS names through.+// - .sol (SNS) → `resolveSnsName` / `reverseLookupAddress` from+// src/solana/sns.js — the exact module api/sns.js and api/sns-subdomain.js+// already share. No Bonfida call is reimplemented here.+//+// Forward: ?name=<x>.eth | ?name=<x>.sol → { name, chain, address, source }+// Reverse: ?address=<addr>[&chain=ethereum|solana] → { address, chain, name, source }+// Reverse only runs the direction the underlying resolver already supports —+// ethers' lookupAddress for ENS, SNS's getFavoriteDomain for SNS — both of+// which the wrapped modules above already implement, so no half-built+// placeholder direction is exposed.+//+// A miss is a 404 `not_found`, never a 500. An unsupported suffix/address+// format is a 400 naming the two supported suffixes/chains. Public, keyless,+// 30 req/min per IP (api/_lib/rate-limit.js `resolveIp`), 5-minute edge cache+// on hits (misses are never cached).++import { defineEndpoint, fail } from '../_lib/gateway.js';+import { rateLimited } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { isValidSolanaAddress, isValidEvmAddress } from '../_lib/validate.js';+import { resolveSnsName, reverseLookupAddress } from '../../src/solana/sns.js';+import { evmFallbackProvider } from '../_lib/evm/rpc.js';++const ENS_RE = /^(?:[a-z0-9-]+\.)*[a-z0-9-]+\.eth$/i;+const SOL_NAME_RE = /^[a-z0-9-]{1,63}\.sol$/i;+const HIT_CACHE_CONTROL = 'public, max-age=300, s-maxage=300, stale-while-revalidate=60';+const ENS_TIMEOUT_MS = 5000;++// Ethereum mainnet (chainId 1) — ENS is a mainnet-only registry.+async function ensProvider() {+ return evmFallbackProvider(1);+}++async function withEnsTimeout(promise, label) {+ const timeout = new Promise((_, reject) =>+ setTimeout(() => reject(new Error(`${label}_timeout`)), ENS_TIMEOUT_MS),+ );+ return Promise.race([promise, timeout]);+}++async function resolveForward(rawName, res) {+ const name = rawName.toLowerCase();++ if (ENS_RE.test(name)) {+ let address;+ try {+ const provider = await ensProvider();+ address = await withEnsTimeout(provider.resolveName(name), 'ens');+ } catch (err) {+ fail(+ 503,+ 'ens_unavailable',+ err?.message === 'ens_timeout'+ ? 'ENS resolution timed out — retry shortly'+ : 'ENS resolution failed — retry shortly',+ );+ }+ if (!address) fail(404, 'not_found', `${name} did not resolve to an Ethereum address`);+ res.setHeader('cache-control', HIT_CACHE_CONTROL);+ return { name, chain: 'ethereum', address, source: 'ens' };+ }++ if (SOL_NAME_RE.test(name)) {+ const address = await resolveSnsName(name);+ if (!address) fail(404, 'not_found', `${name} did not resolve to a Solana address`);+ res.setHeader('cache-control', HIT_CACHE_CONTROL);+ return { name, chain: 'solana', address, source: 'sns' };+ }++ fail(+ 400,+ 'unsupported_suffix',+ 'name must end in .eth (ENS) or .sol (SNS) — no other suffix is supported',+ );+}++async function resolveReverse(rawAddress, chainHint, res) {+ const isEvm = isValidEvmAddress(rawAddress);+ const isSol = isValidSolanaAddress(rawAddress);++ if (!isEvm && !isSol) {+ fail(400, 'validation_error', 'address must be a 0x… Ethereum address or a base58 Solana address');+ }+ if (chainHint && chainHint !== 'ethereum' && chainHint !== 'solana') {+ fail(400, 'validation_error', 'chain must be "ethereum" or "solana" when passed');+ }+ if (chainHint === 'ethereum' && !isEvm) {+ fail(400, 'validation_error', 'address is not a valid Ethereum address for chain=ethereum');+ }+ if (chainHint === 'solana' && !isSol) {+ fail(400, 'validation_error', 'address is not a valid Solana address for chain=solana');+ }++ if (isEvm) {+ let name;+ try {+ const provider = await ensProvider();+ name = await withEnsTimeout(provider.lookupAddress(rawAddress), 'ens_reverse');+ } catch (err) {+ fail(+ 503,+ 'ens_unavailable',+ err?.message === 'ens_reverse_timeout'+ ? 'ENS reverse resolution timed out — retry shortly'+ : 'ENS reverse resolution failed — retry shortly',+ );+ }+ if (!name) fail(404, 'not_found', `${rawAddress} has no primary ENS name`);+ res.setHeader('cache-control', HIT_CACHE_CONTROL);+ return { address: rawAddress, chain: 'ethereum', name, source: 'ens' };+ }++ const name = await reverseLookupAddress(rawAddress);+ if (!name) fail(404, 'not_found', `${rawAddress} has no primary SNS domain`);+ res.setHeader('cache-control', HIT_CACHE_CONTROL);+ return { address: rawAddress, chain: 'solana', name, source: 'sns' };+}++export default defineEndpoint({+ name: 'v1.resolve',+ method: 'GET',+ auth: 'public',+ handler: async ({ res, query, ip }) => {+ // Dedicated per-IP budget on top of the gateway's shared apiV1 burst guard:+ // both ENS and SNS resolution fan out to real upstreams (RPC / Bonfida) on+ // a cache miss, so this caps a scripted enumeration flood.+ const rl = await limits.resolveIp(ip);+ if (!rl.success) return rateLimited(res, rl, 'name resolution is capped at 30 requests/min per IP');++ const rawName = typeof query.name === 'string' ? query.name.trim() : '';+ const rawAddress = typeof query.address === 'string' ? query.address.trim() : '';+ const chainHint = typeof query.chain === 'string' ? query.chain.trim().toLowerCase() : '';++ if (rawName && rawAddress) {+ fail(400, 'validation_error', 'pass either ?name or ?address, not both');+ }+ if (rawName) return resolveForward(rawName, res);+ if (rawAddress) return resolveReverse(rawAddress, chainHint, res);++ fail(+ 400,+ 'validation_error',+ 'pass ?name=<x>.eth or ?name=<x>.sol to resolve a name, or ?address=<addr> to reverse-resolve one',+ );+ },+});diff --git a/api/v1/x/[...slug].js b/api/v1/x/[...slug].jsindex 6d8c4c30b..7db7c45ee 100644--- a/api/v1/x/[...slug].js+++ b/api/v1/x/[...slug].js@@ -41,6 +41,83 @@ function parseQuery(req) {return q;}+// ── free tier lane ──────────────────────────────────────────────────────────+// An unauthenticated caller (no BYOK key, no three.ws credentials) on an+// endpoint marked `free: { perMin, perDay }` (api/v1/_providers.js) gets a real+// per-IP, per-endpoint quota BEFORE the x402 402 challenge — this is what makes+// "the free crypto API" true instead of marketing copy: `curl+// https://three.ws/api/v1/x/coingecko/price?ids=solana` returns data with zero+// wallet setup. Both windows (burst perMin + funnel-budget perDay) must pass;+// whichever check blocks the request drives the RateLimit-* headers so a client+// backing off learns the window that actually stopped it. Returns true when the+// request was served (caller must return); false means the quota is exhausted+// and the caller should fall through to the existing x402 lane.+async function serveFreeLane({ req, res, provider, endpoint }) {+ const ip = clientIp(req);+ const bucketKey = `${provider.id}:${endpoint.id}:${ip}`;+ const [minResult, dayResult] = await Promise.all([+ limits.apiV1FreeMin(bucketKey, endpoint.free.perMin),+ limits.apiV1FreeDay(bucketKey, endpoint.free.perDay),+ ]);++ res.setHeader('x-free-tier', '1');+ const blocked = !minResult.success || !dayResult.success;+ const headerResult = !minResult.success ? minResult : dayResult;+ setRateLimitHeaders(res, headerResult);++ if (blocked) {+ // Hint header (the 402 challenge body shape is spec-locked by the x402+ // bazaar format, so the "quota resets at T" signal rides a header instead):+ // the caller learns exactly when the free lane reopens, on top of the 402's+ // own "or pay per call / send a three.ws API key" accepts array.+ res.setHeader('x-free-tier-reset', new Date(headerResult.reset).toISOString());+ return false;+ }++ const query = parseQuery(req);+ const body = endpoint.method === 'POST' ? await readJson(req) : undefined;+ // Free lane always runs on the platform's own upstream key (there is no+ // caller credential to resolve one from) — same key source the plan lane+ // uses, just billed differently.+ const { key, source } = resolveUpstreamKey(provider, null);++ const started = Date.now();+ let out;+ try {+ out = await executeUpstream({ provider, endpoint, query, body, apiKey: key });+ } catch (err) {+ recordEvent({+ kind: 'api',+ tool: `v1.x.${provider.id}.${endpoint.id}`,+ status: 'error',+ latencyMs: Date.now() - started,+ meta: { billing: 'free', key_source: source, code: err?.code, ip },+ });+ throw err;+ }++ // Metering: free-lane calls still record a usage event (billing: 'free') so+ // funnel adoption is measurable even though no payment settles.+ recordEvent({+ kind: 'api',+ tool: `v1.x.${provider.id}.${endpoint.id}`,+ status: 'ok',+ latencyMs: Date.now() - started,+ meta: { billing: 'free', key_source: source, ip },+ });++ json(res, 200, {+ data: out,+ _meta: {+ provider: provider.id,+ endpoint: endpoint.id,+ billing: 'free',+ free_remaining: { per_min: minResult.remaining, per_day: dayResult.remaining },+ },+ });+ return true;+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;@@ -54,7 +131,8 @@ export default wrap(async (req, res) => {billing: {byok: 'send your own upstream key via the provider\'s BYOK header — pass-through, no markup',plan: 'authenticate with a three.ws API key / OAuth token — uses the platform key',- x402: 'send no credentials — pay per call in USDC (HTTP 402)',+ free: 'send no credentials on an endpoint marked "free" — a per-IP quota (see each endpoint\'s free.perMin/free.perDay) serves real data with zero setup; X-Free-Tier: 1 + RateLimit-* headers on every response',+ x402: 'send no credentials — pay per call in USDC (HTTP 402), or quota-exhausted free-tier calls fall through here',},providers: providerCatalog(),},@@ -106,6 +184,14 @@ export default wrap(async (req, res) => {}}+ // Free tier: no BYOK key, no three.ws credentials, endpoint marked `free` →+ // serve a real per-IP quota before the 402 challenge. Quota exhausted falls+ // through to the x402 lane below (still !byokKey && !principal).+ if (!byokKey && !principal && endpoint.free) {+ const served = await serveFreeLane({ req, res, provider, endpoint });+ if (served) return;+ }+// No BYOK key and no three.ws credentials → pay-per-call via the x402 rail.if (!byokKey && !principal) return getPaidHandler(provider, endpoint)(req, res);diff --git a/api/x402/agent-bouncer.js b/api/x402/agent-bouncer.jsindex c86d99e71..4f8420e1a 100644--- a/api/x402/agent-bouncer.js+++ b/api/x402/agent-bouncer.js@@ -24,18 +24,15 @@ import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { isUuid } from '../_lib/validate.js';import { vetSolanaAgent } from '../_lib/trust/solana-bouncer.js';+import agentBouncerListing from '../_lib/service-catalog/services/agent-bouncer.js';const ROUTE = '/api/x402/agent-bouncer';-const DESCRIPTION =- 'three.ws Agent Bouncer — the platform door check. Given a three.ws agent_id ' +- 'and an optional trust policy, read the agent’s whole Solana track record ' +- '(confirmed on-chain payments, distinct payers, payment failure rate, ' +- 'distribute/buyback follow-through, signed Solana attestations, and the Club ' +- 'ban/tip ledger) and return an admit/refuse verdict with a door tier ' +- '(newcomer / regular / trusted / vip). Behavioral reputation from real ' +- 'settled Solana actions — not a star rating. Use it to vet a counterparty ' +- 'before paying, hiring, or delegating. Pay-per-call in USDC on Solana or Base.';+// Single source of truth: api/_lib/service-catalog/services/agent-bouncer.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = agentBouncerListing.description;const INPUT_EXAMPLE = {agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',diff --git a/api/x402/agent-reputation.js b/api/x402/agent-reputation.jsindex 530a037ed..ac3775ed3 100644--- a/api/x402/agent-reputation.js+++ b/api/x402/agent-reputation.js@@ -40,18 +40,15 @@ import {decayReportAgentReputation,REPUTATION_FLAG_THRESHOLD,} from '../_lib/trust/solana-bouncer.js';+import agentReputationListing from '../_lib/service-catalog/services/agent-reputation.js';const ROUTE = '/api/x402/agent-reputation';-const DESCRIPTION =- 'Cross-chain Agent Reputation — pay $0.01 USDC to get a deterministic 0–100 ' +- 'trust score for ANY counterparty before you pay, trade, or delegate to it. ' +- 'Accepts a Solana wallet, an EVM wallet, a pump.fun mint, an ERC-8004 agent id, ' +- 'or a three.ws agent_id (auto-detected). Scored from real on-chain evidence — ' +- 'transaction history, age, distinct counterparties, holdings, settlement ' +- 'reliability, prior settled agent payments, and ERC-8004 feedback — with the ' +- 'evidence and caveats returned. Unknown subjects return score:null, not a fake ' +- 'score. Pay-per-call in USDC on Base or Solana mainnet.';+// Single source of truth: api/_lib/service-catalog/services/agent-reputation.js+// is the storefront listing copy — importing it here keeps the live 402+// challenge from drifting from what /.well-known/x402.json and the OKX+// projection advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = agentReputationListing.description;const INPUT_EXAMPLE = { subject: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' };diff --git a/api/x402/animation-download.js b/api/x402/animation-download.jsindex 1756dc334..b3ededf8c 100644--- a/api/x402/animation-download.js+++ b/api/x402/animation-download.js@@ -18,18 +18,18 @@ import { sql } from '../_lib/db.js';import { presignGet } from '../_lib/r2.js';import { error, json } from '../_lib/http.js';import { env } from '../_lib/env.js';+import animationDownloadListing from '../_lib/service-catalog/services/animation-download.js';const ROUTE = '/api/x402/animation-download';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;const PRESIGN_TTL_SECONDS = 60;-const DESCRIPTION =- 'three.ws Animation Bazaar — pay once in USDC to unlock a creator-authored ' +- 'avatar animation as a self-contained animated GLB hosted on R2. Wallets ' +- 'that have already paid can re-download for free by signing in with SIWX ' +- '(CAIP-122). Each clip carries its own price and creator payout address; the ' +- 'response returns a short-lived presigned URL the client uses to fetch the ' +- 'GLB directly from R2.';+// Single source of truth:+// api/_lib/service-catalog/services/animation-download.js is the storefront+// listing copy — importing it here keeps the live 402 challenge from drifting+// from what /.well-known/x402.json and the OKX projection advertise (same+// pattern as forge.js → forge-listing.js).+const DESCRIPTION = animationDownloadListing.description;const INPUT_EXAMPLE = { id: '00000000-0000-0000-0000-000000000000' };diff --git a/api/x402/asset-download.js b/api/x402/asset-download.jsindex 50ffd5354..22c2c7ed6 100644--- a/api/x402/asset-download.js+++ b/api/x402/asset-download.js@@ -16,15 +16,15 @@ import { sql } from '../_lib/db.js';import { presignGet } from '../_lib/r2.js';import { error } from '../_lib/http.js';import { env } from '../_lib/env.js';+import assetDownloadListing from '../_lib/service-catalog/services/asset-download.js';const ROUTE = '/api/x402/asset-download';-const DESCRIPTION =- 'three.ws Asset Bazaar — pay once in USDC to unlock a 3D asset (GLB, ' +- 'avatar, or accessory) hosted on R2. Wallets that have already paid can ' +- 're-download for free by signing in with SIWX (CAIP-122). Each asset has ' +- 'its own price and creator payout address; the response carries a short- ' +- 'lived presigned URL the client uses to fetch the file directly from R2.';+// Single source of truth: api/_lib/service-catalog/services/asset-download.js+// is the storefront listing copy — importing it here keeps the live 402+// challenge from drifting from what /.well-known/x402.json and the OKX+// projection advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = assetDownloadListing.description;const INPUT_EXAMPLE = { slug: 'pole-dancer-rumba' };diff --git a/api/x402/bazaar-feed.js b/api/x402/bazaar-feed.jsindex b923fd9b3..7ac99b524 100644--- a/api/x402/bazaar-feed.js+++ b/api/x402/bazaar-feed.js@@ -28,6 +28,7 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { sql } from '../_lib/db.js';+import bazaarFeedListing from '../_lib/service-catalog/services/bazaar-feed.js';const ROUTE = '/api/x402/bazaar-feed';@@ -40,13 +41,11 @@ const PRESSURE_PCT = Math.max(0.05, Number(process.env.X402_BAZAAR_TREND_PRESSUR// Cap on how many movers to return per side (the long tail isn't actionable).const TOP_N = 25;-const DESCRIPTION =- 'Bazaar Feed - pay $0.001 USDC per call for two live views of the x402 service' +- ' marketplace. filter "new"/"active": newest service listings (id, name, price,' +- ' networks, tags, first_seen) plus category rollup and listing-velocity signal' +- ' (spike/active/quiet). filter "price_trends": 24h price-movement across all' +- ' tracked services - trending up/down/stable and net market pressure as' +- ' bullish/bearish/neutral. Live data from the platform bazaar index.';+// Single source of truth: api/_lib/service-catalog/services/bazaar-feed.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = bazaarFeedListing.description;const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',diff --git a/api/x402/billboard.js b/api/x402/billboard.jsindex 5b2148694..e62dfb0b1 100644--- a/api/x402/billboard.js+++ b/api/x402/billboard.js@@ -17,16 +17,16 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { setPlacement, sanitizeImageUrl, sanitizeCaption, isValidCoin, SLOT_HOURS } from '../_lib/billboard-store.js';+import billboardListing from '../_lib/service-catalog/services/billboard.js';const ROUTE = '/api/x402/billboard';-const DESCRIPTION =- 'three.ws coin worlds — feature your content on a 3D world’s billboard. ' +- `Pay once to hold the framed panel behind spawn for ${SLOT_HOURS} hours: ` +- 'pass the coin-world mint plus an image URL and/or a short caption. The ' +- '/temporary coin world renders your placement in place of its default ' +- 'content for everyone who walks in until the slot expires. It is a paid ' +- 'content canvas, not an ad unit — nothing is targeted or tracked.';+// Single source of truth: api/_lib/service-catalog/services/billboard.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js). SLOT_HOURS is still+// imported above for the actual placement TTL the handler writes.+const DESCRIPTION = billboardListing.description;const INPUT_EXAMPLE = {coin: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',diff --git a/api/x402/club-cover.js b/api/x402/club-cover.jsindex 14b88e770..81cddfe93 100644--- a/api/x402/club-cover.js+++ b/api/x402/club-cover.js@@ -27,6 +27,7 @@ import {membershipSnapshot,} from '../_lib/club/cover-pass.js';import { coverRevenueSummary } from '../_lib/club/cover-revenue.js';+import clubCoverListing from '../_lib/service-catalog/services/club-cover.js';const ROUTE = '/api/x402/club-cover';@@ -34,13 +35,11 @@ const ROUTE = '/api/x402/club-cover';// so the USDC door here and the $THREE door (api/club/cover-three.js) issue an// identical pass.-const DESCRIPTION =- 'three.ws Pole Club — pay the cover charge to get past the door. Pay ' +- '$0.01 USDC and the bouncer checks the paying wallet on-chain against the ' +- 'club ban list and its prior club activity, then issues an entry pass with ' +- 'a door tier (newcomer / regular / vip). Banned wallets are turned away. ' +- 'The /club page consumes the pass to drop the velvet rope. Pay-per-call in ' +- 'USDC on Solana mainnet.';+// Single source of truth: api/_lib/service-catalog/services/club-cover.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = clubCoverListing.description;const INPUT_EXAMPLE = {};diff --git a/api/x402/cosmetic-purchase.js b/api/x402/cosmetic-purchase.jsindex ecb4977ca..a2b3dd8e2 100644--- a/api/x402/cosmetic-purchase.js+++ b/api/x402/cosmetic-purchase.js@@ -26,15 +26,16 @@ import { env } from '../_lib/env.js';import { getCosmetic, priceUsdcAtomicsOf } from '../_lib/cosmetics.js';import { grantCosmeticOwnership, normalizeAccountId } from '../_lib/cosmetics-ownership.js';import { recordSaleAndSplit, isMint } from '../_lib/cosmetics-economy.js';+import cosmeticPurchaseListing from '../_lib/service-catalog/services/cosmetic-purchase.js';const ROUTE = '/api/x402/cosmetic-purchase';-const DESCRIPTION =- 'three.ws Avatar Shop — pay once in USDC to unlock a premium avatar cosmetic ' +- '(skin or emote) for an account. Pay on Base or Solana; the cosmetic is ' +- 'recorded to the buyer-specified account and is wearable across /play and ' +- '/walk. Wallets that already purchased an item re-confirm for free by signing ' +- 'in with SIWX. Price varies by rarity.';+// Single source of truth:+// api/_lib/service-catalog/services/cosmetic-purchase.js is the storefront+// listing copy — importing it here keeps the live 402 challenge from drifting+// from what /.well-known/x402.json and the OKX projection advertise (same+// pattern as forge.js → forge-listing.js).+const DESCRIPTION = cosmeticPurchaseListing.description;const INPUT_EXAMPLE = { id: 'skin-midnight', account: 'g_5f3c9a21b8' };diff --git a/api/x402/crypto-intel.js b/api/x402/crypto-intel.jsindex ef5e9a434..47d37bc91 100644--- a/api/x402/crypto-intel.js+++ b/api/x402/crypto-intel.js@@ -72,6 +72,9 @@ const OUTPUT_SCHEMA = {};const BAZAAR = {+ // De-listed per the 2026-07-08 storefront cleanup (prompt 18) — stays live+ // for the /agent-exchange demo; not agent-discoverable via the bazaar.+ discoverable: false,description: DESCRIPTION,useCases: ['market signal', 'agent-to-agent payment demo', 'crypto intel'],input: {diff --git a/api/x402/dance-tip.js b/api/x402/dance-tip.jsindex 87bbd14de..18307b2da 100644--- a/api/x402/dance-tip.js+++ b/api/x402/dance-tip.js@@ -188,7 +188,10 @@ const OUTPUT_SCHEMA = {};const BAZAAR = {- discoverable: true,+ // De-listed per the 2026-07-08 storefront cleanup (prompt 18) — the route+ // stays live for /club + the Saloon Kid NPC, but the flag itself (not just+ // wk.js's catalog omission) now matches the "internal-use only" header above.+ discoverable: false,info: {input: { type: 'http', method: 'GET', queryParams: INPUT_EXAMPLE },output: { type: 'json', example: OUTPUT_EXAMPLE },diff --git a/api/x402/embody.js b/api/x402/embody.jsnew file mode 100644index 000000000..e2324d4ef--- /dev/null+++ b/api/x402/embody.js@@ -0,0 +1,268 @@+// POST /api/x402/embody+//+// Give your agent a 3D body — one paid x402 call returns a rigged, animated,+// talking avatar plus a one-tag embed for any website. The only embodiment+// endpoint in the x402 ecosystem. $1 USDC, no account.+//+// An external agent on any framework pays $1 USDC and gets an embeddable,+// animated, voiced presence: a text prompt (or a reference image) plus a name in;+// a rigged GLB, a durable persona that reloads by id in any future session, a+// voice, and a copy-paste <iframe> embed out.+//+// Contract+// POST { name, prompt?, image_url?, personality?, voice? }+// name required, ≤64 chars+// prompt text description of the body (exactly one of prompt|image_url)+// image_url reference image URL (exactly one of prompt|image_url)+// personality optional flavor text stored on the persona (≤600 chars)+// voice optional TTS voice id (see /api/tts/voices); defaults to 'nova'+// → 200 {+// agent_id, glb_url, viewer_url, profile_url, embed_html, reload_url,+// voice, rigged, name+// }+//+// Design note: this is SYNCHRONOUS and settles on delivery, not a submit-then-poll+// job. The buyer is only charged when a finished body is returned — a failed or+// timed-out generation never settles (payment is verified but not captured). This+// is the more consumer-fair reading of the prompt's job-based sketch: no orphaned+// paid jobs, and the returned bundle is complete on the single call. The heavy+// lifting reuses the SAME free NVIDIA TRELLIS generate → auto-rig chain the 3D+// Studio uses (api/_mcp-studio/forge-client.js) and the durable persona store+// behind the embodiment embed (api/_lib/persona-store.js) — no new pipeline.+//+// Price: priceFor('embody', '1000000') = $1.00 USDC. Solana + Base.++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { priceFor } from '../_lib/x402-prices.js';+import { originFromReq, generate, rig, viewerUrl } from '../_mcp-studio/forge-client.js';+import { createPersona } from '../_lib/persona-store.js';+import { buildEmbedUrl } from '../_lib/embodiment-artifact.js';+import { TTS_VOICE_IDS, DEFAULT_VOICE } from '../_lib/tts-voices.js';++const ROUTE = '/api/x402/embody';++const NAME_MAX = 64;+const PROMPT_MAX = 600;+const PERSONALITY_MAX = 600;++const 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. POST { name, prompt | image_url, personality?, voice? } and get back ' ++ '{ agent_id, glb_url, viewer_url, profile_url, embed_html, voice }. The body is a ' ++ 'durable persona that reloads by id in any future session. $1 USDC, no account. ' ++ 'Generation failures never settle — you are only charged when a finished body is returned.';++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['name'],+ oneOf: [{ required: ['prompt'] }, { required: ['image_url'] }],+ properties: {+ name: { type: 'string', minLength: 1, maxLength: NAME_MAX, description: 'Display name for the agent body.' },+ prompt: { type: 'string', minLength: 1, maxLength: PROMPT_MAX, description: 'Text description of the avatar to generate.' },+ image_url: { type: 'string', format: 'uri', description: 'Reference image URL to reconstruct into 3D.' },+ personality: { type: 'string', maxLength: PERSONALITY_MAX, description: 'Optional flavor text stored on the persona.' },+ voice: { type: 'string', enum: TTS_VOICE_IDS, description: `TTS voice id. Default ${DEFAULT_VOICE}.` },+ },+ additionalProperties: false,+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['agent_id', 'glb_url', 'viewer_url', 'profile_url', 'embed_html', 'voice', 'rigged'],+ properties: {+ agent_id: { type: 'string', description: 'Durable persona id — reload the same body with GET /api/mcp3d/persona?id=<agent_id>.' },+ glb_url: { type: 'string', description: 'The rigged, animation-ready GLB.' },+ viewer_url: { type: 'string', description: 'Interactive 3D viewer for the body.' },+ profile_url: { type: 'string', description: 'The hosted embodiment presence page (renders + speaks + emotes).' },+ embed_html: { type: 'string', description: 'One-tag <iframe> embed to drop into any website.' },+ reload_url: { type: 'string', description: 'JSON endpoint that reloads the persona by id.' },+ voice: { type: 'string' },+ rigged: { type: 'boolean', description: 'True when the auto-rig succeeded; false when the endpoint fell back to the un-rigged mesh.' },+ name: { type: 'string' },+ },+};++const OUTPUT_EXAMPLE = {+ agent_id: 'persona_8f2a1c9d4b',+ glb_url: 'https://pub-xxxx.r2.dev/personas/persona_8f2a1c9d4b.glb',+ viewer_url: 'https://three.ws/viewer?src=https%3A%2F%2Fpub-xxxx.r2.dev%2Fpersonas%2Fpersona_8f2a1c9d4b.glb',+ profile_url: 'https://three.ws/embodiment/embed?persona=persona_8f2a1c9d4b',+ embed_html: '<iframe src="https://three.ws/embodiment/embed?persona=persona_8f2a1c9d4b" width="480" height="640" loading="lazy" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; fullscreen; xr-spatial-tracking" allowfullscreen></iframe>',+ reload_url: 'https://three.ws/api/mcp3d/persona?id=persona_8f2a1c9d4b',+ voice: 'nova',+ rigged: true,+ name: 'Nova Scout',+};++const BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'json', example: { name: 'Nova Scout', prompt: 'a friendly explorer in a teal jumpsuit', voice: 'nova' }, schema: INPUT_SCHEMA },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({ method: 'POST', bodySchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),+};++// Embed iframe sizing — a portrait frame suits a standing avatar.+const EMBED_W = 480;+const EMBED_H = 640;++async function readBody(req) {+ if (req.body && typeof req.body === 'object') return req.body;+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8').trim();+ if (!raw) return {};+ return JSON.parse(raw);+}++// Throw a 400 with a stable code — runs after verify but BEFORE settle, so a+// rejected body is never charged.+function bad(code, message, extra = {}) {+ const err = new Error(message);+ err.status = 400;+ err.code = code;+ Object.assign(err, extra);+ return err;+}++function validate(body) {+ const name = typeof body?.name === 'string' ? body.name.trim() : '';+ if (!name) throw bad('invalid_name', 'name is required');+ if (name.length > NAME_MAX) throw bad('invalid_name', `name must be ≤${NAME_MAX} characters`);++ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';+ const imageUrl = typeof body?.image_url === 'string' ? body.image_url.trim() : '';+ if (!prompt && !imageUrl) throw bad('missing_input', 'provide either a prompt or an image_url');+ if (prompt && imageUrl) throw bad('ambiguous_input', 'provide exactly one of prompt or image_url, not both');+ if (prompt && prompt.length > PROMPT_MAX) throw bad('invalid_prompt', `prompt must be ≤${PROMPT_MAX} characters`);+ if (imageUrl) {+ let u;+ try { u = new URL(imageUrl); } catch { throw bad('invalid_image_url', 'image_url must be a valid URL'); }+ if (u.protocol !== 'https:' && u.protocol !== 'http:') throw bad('invalid_image_url', 'image_url must be http(s)');+ }++ const personality = typeof body?.personality === 'string' ? body.personality.trim().slice(0, PERSONALITY_MAX) : '';++ let voice = DEFAULT_VOICE;+ if (body?.voice !== undefined && body?.voice !== null && body?.voice !== '') {+ if (typeof body.voice !== 'string' || !TTS_VOICE_IDS.includes(body.voice)) {+ throw bad('invalid_voice', `voice must be one of: ${TTS_VOICE_IDS.join(', ')}`, { valid_voices: TTS_VOICE_IDS });+ }+ voice = body.voice;+ }++ return { name, prompt, imageUrl, personality, voice };+}++// Run the generate → rig chain and mint a durable persona. Exported for tests+// (dependency-injected forge/persona so the pipeline can be exercised offline).+export async function runEmbodyChain(+ { base, name, prompt, imageUrl, personality, voice },+ { generateFn = generate, rigFn = rig, createPersonaFn = createPersona } = {},+) {+ // 1. Mesh generation (free NVIDIA TRELLIS lane; image→3D reconstructs).+ const gen = await generateFn(+ base,+ {+ ...(prompt ? { prompt } : {}),+ ...(imageUrl ? { imageUrls: [imageUrl] } : {}),+ aspect: '1:1',+ tier: 'draft',+ },+ { timeoutEnv: 'EMBODY_GEN_TIMEOUT_MS' },+ );+ if (gen?._timedOut) {+ const e = new Error('avatar generation timed out before a body was produced');+ e.status = 504; e.code = 'generation_timeout'; e.stage = 'generate';+ throw e;+ }+ if (!gen?.glb_url) {+ const e = new Error('avatar generation did not return a model');+ e.status = 502; e.code = 'generation_failed'; e.stage = 'generate';+ throw e;+ }++ // 2. Auto-rig (humanoid skeleton + skin weights). A rig failure/timeout is a+ // graceful degrade to the un-rigged mesh — never a hard failure, never a+ // T-pose (the mesh itself renders fine; it just isn't skeleton-driven yet).+ let riggedGlb = gen.glb_url;+ let rigged = false;+ try {+ const rigResult = await rigFn(base, gen.glb_url, { timeoutEnv: 'EMBODY_RIG_TIMEOUT_MS' });+ if (rigResult && !rigResult._timedOut && rigResult.glb_url) {+ riggedGlb = rigResult.glb_url;+ rigged = true;+ }+ } catch {+ // Keep the mesh; rigged stays false. Surfaced to the caller in `rigged`.+ }++ // 3. Durable persona — copies the GLB into our own storage and stores the+ // name/voice/personality so the body reloads by id in any future session.+ const persona = await createPersonaFn({+ glbUrl: riggedGlb,+ name,+ voice,+ sourcePrompt: prompt || `image:${imageUrl}`,+ look: { rigged, style: personality || null },+ });++ return { persona, glbUrl: riggedGlb, rigged, voice, name };+}++function buildBundle(base, { persona, glbUrl, rigged, voice, name }) {+ const personaView = { persona_id: persona.id, glb_url: persona.glb_url || glbUrl, name };+ const profileUrl = buildEmbedUrl({ persona: personaView, state: 'idle' });+ const embedHtml =+ `<iframe src="${profileUrl}" width="${EMBED_W}" height="${EMBED_H}" ` ++ `loading="lazy" style="border:0;border-radius:12px;max-width:100%" ` ++ `allow="autoplay; fullscreen; xr-spatial-tracking" allowfullscreen ` ++ `sandbox="allow-scripts allow-same-origin allow-popups"></iframe>`;+ return {+ agent_id: persona.id,+ glb_url: personaView.glb_url,+ viewer_url: viewerUrl(base, personaView.glb_url),+ profile_url: profileUrl,+ embed_html: embedHtml,+ reload_url: `${base}/api/mcp3d/persona?id=${encodeURIComponent(persona.id)}`,+ voice,+ rigged,+ name,+ };+}++export default paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor('embody', '1000000'),+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Embodiment',+ tags: ['3d', 'avatar', 'embed', 'agent', 'embodiment'],+ }),++ async handler({ req }) {+ let body;+ try {+ body = await readBody(req);+ } catch {+ throw bad('invalid_json', 'request body must be valid JSON');+ }+ // Validation runs here (post-verify, pre-settle) so a bad request is never charged.+ const input = validate(body);++ const base = originFromReq(req);+ const chain = await runEmbodyChain({ base, ...input });+ return buildBundle(base, chain);+ },+});++export { validate as _validate, buildBundle as _buildBundle };diff --git a/api/x402/fact-check.js b/api/x402/fact-check.jsindex 457c0d26f..aa9d59e5c 100644--- a/api/x402/fact-check.js+++ b/api/x402/fact-check.js@@ -1,6 +1,8 @@-// INTERNAL-USE ONLY; not an agent product. De-listed from the x402 discovery-// catalog (api/wk.js) in the 2026-07 overhaul: the fact-checker app (src/fact-checker-app.js) and the Sheriff Boone NPC in /play buy through it.-// The route stays live for those consumers; do not re-add it to the catalog.+// Re-listed per the 2026-07-08 storefront cleanup (prompt 18): sourced+// verdicts with cryptographic attestations are a defensible agent product —+// the 2026-07 overhaul's "internal-use only" de-listing is superseded. The+// fact-checker app (src/fact-checker-app.js) and the Sheriff Boone NPC in+// /play also buy through this same route.// POST /api/x402/fact-check//// Real-Time Fact Checker — paid x402 micropayment endpoint.diff --git a/api/x402/llm-proxy.js b/api/x402/llm-proxy.jsindex b86892862..a367aad04 100644--- a/api/x402/llm-proxy.js+++ b/api/x402/llm-proxy.js@@ -23,6 +23,7 @@ import { buildBazaarSchema } from '../_lib/x402-spec.js';import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { llmComplete } from '../_lib/llm.js';+import llmProxyListing from '../_lib/service-catalog/services/llm-proxy.js';const ROUTE = '/api/x402/llm-proxy';@@ -41,14 +42,11 @@ function resolveModelOpts(modelAlias) {return { anthropicModel: String(modelAlias), preferNvidia: false };}-const DESCRIPTION =- 'three.ws LLM Inference Proxy — pay per completion with no API key required. ' +- 'Runs one-shot text prompts through the platform\'s free-first provider chain ' +- '(Groq → OpenRouter → NVIDIA NIM → Anthropic). Response includes measured ' +- 'latency, token counts, and the provider actually used. Ideal for latency ' +- 'benchmarking, agent pipelines, and one-off completions. ' +- 'Model aliases: "fast" (Groq, sub-second) · "smart" (Anthropic Haiku backstop). ' +- 'Price: $0.005 USDC per completion on Base or Solana.';+// Single source of truth: api/_lib/service-catalog/services/llm-proxy.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = llmProxyListing.description;const INPUT_EXAMPLE = {model: 'fast',diff --git a/api/x402/mint-to-mesh-batch.js b/api/x402/mint-to-mesh-batch.jsindex 0a10ae195..4bac2c136 100644--- a/api/x402/mint-to-mesh-batch.js+++ b/api/x402/mint-to-mesh-batch.js@@ -1,6 +1,6 @@-// INTERNAL-USE ONLY; not an agent product. De-listed from the x402 discovery-// catalog (api/wk.js) in the 2026-07 overhaul: the Mei foundry NPC in /play sells it; the real agent-facing text->3D product is Forge (/api/x402/forge).-// The route stays live for those consumers; do not re-add it to the catalog.+// Re-listed per the 2026-07-08 storefront cleanup (prompt 18) — batch sibling+// of mint-to-mesh, same disposition: see api/x402/mint-to-mesh.js for the+// header note superseding the prior "internal-use only" de-listing.// POST /api/x402/mint-to-mesh-batch// body: { mints: ["mint1", "mint2", ...] } (1–10 mints)//diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.jsindex c4daf009b..3ceac5f52 100644--- a/api/x402/mint-to-mesh.js+++ b/api/x402/mint-to-mesh.js@@ -1,6 +1,8 @@-// INTERNAL-USE ONLY; not an agent product. De-listed from the x402 discovery-// catalog (api/wk.js) in the 2026-07 overhaul: the Mei foundry NPC in /play sells it; the real agent-facing text->3D product is Forge (/api/x402/forge).-// The route stays live for those consumers; do not re-add it to the catalog.+// Re-listed per the 2026-07-08 storefront cleanup (prompt 18): turning an+// arbitrary on-chain SPL mint into an instantly renderable, themed 3D asset+// on demand is a real, distinct capability (Forge is prompt-driven generation+// — this is deterministic token-to-mesh rendering). The Mei foundry NPC in+// /play also buys through this same route.// GET /api/x402/mint-to-mesh?mint=<solana-mint>//// Paid endpoint cataloged by the CDP x402 Bazaar (agentic.market) and thediff --git a/api/x402/onchain-identity-verify.js b/api/x402/onchain-identity-verify.jsindex 3ce4e3276..e679df8dc 100644--- a/api/x402/onchain-identity-verify.js+++ b/api/x402/onchain-identity-verify.js@@ -29,17 +29,16 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { verifyClaim } from '../_lib/x402/identity-claim-verify.js';+import onchainIdentityVerifyListing from '../_lib/service-catalog/services/onchain-identity-verify.js';const ROUTE = '/api/x402/onchain-identity-verify';-const DESCRIPTION =- 'Cross-platform On-Chain Identity Verifier — prove any claim that an identity ' +- 'controls an address. `identity` can be an ENS name, an SNS (.sol) name, an EVM ' +- 'or Solana wallet, an ERC-8004 agent id, or a three.ws agent_id; `address` is ' +- 'the contract/mint/wallet it claims. Returns on-chain evidence (deploy tx + ' +- 'deployer, mint/update authority, ENS/SNS resolution, ERC-8004 registration, ' +- 'three.ws deploy record) with verified true/false/unverifiable. Use it as a ' +- 'trust primitive before paying, trading, or delegating to a counterparty agent.';+// Single source of truth:+// api/_lib/service-catalog/services/onchain-identity-verify.js is the+// storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = onchainIdentityVerifyListing.description;export const INPUT_EXAMPLE = {identity: 'vitalik.eth',diff --git a/api/x402/pipeline-gameready.js b/api/x402/pipeline-gameready.jsindex 4cc9f665c..d5065f668 100644--- a/api/x402/pipeline-gameready.js+++ b/api/x402/pipeline-gameready.js@@ -26,6 +26,7 @@ import {persistStageOutput,stageObjectKey,} from '../_lib/pipeline-stage.js';+import pipelineGameReadyListing from '../_lib/service-catalog/services/pipeline-gameready.js';const ROUTE = '/api/x402/pipeline-gameready';const SLUG = 'pipeline-gameready';@@ -39,13 +40,12 @@ const TOPOLOGY_TO_MODE = { quad: 'quad', tri: 'lowpoly' };const POLY_MIN = 1_000;const POLY_MAX = 500_000;-const DESCRIPTION =- '3D Asset Pipeline — Game-Ready: pay $0.03 USDC to make a GLB engine-ready. ' +- 'The mesh is retopologized to a fixed polygon budget (quad QuadriFlow or ' +- 'silhouette-preserving low-poly) with PBR re-baked onto the new topology, so it ' +- 'drops into a real-time engine within budget. POST a public glb_url + ' +- 'poly_budget; get back a durable first-party GLB URL. Pay autonomously in USDC ' +- 'on Solana mainnet.';+// Single source of truth:+// api/_lib/service-catalog/services/pipeline-gameready.js is the storefront+// listing copy — importing it here keeps the live 402 challenge from drifting+// from what /.well-known/x402.json and the OKX projection advertise (same+// pattern as forge.js → forge-listing.js).+const DESCRIPTION = pipelineGameReadyListing.description;export const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',diff --git a/api/x402/pipeline-rembg.js b/api/x402/pipeline-rembg.jsindex 9a365b458..8b3ba0510 100644--- a/api/x402/pipeline-rembg.js+++ b/api/x402/pipeline-rembg.js@@ -25,18 +25,18 @@ import {persistStageOutput,stageObjectKey,} from '../_lib/pipeline-stage.js';+import pipelineRembgListing from '../_lib/service-catalog/services/pipeline-rembg.js';const ROUTE = '/api/x402/pipeline-rembg';const SLUG = 'pipeline-rembg';const VALID_MODELS = new Set(['rmbg2', 'u2net', 'isnet', 'u2net_human_seg', 'silueta']);-const DESCRIPTION =- '3D Asset Pipeline — Background Removal: pay $0.01 USDC to strip the background ' +- 'from an image, returning a transparent PNG. This is the clean reference view ' +- 'image→3D reconstruction needs so it never bakes a room into the mesh. POST a ' +- 'public image_url; get back a durable first-party PNG URL. Pay autonomously in ' +- 'USDC on Solana mainnet.';+// Single source of truth: api/_lib/service-catalog/services/pipeline-rembg.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = pipelineRembgListing.description;export const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',diff --git a/api/x402/pipeline-remesh.js b/api/x402/pipeline-remesh.jsindex 1da8f5efa..2e0df0695 100644--- a/api/x402/pipeline-remesh.js+++ b/api/x402/pipeline-remesh.js@@ -26,6 +26,7 @@ import {persistStageOutput,stageObjectKey,} from '../_lib/pipeline-stage.js';+import pipelineRemeshListing from '../_lib/service-catalog/services/pipeline-remesh.js';const ROUTE = '/api/x402/pipeline-remesh';const SLUG = 'pipeline-remesh';@@ -34,12 +35,11 @@ const VALID_MODES = new Set(['triangle', 'quad', 'lowpoly']);const VALID_OPERATIONS = new Set(['full', 'simplify', 'repair', 'convert']);const VALID_TEXTURE_SIZES = new Set([512, 1024, 2048]);-const DESCRIPTION =- '3D Asset Pipeline — Remesh: pay $0.03 USDC to retopologize a GLB. Triangle, ' +- 'quad, or low-poly remeshing plus repair and decimation to a target face count, ' +- 'with the texture re-baked onto the new topology. POST a public glb_url and ' +- 'options; get back a durable first-party GLB URL. Nowhere else in the x402 ' +- 'ecosystem sells mesh remeshing. Pay autonomously in USDC on Solana mainnet.';+// Single source of truth: api/_lib/service-catalog/services/pipeline-remesh.js+// is the storefront listing copy — importing it here keeps the live 402+// challenge from drifting from what /.well-known/x402.json and the OKX+// projection advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = pipelineRemeshListing.description;export const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',diff --git a/api/x402/pipeline-rig.js b/api/x402/pipeline-rig.jsindex 3b1d48c88..00acdab2e 100644--- a/api/x402/pipeline-rig.js+++ b/api/x402/pipeline-rig.js@@ -26,18 +26,18 @@ import {persistStageOutput,stageObjectKey,} from '../_lib/pipeline-stage.js';+import pipelineRigListing from '../_lib/service-catalog/services/pipeline-rig.js';const ROUTE = '/api/x402/pipeline-rig';const SLUG = 'pipeline-rig';const VALID_RIG_TYPES = new Set(['biped', 'quadruped']);-const DESCRIPTION =- '3D Asset Pipeline — Rig: pay $0.05 USDC to make a static GLB animation-ready. ' +- 'A humanoid skeleton is inferred and bound to the mesh with skin weights so the ' +- 'model can walk, wave, and emote. POST a public glb_url; get back a durable ' +- 'first-party rigged GLB URL. No other x402 resource rigs a mesh. Pay ' +- 'autonomously in USDC on Solana mainnet — no API key, no account.';+// Single source of truth: api/_lib/service-catalog/services/pipeline-rig.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = pipelineRigListing.description;export const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',diff --git a/api/x402/pipeline-stylize.js b/api/x402/pipeline-stylize.jsindex e27a9c496..a13102be1 100644--- a/api/x402/pipeline-stylize.js+++ b/api/x402/pipeline-stylize.js@@ -25,6 +25,7 @@ import {persistStageOutput,stageObjectKey,} from '../_lib/pipeline-stage.js';+import pipelineStylizeListing from '../_lib/service-catalog/services/pipeline-stylize.js';const ROUTE = '/api/x402/pipeline-stylize';const SLUG = 'pipeline-stylize';@@ -38,12 +39,11 @@ const STYLE_BOUNDS = {lowpoly: { def: 40, min: 8, max: 120 },};-const DESCRIPTION =- '3D Asset Pipeline — Stylize: pay $0.03 USDC to geometrically restyle a GLB. ' +- 'Voxel, brick, Voronoi-shatter, or faceted low-poly filters that rebuild the ' +- 'mesh itself (not a shader), so the look survives export to any engine. POST a ' +- 'public glb_url + style; get back a durable first-party GLB URL. Pay ' +- 'autonomously in USDC on Solana mainnet.';+// Single source of truth: api/_lib/service-catalog/services/pipeline-stylize.js+// is the storefront listing copy — importing it here keeps the live 402+// challenge from drifting from what /.well-known/x402.json and the OKX+// projection advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = pipelineStylizeListing.description;export const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',diff --git a/api/x402/pump-agent-audit.js b/api/x402/pump-agent-audit.jsindex d0adce99e..e8f4d6d13 100644--- a/api/x402/pump-agent-audit.js+++ b/api/x402/pump-agent-audit.js@@ -175,7 +175,11 @@ const OUTPUT_SCHEMA = {};const BAZAAR = {- discoverable: true,+ // De-listed per the 2026-07-08 storefront cleanup (prompt 18) — the paid+ // "oracle" framing over-claims what a payments-history audit actually is; a+ // free whale surface (/api/crypto/whales) replaces it as the agent product.+ // Route stays live for the /play town NPC.+ discoverable: false,info: {input: {type: 'http',@@ -618,7 +622,10 @@ const WHALE_OUTPUT_SCHEMA = {};const WHALE_BAZAAR = {- discoverable: true,+ // De-listed per the 2026-07-08 storefront cleanup (prompt 18) — see BAZAAR+ // above; the free /api/crypto/whales surface replaces this as the agent+ // product, this route stays live for its in-product consumer only.+ discoverable: false,info: {input: {type: 'http',diff --git a/api/x402/remix-asset.js b/api/x402/remix-asset.jsindex d57aea473..7828a627d 100644--- a/api/x402/remix-asset.js+++ b/api/x402/remix-asset.js@@ -27,6 +27,7 @@ import { settleRemixRoyalty } from '../_lib/remix-settlement.js';import { atomicsToUsd } from '../_lib/remix-royalty.js';import { composeRefinement } from '../../mcp-server/src/tools/_lineage.js';import { generate, originFromReq, viewerUrl } from '../_mcp-studio/forge-client.js';+import remixAssetListing from '../_lib/service-catalog/services/remix-asset.js';// $0.25 — the cost of a generation. The creator royalty comes OUT of this fee// (the platform's share), never as an extra charge to the remixer.@@ -181,16 +182,16 @@ async function handleRemix({ req, requirement }) {};}+// Single source of truth: api/_lib/service-catalog/services/remix-asset.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).export default paidEndpoint({route: '/api/x402/remix-asset',method: 'POST',priceAtomics: PRICE_ATOMICS,networks: ['solana', 'base'],- description:- 'Remix a published 3D asset: pay a fixed fee to generate a new model derived from another creator’s ' +- 'remixable model, described in words ("make it metallic"). A creator-set royalty (≤20%) of the fee routes ' +- 'on-chain to the original creator; durable parent→child provenance is recorded. Browse remixable assets and ' +- 'their terms free at GET /api/remix-feed.',+ description: remixAssetListing.description,mimeType: 'application/json',bazaar: BAZAAR,// A duplicate call is materially expensive (a GPU generation + an on-chaindiff --git a/api/x402/skill-call.js b/api/x402/skill-call.jsindex 363d108ad..77cc247ca 100644--- a/api/x402/skill-call.js+++ b/api/x402/skill-call.js@@ -24,15 +24,15 @@ import { priceFor } from '../_lib/x402-prices.js';import { sql } from '../_lib/db.js';import { error } from '../_lib/http.js';import { env } from '../_lib/env.js';+import skillCallListing from '../_lib/service-catalog/services/skill-call.js';const ROUTE = '/api/x402/skill-call';-const 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. Payment settles straight to the skill ' +- "author's wallet, so authors earn on every call. Per-call pricing — every " +- 'invocation is a fresh payment (no free re-access).';+// Single source of truth: api/_lib/service-catalog/services/skill-call.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = skillCallListing.description;const INPUT_EXAMPLE = { skill: 'wallet-balance' };diff --git a/api/x402/skill-marketplace.js b/api/x402/skill-marketplace.jsindex 3d4909278..894e1c24e 100644--- a/api/x402/skill-marketplace.js+++ b/api/x402/skill-marketplace.js@@ -28,15 +28,17 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { sql } from '../_lib/db.js';import { priceFor } from '../_lib/x402-prices.js';+import skillMarketplaceListing from '../_lib/service-catalog/services/skill-marketplace.js';const ROUTE = '/api/x402/skill-marketplace';-const DESCRIPTION =- 'three.ws Skill Marketplace — list active skill listings with pricing across ' +- 'all three.ws agents. Optionally filter by skill name to find the cheapest ' +- 'provider for a specific capability (e.g. inspect_model, render_avatar). ' +- 'Returns price atomics, chain, currency, trial offer, and time-pass terms ' +- 'when set by the agent owner. Use to route paid work to the cheapest agent.';+// Single source of truth:+// api/_lib/service-catalog/services/skill-marketplace.js is the storefront+// listing copy — importing it here keeps the live 402 challenge from drifting+// from what /.well-known/x402.json and the OKX projection advertise (same+// pattern as forge.js → forge-listing.js). The POST (analytics) endpoint below+// appends its own mode-specific sentence to this same base text.+const DESCRIPTION = skillMarketplaceListing.description;const INPUT_EXAMPLE = { skill: 'inspect_model', limit: 20 };diff --git a/api/x402/symbol-availability.js b/api/x402/symbol-availability.jsindex 3e0a04bff..9456c32fe 100644--- a/api/x402/symbol-availability.js+++ b/api/x402/symbol-availability.js@@ -12,10 +12,12 @@// taken_list, availability_ratio, headline, results[] }.// It is a collision checker, not a market oracle: `availability_ratio` is// simply available_count / scanned_count (a convenience roll-up), NOT a-// trading signal. The `signal`/`headline` fields are retained as an internal-// alias consumed by the autonomous scan loop's registry entry-// (`symbol-scan-common`); external callers should treat availability_ratio-// and the counts as the answer.+// trading signal. The 2026-07-08 storefront cleanup (prompt 18) removed the+// bullish/bearish/neutral `signal` field this endpoint used to return —+// this is a collision checker, sold as exactly that. The autonomous scan+// loop's registry entry (`symbol-scan-common`) now derives its own coarse+// bucket from `available_count`/`scanned_count` locally instead of reading+// it off the wire.//// Why this is defensible: three.ws indexes every mint deployed through its// own launch pipeline (pump_agent_mints). Pre-launch collision checks are@@ -29,15 +31,18 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { sql } from '../_lib/db.js';import { priceFor } from '../_lib/x402-prices.js';+import symbolAvailabilityListing from '../_lib/service-catalog/services/symbol-availability.js';const ROUTE = '/api/x402/symbol-availability';-const DESCRIPTION =- 'three.ws Symbol Availability — given a candidate ticker symbol, check for ' +- 'exact and fuzzy collisions across pump.fun mints indexed by three.ws. ' +- 'Returns exact matches (same symbol on the same network) plus trigram-similar ' +- 'symbols (e.g. "USDC" vs "USDCC", "PUMP" vs "PMP"). Use before launching a ' +- 'token to avoid name confusion and aggregator-search dilution.';+// Single source of truth:+// api/_lib/service-catalog/services/symbol-availability.js is the storefront+// listing copy — importing it here keeps the live 402 challenge (single-ticker+// GET) from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js). BATCH_DESCRIPTION+// below stays local — the batch POST mode is intentionally not advertised to+// external buyers.+const DESCRIPTION = symbolAvailabilityListing.description;const INPUT_EXAMPLE = { ticker: 'HELIO', network: 'mainnet' };@@ -204,11 +209,13 @@ const singleEndpoint = paidEndpoint({// ── Batch scan (POST) ────────────────────────────────────────────────────────// Accepts { symbols: string[], network?: string } and checks all symbols in-// parallel. Returns counts + available/taken lists + availability_ratio. The-// { signal, headline } pair is retained as an internal alias for the autonomous-// scan loop's registry entry (`symbol-scan-common`), which upserts into-// oracle_intel_signals (topic: 'symbol_availability') — it is not a market-// signal and is not advertised to external buyers.+// parallel. Returns counts + available/taken lists + availability_ratio + a+// factual `headline` summary. It does not return a bullish/bearish/neutral+// signal — this is a collision checker, not a market oracle. The autonomous+// scan loop's registry entry (`symbol-scan-common` in autonomous-registry.js)+// derives its own coarse bucket from available_count/scanned_count for its+// internal oracle_intel_signals row; that classification never ships on the+// wire to external buyers.const BATCH_MAX = 10;@@ -270,16 +277,6 @@ async function readJsonBody(req) {return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');}-// Internal-only: coarse availability bucket for the autonomous scan loop's-// oracle_intel_signals row. This is a name-collision ratio, not a market signal;-// it is never advertised to external buyers (see BATCH_DESCRIPTION).-function classifyScanSignal({ availableCount, scannedCount }) {- const ratio = scannedCount > 0 ? availableCount / scannedCount : 0;- if (ratio >= 0.6) return 'bullish';- if (ratio >= 0.3) return 'neutral';- return 'bearish';-}-const batchEndpoint = paidEndpoint({route: ROUTE,method: 'POST',@@ -337,8 +334,6 @@ const batchEndpoint = paidEndpoint({const availabilityRatio = symbols.length > 0? Number((availableCount / symbols.length).toFixed(3)): 0;- // Internal alias kept for the autonomous scan loop consumer only.- const signal = classifyScanSignal({ availableCount, scannedCount: symbols.length });const headline =availableCount === symbols.length@@ -354,7 +349,6 @@ const batchEndpoint = paidEndpoint({available_list: availableList,taken_list: takenList,availability_ratio: availabilityRatio,- signal,headline,network,results,diff --git a/api/x402/three-intel.js b/api/x402/three-intel.jsindex 2ffcd86b1..47e0bbb92 100644--- a/api/x402/three-intel.js+++ b/api/x402/three-intel.js@@ -23,6 +23,13 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { env } from '../_lib/env.js';+import {+ mppEnabled,+ looksLikeMppPayment,+ mppRequirements,+ mppVerify,+ mppSettle,+} from '../_lib/bnb/mpp-server.js';const ROUTE = '/api/x402/three-intel';@@ -60,6 +67,9 @@ const OUTPUT_SCHEMA = {};export const BAZAAR = {+ // De-listed per the 2026-07-08 storefront cleanup (prompt 18) — stays live+ // for the /play town kiosk; not agent-discoverable via the bazaar.+ discoverable: false,description: DESCRIPTION,useCases: ['$THREE market signal', 'in-world paid oracle', 'token intel'],input: { type: 'query', example: {}, schema: INPUT_SCHEMA },@@ -138,10 +148,42 @@ export function buildSignal({ price_usd, change_24h, volume_24h_usd, liquidity_ureturn { signal, headline, rationale, confidence };}-export default paidEndpoint({+const PRICE_ATOMICS = priceFor('three-intel', '10000'); // $0.01 USDC++/**+ * The oracle's business logic, shared by the x402 handler and the MPP+ * (BNB Chain) alternate payment path. Throws a 503 when live data is+ * unavailable — a paid endpoint never charges for a fabricated signal.+ */+export async function computeThreeIntel() {+ const mint = env.THREE_TOKEN_MINT;+ let live = null;+ try { live = await fetchThreeMarket(mint); } catch { /* upstream hiccup */ }++ if (!live || live.change_24h == null) {+ throw Object.assign(new Error('live THREE market data is temporarily unavailable'), {+ status: 503,+ code: 'data_unavailable',+ });+ }++ const { signal, headline, rationale, confidence } = buildSignal(live);+ return {+ mint,+ symbol: 'THREE',+ ...live,+ signal,+ headline,+ rationale,+ confidence,+ ts: new Date().toISOString(),+ };+}++const x402Handler = paidEndpoint({route: ROUTE,method: 'GET',- priceAtomics: priceFor('three-intel', '10000'), // $0.01 USDC+ priceAtomics: PRICE_ATOMICS,networks: ['solana', 'base'],description: DESCRIPTION,bazaar: BAZAAR,@@ -150,33 +192,49 @@ export default paidEndpoint({tags: ['three', 'market', 'signal', 'play', 'solana'],}),accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),+ handler: computeThreeIntel,+});- async handler() {- const mint = env.THREE_TOKEN_MINT;- let live = null;- try { live = await fetchThreeMarket(mint); } catch { /* upstream hiccup */ }-- if (!live || live.change_24h == null) {- // Live data is unavailable (DexScreener hiccup/rate-limit). This is a- // paid endpoint — never charge for a fabricated signal. Throw so the- // paidEndpoint wrapper returns a 503 BEFORE settlement runs; the buyer- // is not charged and can retry once live data is back.- throw Object.assign(new Error('live THREE market data is temporarily unavailable'), {- status: 503,- code: 'data_unavailable',- });+// Additive MPP (BNB Chain / b402) alternate payment path. A BNB-network+// X-PAYMENT settles through the b402 facilitator; every Solana/Base x402+// request (and every unpaid request) falls through to the untouched x402+// handler. Order is verify (free) → compute → settle so a data-outage 503+// never charges the buyer. Advertising header lets MPP clients discover us.+export default async function handler(req, res) {+ if (mppEnabled() && looksLikeMppPayment(req)) {+ const requirements = await mppRequirements({+ route: ROUTE,+ priceAtomics: PRICE_ATOMICS,+ description: DESCRIPTION,+ });+ const verified = await mppVerify(req, requirements);+ if (!verified.ok) {+ return sendJson(res, verified.status, { error: verified.code, message: verified.reason });}+ let body;+ try {+ body = await computeThreeIntel();+ } catch (err) {+ // Business failure BEFORE settle — buyer is not charged.+ return sendJson(res, err.status || 500, { error: err.code || 'error', message: err.message });+ }+ const settled = await mppSettle(verified.payload, requirements, { client: verified.client });+ if (!settled.ok) {+ return sendJson(res, settled.status, { error: settled.code, message: settled.reason });+ }+ res.setHeader('X-PAYMENT-RESPONSE', settled.paymentResponseHeader);+ res.setHeader('X-Settled-Via', 'mpp-b402');+ return sendJson(res, 200, body);+ }+ // Advertise MPP payability to discovery clients without altering x402.+ if (mppEnabled() && typeof res.setHeader === 'function') {+ res.setHeader('X-Accept-Payment-MPP', ROUTE);+ }+ return x402Handler(req, res);+}- const { signal, headline, rationale, confidence } = buildSignal(live);- return {- mint,- symbol: 'THREE',- ...live,- signal,- headline,- rationale,- confidence,- ts: new Date().toISOString(),- };- },-});+function sendJson(res, status, obj) {+ res.statusCode = status;+ if (typeof res.setHeader === 'function') res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify(obj));+}diff --git a/api/x402/token-intel.js b/api/x402/token-intel.jsindex ffeb13def..b327a1a68 100644--- a/api/x402/token-intel.js+++ b/api/x402/token-intel.js@@ -20,15 +20,15 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { fetchTokenMarket, buildTokenSignal, buildTokenRisk, isResolvableAddress } from '../_lib/token-market.js';+import tokenIntelListing from '../_lib/service-catalog/services/token-intel.js';const ROUTE = '/api/x402/token-intel';-const DESCRIPTION =- 'Generic 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. Pass ?mint=<contract-address> (Solana mint or EVM 0x). Powered ' +- 'by live DexScreener data.';+// Single source of truth: api/_lib/service-catalog/services/token-intel.js is+// the storefront listing copy — importing it here keeps the live 402 challenge+// from drifting from what /.well-known/x402.json and the OKX projection+// advertise (same pattern as forge.js → forge-listing.js).+const DESCRIPTION = tokenIntelListing.description;export const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',diff --git a/api/x402/tutor.js b/api/x402/tutor.jsindex 524f8e0f3..7c168c0b4 100644--- a/api/x402/tutor.js+++ b/api/x402/tutor.js@@ -132,7 +132,10 @@ const OUTPUT_SCHEMA = {};const BAZAAR = {- discoverable: true,+ // De-listed per the 2026-07-08 storefront cleanup (prompt 18): a genuine+ // internal consumer exists (the /tutor page + /play Schoolmarm NPC), so per+ // the work order's own escape hatch this route is delisted, not deleted.+ discoverable: false,info: {input: { type: 'http', method: 'POST', bodyType: 'json', body: INPUT_EXAMPLE },output: { type: 'json', example: OUTPUT_EXAMPLE },diff --git a/avatar-sdk/README.md b/avatar-sdk/README.mdindex 97a73be1c..619a34839 100644--- a/avatar-sdk/README.md+++ b/avatar-sdk/README.md@@ -54,6 +54,15 @@ Importing the package registers the `<agent-3d>` custom element as a side effect<!-- …or point at a GLB directly --><agent-3d src="https://example.com/my-avatar.glb"></agent-3d>++<!-- Add brain="free" and the avatar holds a real conversation — no API key,+ no backend, no per-token cost. Routed through three.ws's host-paid free+ tier (OpenRouter/Groq/NVIDIA, whichever is healthy). -->+<agent-3d+ src="https://example.com/my-avatar.glb"+ brain="free"+ instructions="You are Maya, a friendly guide to this site."+></agent-3d>```Need only a 3D preview — no chat, no voice, no 3 MB runtime? Use the light viewer:@@ -100,10 +109,24 @@ It dispatches a `load` event (`detail: { url }`) on success and an `error` event### `<agent-3d>`The full runtime element. Set `avatarid` to resolve a server-hosted avatar, or-`src` for a direct GLB. Other attributes: `ios-src` (USDZ for iOS AR Quick Look)+`src`/`body` for a direct GLB. Other attributes: `ios-src` (USDZ for iOS AR Quick Look)and `kiosk` (hide the debug GUI). Instance methods include `playGesture(name, opts?)`and `setMorph(name, weight)`.+**Conversation (`brain`)** — with no `brain` attribute the avatar is a silent 3D+decoration. Set one to give it a voice:++| `brain` value | Behavior |+|---|---|+| *(unset)* | Silent — no chat, no LLM calls. |+| `free` | Zero-config free chat. Routed through three.ws's host-paid `/api/llm/anthropic` proxy, which resolves to whichever free tier is healthy (OpenRouter, Groq, or NVIDIA NIM). No API key, no backend code, no per-token cost to you. |+| any other model id (e.g. `claude-sonnet-4-6`) | Passed through as a literal model id on the same proxy — use your own Anthropic key via the three.ws dashboard for a paid Claude model. |++Pair `brain` with `instructions` (a system prompt string) and `memory` (`local`+by default) to give the agent a persona and durable facts — see the+[Personal AI site tutorial](../docs/tutorials/personal-ai-site.md) for a full+worked example.+## Open the avatar creator`AvatarCreator` opens a modal iframe pointing at the three.ws Avatar Studio (or andiff --git a/data/pages.json b/data/pages.jsonindex b3ed24c51..4dc0b48e8 100644--- a/data/pages.json+++ b/data/pages.json@@ -673,6 +673,14 @@"changefreq": "monthly","added": "2026-04-28"},+ {+ "path": "/viewer",+ "title": "glTF / GLB Viewer",+ "description": "Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.",+ "priority": 0.5,+ "changefreq": "monthly",+ "added": "2026-07-08"+ },{"path": "/playground","title": "Playground",@@ -1162,6 +1170,70 @@"changefreq": "hourly","added": "2026-07-07"},+ {+ "path": "/screener",+ "title": "Crypto Token Screener",+ "description": "Screen the top 250 cryptocurrencies with live filters — search by name or symbol, isolate gainers or losers, and set minimum market cap and 24h volume thresholds. Every column sorts and every row links to a full coin detail page.",+ "priority": 0.7,+ "changefreq": "hourly",+ "added": "2026-07-08"+ },+ {+ "path": "/categories",+ "title": "Crypto Categories by Market Cap",+ "description": "Every crypto sector ranked by market cap — smart contract platforms, AI agents, memecoins, DeFi, gaming, and more — with 24h change, volume, and the top coins in each. See which narratives are leading the market right now.",+ "priority": 0.7,+ "changefreq": "hourly",+ "added": "2026-07-08"+ },+ {+ "path": "/exchanges",+ "title": "Top Crypto Exchanges",+ "description": "The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-07-08"+ },+ {+ "path": "/derivatives",+ "title": "Crypto Derivatives & Perpetual Futures",+ "description": "Live perpetual-futures markets across exchanges — price, 24h change, funding rate, open interest, and volume for every major contract. Filter by underlying index (BTC, ETH, SOL) and sort by any column.",+ "priority": 0.7,+ "changefreq": "always",+ "added": "2026-07-08"+ },+ {+ "path": "/converter",+ "title": "Crypto Currency Converter",+ "description": "Convert between any cryptocurrency and major world fiat currencies at live market rates — crypto to crypto, crypto to fiat, and back. Type an amount, pick both sides, and share the result via URL.",+ "priority": 0.7,+ "changefreq": "hourly",+ "added": "2026-07-08"+ },+ {+ "path": "/defi",+ "title": "DeFi TVL & Top Protocols",+ "description": "Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.",+ "priority": 0.7,+ "changefreq": "hourly",+ "added": "2026-07-08"+ },+ {+ "path": "/chains",+ "title": "Blockchain TVL by Chain",+ "description": "A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.",+ "priority": 0.7,+ "changefreq": "hourly",+ "added": "2026-07-08"+ },+ {+ "path": "/stablecoins",+ "title": "Stablecoins Market Cap & Peg Health",+ "description": "Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.",+ "priority": 0.7,+ "changefreq": "hourly",+ "added": "2026-07-08"+ },{"path": "/constellation","title": "watsonx Constellation",diff --git a/deploy/sniper/cloudrun.yaml b/deploy/sniper/cloudrun.yamlindex 3238e9a1b..a7e59116b 100644--- a/deploy/sniper/cloudrun.yaml+++ b/deploy/sniper/cloudrun.yaml@@ -76,7 +76,7 @@ spec:# breaker, daily budget, kill switches). Set back to "simulate" to halt# all spend without touching open positions.- name: SNIPER_MODE- value: live+ value: simulate- name: SNIPER_NETWORKvalue: mainnet# Emergency stop: set to "1" and redeploy to halt all new buys while@@ -130,17 +130,22 @@ spec:name: sniper-solana-rpc-urlkey: latest# Ops alerting (optional) — reuses the platform's shared ops channel.- # Absent → sendOpsAlert is a no-op, the worker still runs.- - name: TELEGRAM_BOT_TOKEN- valueFrom:- secretKeyRef:- name: telegram-bot-token- key: latest- - name: TELEGRAM_ALERTS_CHAT_ID- valueFrom:- secretKeyRef:- name: telegram-alerts-chat-id- key: latest+ # Absent → sendOpsAlert is a no-op, the worker still runs. Cloud Run's+ # `services replace` hard-fails if a secretKeyRef target doesn't exist+ # (no such thing as an optional mount), so these stay commented out+ # until the telegram-bot-token / telegram-alerts-chat-id secrets are+ # actually created in Secret Manager. Uncomment + redeploy once they+ # exist — no code change needed, sendOpsAlert already reads them.+ # - name: TELEGRAM_BOT_TOKEN+ # valueFrom:+ # secretKeyRef:+ # name: telegram-bot-token+ # key: latest+ # - name: TELEGRAM_ALERTS_CHAT_ID+ # valueFrom:+ # secretKeyRef:+ # name: telegram-alerts-chat-id+ # key: latestresources:limits:cpu: "1"diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 373ef01af..c3220b61f 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -26,17 +26,17 @@ All responses are JSON. Successful responses return the resource or a result obj```json{- "error": "Message describing what went wrong",- "code": "ERROR_CODE"+ "error": "Message describing what went wrong",+ "code": "ERROR_CODE"}```### Rate limits-| Tier | Limit |-|------|-------|-| Authenticated | 100 req/min |-| Unauthenticated | 20 req/min |+| Tier | Limit |+| --------------- | ----------- |+| Authenticated | 100 req/min |+| Unauthenticated | 20 req/min |Rate-limited responses return HTTP 429 with `{ "error": "...", "code": "RATE_LIMITED" }`.@@ -54,31 +54,31 @@ Returns the authenticated user's agents. Requires auth.**Query parameters**-| Parameter | Type | Description |-|-----------|------|-------------|-| `limit` | integer | Max results (default: 20) |-| `offset` | integer | Pagination offset (default: 0) |+| Parameter | Type | Description |+| --------- | ------- | ------------------------------ |+| `limit` | integer | Max results (default: 20) |+| `offset` | integer | Pagination offset (default: 0) |**Response**```json{- "agents": [- {- "id": "abc123",- "name": "Aria",- "description": "Product guide",- "avatar_url": "https://cdn.example.com/aria.glb",- "thumbnail_url": "https://cdn.example.com/aria.png",- "creator_address": "0xabc...",- "created_at": "2025-01-15T10:00:00Z",- "chain_id": 8453,- "chain_agent_id": 42- }- ],- "total": 5,- "limit": 20,- "offset": 0+ "agents": [+ {+ "id": "abc123",+ "name": "Aria",+ "description": "Product guide",+ "avatar_url": "https://cdn.example.com/aria.glb",+ "thumbnail_url": "https://cdn.example.com/aria.png",+ "creator_address": "0xabc...",+ "created_at": "2025-01-15T10:00:00Z",+ "chain_id": 8453,+ "chain_agent_id": 42+ }+ ],+ "total": 5,+ "limit": 20,+ "offset": 0}```@@ -120,9 +120,9 @@ Requires auth.```json{- "name": "Aria",- "description": "Product guide",- "manifest": { }+ "name": "Aria",+ "description": "Product guide",+ "manifest": {}}```@@ -130,8 +130,8 @@ Requires auth.```json{- "id": "new-agent-id",- "agent": { }+ "id": "new-agent-id",+ "agent": {}}```@@ -178,8 +178,8 @@ Requires auth. Owner only. Links an Ethereum wallet to the agent for signing act```json{- "address": "0xabc...",- "signature": "0x..."+ "address": "0xabc...",+ "signature": "0x..."}```@@ -235,32 +235,32 @@ Requires auth. Returns the authenticated user's widgets, including joined avatar**Query parameters**-| Parameter | Type | Description |-|-----------|------|-------------|-| `limit` | integer | Max results (default: 20) |-| `offset` | integer | Pagination offset (default: 0) |-| `type` | string | Filter by widget type |-| `agent_id` | string | Filter by agent ID |+| Parameter | Type | Description |+| ---------- | ------- | ------------------------------ |+| `limit` | integer | Max results (default: 20) |+| `offset` | integer | Pagination offset (default: 0) |+| `type` | string | Filter by widget type |+| `agent_id` | string | Filter by agent ID |**Response**```json{- "widgets": [- {- "id": "wdgt_abc123def456",- "agent_id": "abc123",- "type": "turntable",- "config": { "auto_rotate_speed": 0.5, "preset": "venice" },- "is_public": true,- "created_at": "2025-01-15T10:00:00Z",- "view_count": 42,- "avatar": { }- }- ],- "total": 8,- "limit": 20,- "offset": 0+ "widgets": [+ {+ "id": "wdgt_abc123def456",+ "agent_id": "abc123",+ "type": "turntable",+ "config": { "auto_rotate_speed": 0.5, "preset": "venice" },+ "is_public": true,+ "created_at": "2025-01-15T10:00:00Z",+ "view_count": 42,+ "avatar": {}+ }+ ],+ "total": 8,+ "limit": 20,+ "offset": 0}```@@ -292,13 +292,13 @@ Requires auth. Bearer token must have `avatars:write` scope.```json{- "agent_id": "abc123",- "type": "turntable",- "config": {- "auto_rotate_speed": 0.5,- "preset": "venice"- },- "visibility": "public"+ "agent_id": "abc123",+ "type": "turntable",+ "config": {+ "auto_rotate_speed": 0.5,+ "preset": "venice"+ },+ "visibility": "public"}```@@ -306,8 +306,8 @@ Requires auth. Bearer token must have `avatars:write` scope.```json{- "id": "wdgt_abc123def456",- "embed_url": "https://three.ws/widgets/view?id=wdgt_abc123def456"+ "id": "wdgt_abc123def456",+ "embed_url": "https://three.ws/widgets/view?id=wdgt_abc123def456"}```@@ -373,29 +373,29 @@ GET /api/agent-actions**Query parameters**-| Parameter | Type | Description |-|-----------|------|-------------|-| `agent_id` | string | Required. Filter by agent ID |-| `limit` | integer | Max results (default: 20) |-| `cursor` | string | Cursor for keyset pagination |+| Parameter | Type | Description |+| ---------- | ------- | ---------------------------- |+| `agent_id` | string | Required. Filter by agent ID |+| `limit` | integer | Max results (default: 20) |+| `cursor` | string | Cursor for keyset pagination |**Response**```json{- "actions": [- {- "id": "act_xyz",- "agent_id": "abc123",- "type": "speak",- "payload": { "text": "Hello, welcome!" },- "source_skill": "greeting",- "signature": "0x...",- "signer_address": "0xabc...",- "created_at": "2025-01-15T10:05:00Z"- }- ],- "cursor": "2025-01-14T10:05:00Z"+ "actions": [+ {+ "id": "act_xyz",+ "agent_id": "abc123",+ "type": "speak",+ "payload": { "text": "Hello, welcome!" },+ "source_skill": "greeting",+ "signature": "0x...",+ "signer_address": "0xabc...",+ "created_at": "2025-01-15T10:05:00Z"+ }+ ],+ "cursor": "2025-01-14T10:05:00Z"}```@@ -413,12 +413,12 @@ Append-only. Actions are never deleted. Optionally include an ERC-191 signature```json{- "agent_id": "abc123",- "type": "speak",- "payload": { "text": "Hello, welcome!" },- "source_skill": "greeting",- "signature": "0x...",- "signer_address": "0xabc..."+ "agent_id": "abc123",+ "type": "speak",+ "payload": { "text": "Hello, welcome!" },+ "source_skill": "greeting",+ "signature": "0x...",+ "signer_address": "0xabc..."}```@@ -436,30 +436,30 @@ GET /api/agent-memory**Query parameters**-| Parameter | Type | Description |-|-----------|------|-------------|-| `agentId` | string | Required. The agent's ID |-| `type` | string | Filter by memory type: `user`, `feedback`, `project`, `reference` |-| `since` | string | ISO 8601 timestamp — return only memories updated after this time |-| `limit` | integer | Max results (default: 50) |+| Parameter | Type | Description |+| --------- | ------- | ----------------------------------------------------------------- |+| `agentId` | string | Required. The agent's ID |+| `type` | string | Filter by memory type: `user`, `feedback`, `project`, `reference` |+| `since` | string | ISO 8601 timestamp — return only memories updated after this time |+| `limit` | integer | Max results (default: 50) |**Response**```json{- "memories": [- {- "id": "mem_abc",- "agent_id": "abc123",- "type": "user",- "content": "User prefers concise answers.",- "salience": 0.8,- "expires_at": null,- "client_id": "local-uuid-123",- "created_at": "2025-01-15T10:00:00Z",- "updated_at": "2025-01-15T10:00:00Z"- }- ]+ "memories": [+ {+ "id": "mem_abc",+ "agent_id": "abc123",+ "type": "user",+ "content": "User prefers concise answers.",+ "salience": 0.8,+ "expires_at": null,+ "client_id": "local-uuid-123",+ "created_at": "2025-01-15T10:00:00Z",+ "updated_at": "2025-01-15T10:00:00Z"+ }+ ]}```@@ -477,12 +477,12 @@ Idempotent — uses `client_id` as a conflict key. If a memory with the same `cl```json{- "agent_id": "abc123",- "type": "feedback",- "content": "Stop summarizing at end of responses.",- "salience": 0.9,- "expires_at": null,- "client_id": "local-uuid-456"+ "agent_id": "abc123",+ "type": "feedback",+ "content": "Stop summarizing at end of responses.",+ "salience": 0.9,+ "expires_at": null,+ "client_id": "local-uuid-456"}```@@ -518,15 +518,13 @@ Send a message to an agent's LLM runtime. Proxied through the platform for auth```json{- "agent_id": "abc123",- "messages": [- { "role": "user", "content": "What animations do you have?" }- ],- "context": {- "model_name": "avatar.glb",- "animations": ["wave", "idle", "dance"],- "settings": { }- }+ "agent_id": "abc123",+ "messages": [{ "role": "user", "content": "What animations do you have?" }],+ "context": {+ "model_name": "avatar.glb",+ "animations": ["wave", "idle", "dance"],+ "settings": {}+ }}```@@ -536,19 +534,19 @@ The `context` object is included in the system prompt so the model knows what'sThe LLM can invoke these viewer actions in its response:-| Tool | Description |-|------|-------------|-| `setWireframe` | Toggle wireframe mode |-| `setSkeleton` | Toggle skeleton overlay |-| `setGrid` | Toggle ground grid |-| `setAutoRotate` | Start/stop auto-rotation |-| `setBgColor` | Set background color |-| `setTransparentBg` | Toggle transparent background |-| `setEnvironment` | Set environment map |-| `takeScreenshot` | Capture viewport screenshot |-| `loadModel` | Load a different model URL |-| `runValidation` | Run glTF validation |-| `showMaterialEditor` | Open material editor UI |+| Tool | Description |+| -------------------- | ----------------------------- |+| `setWireframe` | Toggle wireframe mode |+| `setSkeleton` | Toggle skeleton overlay |+| `setGrid` | Toggle ground grid |+| `setAutoRotate` | Start/stop auto-rotation |+| `setBgColor` | Set background color |+| `setTransparentBg` | Toggle transparent background |+| `setEnvironment` | Set environment map |+| `takeScreenshot` | Capture viewport screenshot |+| `loadModel` | Load a different model URL |+| `runValidation` | Run glTF validation |+| `showMaterialEditor` | Open material editor UI |**Response (streaming SSE)**@@ -574,36 +572,36 @@ Server-Sent Events stream from a unified multi-provider LLM gateway. Used by the```json{- "provider": "claude-sonnet-4-6",- "messages": [{ "role": "user", "content": "Hello" }],- "system": "You are a friendly product guide.",- "maxTokens": 1024+ "provider": "claude-sonnet-4-6",+ "messages": [{ "role": "user", "content": "Hello" }],+ "system": "You are a friendly product guide.",+ "maxTokens": 1024}```**Supported `provider` IDs**-| Provider | Network | Tier |-|---|---|---|-| `claude-opus-4-7` | Anthropic | flagship |-| `claude-sonnet-4-6` | Anthropic | balanced |-| `claude-haiku-4-5` | Anthropic | fast |-| `gpt-4o` | OpenAI | flagship |-| `gpt-4o-mini` | OpenAI | fast |-| `qwen-*` | Qwen / Alibaba | varies |-| `openrouter:*` | OpenRouter (any) | varies |+| Provider | Network | Tier |+| ------------------- | ---------------- | -------- |+| `claude-opus-4-7` | Anthropic | flagship |+| `claude-sonnet-4-6` | Anthropic | balanced |+| `claude-haiku-4-5` | Anthropic | fast |+| `gpt-4o` | OpenAI | flagship |+| `gpt-4o-mini` | OpenAI | fast |+| `qwen-*` | Qwen / Alibaba | varies |+| `openrouter:*` | OpenRouter (any) | varies |Call `GET /api/brain/chat` for the live list of providers actually available on the current deployment (depends on which provider keys are configured).**Response (SSE)**-| Event | Payload |-|---|---|-| `meta` | `{ provider, label, network, model, tier }` |-| `first` | `{ firstTokenMs }` |-| (data) | JSON-encoded text chunk |-| `done` | `{ elapsedMs, firstTokenMs, usage }` |-| `error` | `{ message, elapsedMs }` |+| Event | Payload |+| ------- | ------------------------------------------- |+| `meta` | `{ provider, label, network, model, tier }` |+| `first` | `{ firstTokenMs }` |+| (data) | JSON-encoded text chunk |+| `done` | `{ elapsedMs, firstTokenMs, usage }` |+| `error` | `{ message, elapsedMs }` |**Rate limits:** Per-IP and per-agent limits apply in addition to the standard platform limits. Failed upstream calls automatically fall back to OpenRouter where possible.@@ -630,6 +628,7 @@ POST /api/tts/elevenText-to-speech via ElevenLabs with R2 caching. Requires auth.**Limits**+- Max 500 characters per request- 1,000 characters per hour per user (tracked via Redis)@@ -637,9 +636,9 @@ Text-to-speech via ElevenLabs with R2 caching. Requires auth.```json{- "voiceId": "rachel",- "text": "Hello, welcome to my portfolio!",- "modelId": "eleven_monolingual_v1"+ "voiceId": "rachel",+ "text": "Hello, welcome to my portfolio!",+ "modelId": "eleven_monolingual_v1"}```@@ -678,22 +677,22 @@ silently.{ "prompt": "a small ceramic robot figurine" }```-| Field | Type | Description |-|-------|------|-------------|+| Field | Type | Description |+| -------- | ------ | ------------------------------------------------------------------- || `prompt` | string | Describe a single object or character. 3–1000 characters. Required. |**Response — finished inline** (the NIM often completes inside the request window):```json{- "data": {- "status": "done",- "glb_url": "https://cdn.three.ws/forge/anon/<id>.glb",- "viewer_url": "https://three.ws/viewer?src=https%3A%2F%2Fcdn.three.ws%2Fforge%2Fanon%2F%3Cid%3E.glb",- "creation_id": "<uuid>",- "backend": "nvidia",- "tier": "draft"- }+ "data": {+ "status": "done",+ "glb_url": "https://cdn.three.ws/forge/anon/<id>.glb",+ "viewer_url": "https://three.ws/viewer?src=https%3A%2F%2Fcdn.three.ws%2Fforge%2Fanon%2F%3Cid%3E.glb",+ "creation_id": "<uuid>",+ "backend": "nvidia",+ "tier": "draft"+ }}```@@ -701,14 +700,14 @@ silently.```json{- "data": {- "status": "pending",- "job": "f1.<signed-token>",- "poll_url": "/api/forge?job=f1.<signed-token>",- "viewer_url": null,- "backend": "nvidia",- "tier": "draft"- }+ "data": {+ "status": "pending",+ "job": "f1.<signed-token>",+ "poll_url": "/api/forge?job=f1.<signed-token>",+ "viewer_url": null,+ "backend": "nvidia",+ "tier": "draft"+ }}```@@ -724,12 +723,12 @@ curl -s -X POST https://three.ws/api/v1/ai/text-to-3d \**Errors**-| Status | Code | Meaning |-|--------|------|---------|-| `400` | `validation_error` | `prompt` missing, shorter than 3 chars, or over 1000 |-| `429` | `quota_exceeded` | Daily free quota spent; see `X-RateLimit-Reset` and `upgrade.endpoint` (`/api/x402/forge`) |-| `503` | `not_configured` | The NVIDIA NIM lane isn't configured on this deployment (`NVIDIA_API_KEY`) |-| `502`/`504` | `lane_error` / `lane_timeout` | The generation lane failed or timed out — retry |+| Status | Code | Meaning |+| ----------- | ----------------------------- | ------------------------------------------------------------------------------------------ |+| `400` | `validation_error` | `prompt` missing, shorter than 3 chars, or over 1000 |+| `429` | `quota_exceeded` | Daily free quota spent; see `X-RateLimit-Reset` and `upgrade.endpoint` (`/api/x402/forge`) |+| `503` | `not_configured` | The NVIDIA NIM lane isn't configured on this deployment (`NVIDIA_API_KEY`) |+| `502`/`504` | `lane_error` / `lane_timeout` | The generation lane failed or timed out — retry |---@@ -760,25 +759,25 @@ outage never burns a free generation.{ "prompt": "a brass owl figurine on a plain white background", "aspect_ratio": "1:1" }```-| Field | Type | Description |-|-------|------|-------------|-| `prompt` | string | Image description. 3–2000 characters. Required. |-| `aspect_ratio` | string | One of `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`. Default `1:1`. |-| `seed` | integer | Optional deterministic seed (0–4294967295). Honored on the NIM / Replicate flux lanes; the Vertex/Gemini lane has no seed parameter and ignores it. |+| Field | Type | Description |+| -------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |+| `prompt` | string | Image description. 3–2000 characters. Required. |+| `aspect_ratio` | string | One of `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`. Default `1:1`. |+| `seed` | integer | Optional deterministic seed (0–4294967295). Honored on the NIM / Replicate flux lanes; the Vertex/Gemini lane has no seed parameter and ignores it. |**Response — 200**```json{- "url": "https://cdn.three.ws/forge/refs/<id>.jpg",- "provider": "nvidia-nim",- "model": "black-forest-labs/flux.1-schnell",- "width": 1024,- "height": 1024,- "aspect_ratio": "1:1",- "seed": null,- "free": true,- "quota": { "used": 1, "limit": 5, "remaining": 4, "resetAt": "2026-07-08T00:00:00.000Z" }+ "url": "https://cdn.three.ws/forge/refs/<id>.jpg",+ "provider": "nvidia-nim",+ "model": "black-forest-labs/flux.1-schnell",+ "width": 1024,+ "height": 1024,+ "aspect_ratio": "1:1",+ "seed": null,+ "free": true,+ "quota": { "used": 1, "limit": 5, "remaining": 4, "resetAt": "2026-07-08T00:00:00.000Z" }}```@@ -814,15 +813,15 @@ discovery doc (price, free-tier width, which lanes are configured).**Errors**-| Status | Code | Meaning |-|--------|------|---------|-| `400` | `invalid_prompt` / `prompt_too_long` / `invalid_aspect_ratio` / `invalid_seed` | Request validation failed |-| `402` | — | Free quota spent — pay the x402 challenge to continue |-| `422` | `content_refused` | The provider blocked the prompt on content-policy grounds (not retried) |-| `429` | `rate_limited` | Lane briefly busy — retry after `retryAfter` seconds |-| `503` | `not_configured` | No image lane is configured (`NVIDIA_API_KEY`, `GOOGLE_CLOUD_PROJECT` + `GCP_SERVICE_ACCOUNT_JSON`, or `REPLICATE_API_TOKEN`) |-| `503` | `lane_unavailable` | The configured lane is temporarily down — retry |-| `502` | `generation_failed` | The lane returned no usable image — retry |+| Status | Code | Meaning |+| ------ | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |+| `400` | `invalid_prompt` / `prompt_too_long` / `invalid_aspect_ratio` / `invalid_seed` | Request validation failed |+| `402` | — | Free quota spent — pay the x402 challenge to continue |+| `422` | `content_refused` | The provider blocked the prompt on content-policy grounds (not retried) |+| `429` | `rate_limited` | Lane briefly busy — retry after `retryAfter` seconds |+| `503` | `not_configured` | No image lane is configured (`NVIDIA_API_KEY`, `GOOGLE_CLOUD_PROJECT` + `GCP_SERVICE_ACCOUNT_JSON`, or `REPLICATE_API_TOKEN`) |+| `503` | `lane_unavailable` | The configured lane is temporarily down — retry |+| `502` | `generation_failed` | The lane returned no usable image — retry |---@@ -857,30 +856,30 @@ access, not a different model.{ "text": "Your deploy finished — three services are green.", "voice": "nova", "format": "wav" }```-| Field | Type | Description |-|-------|------|-------------|-| `text` | string | Text to synthesize. Required. ≤4096 chars (free tier ≤500). |-| `voice` | string | Voice id (`nova`, `alloy`, `shimmer`, `onyx`, …). Unknown values fall back to the default persona. Default `nova`. |-| `format` | string | `wav` or `pcm`. Magpie emits WAV or raw PCM. Default `wav`. |-| `language` | string | BCP-47 tag: `en-US`, `es-US`, `fr-FR`, `de-DE`, `it-IT`, `hi-IN`, `zh-CN`, `vi-VN`, `ja-JP`. Default `en-US`. |+| Field | Type | Description |+| ---------- | ------ | ------------------------------------------------------------------------------------------------------------------ |+| `text` | string | Text to synthesize. Required. ≤4096 chars (free tier ≤500). |+| `voice` | string | Voice id (`nova`, `alloy`, `shimmer`, `onyx`, …). Unknown values fall back to the default persona. Default `nova`. |+| `format` | string | `wav` or `pcm`. Magpie emits WAV or raw PCM. Default `wav`. |+| `language` | string | BCP-47 tag: `en-US`, `es-US`, `fr-FR`, `de-DE`, `it-IT`, `hi-IN`, `zh-CN`, `vi-VN`, `ja-JP`. Default `en-US`. |**Response — 200**```json{- "data": {- "audio": "UklGR... (base64)",- "encoding": "base64",- "format": "wav",- "content_type": "audio/wav",- "sample_rate": 44100,- "voice": "Magpie-Multilingual.EN-US.Aria",- "model": "magpie-tts-multilingual",- "characters": 47,- "bytes": 132344,- "tier": "free",- "free_remaining_today": 9- }+ "data": {+ "audio": "UklGR... (base64)",+ "encoding": "base64",+ "format": "wav",+ "content_type": "audio/wav",+ "sample_rate": 44100,+ "voice": "Magpie-Multilingual.EN-US.Aria",+ "model": "magpie-tts-multilingual",+ "characters": 47,+ "bytes": 132344,+ "tier": "free",+ "free_remaining_today": 9+ }}```@@ -928,27 +927,27 @@ Send audio one of two ways:WebM/Opus is not accepted — decode it to PCM/WAV client-side first.-| Field | Type | Description |-|-------|------|-------------|-| `audio` | string | Base64 audio in a JSON body (data: URIs accepted). Required for the JSON transport. |-| `format` | string | `wav` \| `pcm` \| `flac` \| `ogg`. Default `wav`. |-| `language` | string | BCP-47 language hint. Default `en-US`. |-| `sampleRate` | integer | Sample rate (Hz) for raw PCM. Ignored for WAV (read from the header). |-| `words` | boolean | Return word-level timestamps. Default `false`. |+| Field | Type | Description |+| ------------ | ------- | ----------------------------------------------------------------------------------- |+| `audio` | string | Base64 audio in a JSON body (data: URIs accepted). Required for the JSON transport. |+| `format` | string | `wav` \| `pcm` \| `flac` \| `ogg`. Default `wav`. |+| `language` | string | BCP-47 language hint. Default `en-US`. |+| `sampleRate` | integer | Sample rate (Hz) for raw PCM. Ignored for WAV (read from the header). |+| `words` | boolean | Return word-level timestamps. Default `false`. |**Response — 200**```json{- "data": {- "text": "schedule the deploy for friday morning",- "confidence": 0.94,- "duration": 2.1,- "language": "en-US",- "model": "riva-asr",- "tier": "free",- "free_remaining_today": 4- }+ "data": {+ "text": "schedule the deploy for friday morning",+ "confidence": 0.94,+ "duration": 2.1,+ "language": "en-US",+ "model": "riva-asr",+ "tier": "free",+ "free_remaining_today": 4+ }}```@@ -986,15 +985,15 @@ sample rate, whether the lane is configured).**Errors** (both endpoints)-| Status | Code | Meaning |-|--------|------|---------|-| `400` | `bad_request` / `text_too_long` | Request validation failed (empty/invalid body, or text over 4096 chars) |-| `402` | — | Free quota spent (or over the free size limit) — pay the x402 challenge |-| `413` | `payload_too_large` | Audio exceeds the 8 MB limit |-| `415` | `unsupported_media_type` | Unrecognized audio `Content-Type` (ASR) |-| `429` | `rate_limited` | Upstream credit metering hit — retry shortly |-| `503` | `not_configured` | TTS needs `NVIDIA_API_KEY`; ASR needs `NVIDIA_API_KEY` + `NVIDIA_ASR_FUNCTION_ID` |-| `502` | `provider_error` / `invalid_key` | The NIM lane failed — retry |+| Status | Code | Meaning |+| ------ | -------------------------------- | --------------------------------------------------------------------------------- |+| `400` | `bad_request` / `text_too_long` | Request validation failed (empty/invalid body, or text over 4096 chars) |+| `402` | — | Free quota spent (or over the free size limit) — pay the x402 challenge |+| `413` | `payload_too_large` | Audio exceeds the 8 MB limit |+| `415` | `unsupported_media_type` | Unrecognized audio `Content-Type` (ASR) |+| `429` | `rate_limited` | Upstream credit metering hit — retry shortly |+| `503` | `not_configured` | TTS needs `NVIDIA_API_KEY`; ASR needs `NVIDIA_API_KEY` + `NVIDIA_ASR_FUNCTION_ID` |+| `502` | `provider_error` / `invalid_key` | The NIM lane failed — retry |---@@ -1016,9 +1015,9 @@ GET /api/v1/token/security?address=<mint>Public, CORS-open, no auth. Rate limited to **20 requests/min per IP**; responsesare edge-cached for 60s. Solana only — an EVM `0x…` address returns `400`.-| Query param | Type | Description |-|-------------|------|-------------|-| `address` | string | Base58 Solana mint address. Required. |+| Query param | Type | Description |+| ----------- | ------ | ------------------------------------- |+| `address` | string | Base58 Solana mint address. Required. |**Response**@@ -1028,32 +1027,41 @@ factual conditions (an empty array means none tripped).```json{- "data": {- "address": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",- "chain": "solana",- "mint_authority": { "revoked": true, "address": null },- "freeze_authority": { "revoked": true, "address": null },- "supply": "999683523471616",- "decimals": 6,- "top_holders": { "top1_pct": 6.6, "top5_pct": 14.7, "top10_pct": 22.3, "holders_sampled": 20 },- "liquidity": { "usd": 196695.93, "largest_pair": "three/SOL", "pair_created_at": 1777446541000 },- "flags": [],- "sources": ["solana-rpc", "dexscreener"],- "ts": 1783382400000- }+ "data": {+ "address": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "chain": "solana",+ "mint_authority": { "revoked": true, "address": null },+ "freeze_authority": { "revoked": true, "address": null },+ "supply": "999683523471616",+ "decimals": 6,+ "top_holders": {+ "top1_pct": 6.6,+ "top5_pct": 14.7,+ "top10_pct": 22.3,+ "holders_sampled": 20+ },+ "liquidity": {+ "usd": 196695.93,+ "largest_pair": "three/SOL",+ "pair_created_at": 1777446541000+ },+ "flags": [],+ "sources": ["solana-rpc", "dexscreener"],+ "ts": 1783382400000+ }}```**Flags** (emitted only when the underlying facts are known):-| Flag | Condition |-|------|-----------|-| `mint_authority_active` | The mint authority is not revoked — supply can still be inflated |-| `freeze_authority_active` | The freeze authority is not revoked — accounts can be frozen |-| `top1_holder_over_20pct` | The single largest account holds > 20% of supply |-| `top10_holders_over_80pct` | The top 10 accounts hold > 80% of supply |-| `liquidity_under_10k` | Deepest-pair liquidity is under $10,000 |-| `pair_younger_than_24h` | The deepest pair was created less than 24h ago |+| Flag | Condition |+| -------------------------- | ---------------------------------------------------------------- |+| `mint_authority_active` | The mint authority is not revoked — supply can still be inflated |+| `freeze_authority_active` | The freeze authority is not revoked — accounts can be frozen |+| `top1_holder_over_20pct` | The single largest account holds > 20% of supply |+| `top10_holders_over_80pct` | The top 10 accounts hold > 80% of supply |+| `liquidity_under_10k` | Deepest-pair liquidity is under $10,000 |+| `pair_younger_than_24h` | The deepest pair was created less than 24h ago |**Example**@@ -1067,13 +1075,111 @@ Each section resolves independently. If one upstream is down, only that sectionis nulled and it drops out of `sources` — the call still succeeds (`200`) as longas any section resolved.-| Status | Code | Meaning |-|--------|------|---------|-| `400` | `validation_error` | `address` missing or not a base58 Solana address |-| `400` | `unsupported_chain` | An EVM `0x…` address — this endpoint is Solana-only |-| `404` | `not_found` | Sources answered but no on-chain mint or market exists for this address |-| `429` | `rate_limited` | Over 20 requests/min from this IP — back off per `retry_after` |-| `503` | `sources_unavailable` | Every upstream failed — transient, retry shortly |+| Status | Code | Meaning |+| ------ | --------------------- | ----------------------------------------------------------------------- |+| `400` | `validation_error` | `address` missing or not a base58 Solana address |+| `400` | `unsupported_chain` | An EVM `0x…` address — this endpoint is Solana-only |+| `404` | `not_found` | Sources answered but no on-chain mint or market exists for this address |+| `429` | `rate_limited` | Over 20 requests/min from this IP — back off per `retry_after` |+| `503` | `sources_unavailable` | Every upstream failed — transient, retry shortly |++---++## Name Resolution API++Name resolution is the highest-frequency primitive in agent tooling — every+payment, transfer, or profile lookup starts with turning a human-readable name+into an address (or back). This endpoint wraps the platform's existing ENS and+SNS resolvers (the same ones behind `/api/agents/ens/:name` and `/api/sns`) in+one free, versioned door.++### Resolve a name / reverse-resolve an address++```+GET /api/v1/resolve?name=<x>.eth+GET /api/v1/resolve?name=<x>.sol+GET /api/v1/resolve?address=<addr>[&chain=ethereum|solana]+```++Public, CORS-open, no auth, no cost. Rate limited to **30 requests/min per+IP**; successful responses are edge-cached for 5 minutes. Pass exactly one of+`name` or `address`.++| Query param | Type | Description |+| ----------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------ |+| `name` | string | A name ending in `.eth` (ENS) or `.sol` (SNS). Required unless `address` is passed. |+| `address` | string | A `0x…` Ethereum address or a base58 Solana address to reverse-resolve. Required unless `name` is passed. |+| `chain` | string | `"ethereum"` \| `"solana"` — optional hint, validated against the address format when passed. Auto-detected from the address when omitted. |++**Forward response** (`?name=…`)++```json+{+ "data": {+ "name": "vitalik.eth",+ "chain": "ethereum",+ "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",+ "source": "ens"+ }+}+```++```json+{+ "data": {+ "name": "bonfida.sol",+ "chain": "solana",+ "address": "<owner base58 address>",+ "source": "sns"+ }+}+```++**Reverse response** (`?address=…`)++```json+{+ "data": {+ "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",+ "chain": "ethereum",+ "name": "vitalik.eth",+ "source": "ens"+ }+}+```++```json+{+ "data": {+ "address": "<base58 address>",+ "chain": "solana",+ "name": "bonfida.sol",+ "source": "sns"+ }+}+```++Reverse lookup only runs in the direction the wrapped resolver already+supports (ethers `lookupAddress` for ENS, SNS `getFavoriteDomain` for SNS) —+both directions are covered, so there is no half-built placeholder here.++**Examples**++```bash+curl -s 'https://three.ws/api/v1/resolve?name=vitalik.eth'+curl -s 'https://three.ws/api/v1/resolve?name=bonfida.sol'+curl -s 'https://three.ws/api/v1/resolve?address=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'+```++**Errors**++| Status | Code | Meaning |+| ------ | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |+| `400` | `validation_error` | Neither/both of `name`/`address` passed, `address` isn't a recognizable Ethereum or Solana address, or `chain` doesn't match the address format |+| `400` | `unsupported_suffix` | `name` doesn't end in `.eth` or `.sol` — those are the only two supported registries |+| `404` | `not_found` | The name/address is well-formed but does not resolve — a miss, not a failure |+| `429` | `rate_limited` | Over 30 requests/min from this IP — back off per `retry_after` |+| `503` | `ens_unavailable` | The ENS RPC chain timed out or failed — transient, retry shortly |---@@ -1081,15 +1187,15 @@ as any section resolved.Authentication is covered in detail in the [Authentication documentation](authentication.md). Quick reference:-| Endpoint | Method | Description |-|----------|--------|-------------|-| `/api/auth/siwe/nonce` | GET | Get a SIWE nonce |-| `/api/auth/siwe/verify` | POST | Verify SIWE signature, create session |-| `/api/auth/session` | GET | Get current session |-| `/api/auth/session` | DELETE | Logout / destroy session |-| `/api/auth/privy/[handler]` | GET/POST | Privy OAuth handlers |-| `/api/auth/wallets` | GET | List wallets linked to current user |-| `/api/auth/wallets` | POST | Link a new wallet |+| Endpoint | Method | Description |+| --------------------------- | -------- | ------------------------------------- |+| `/api/auth/siwe/nonce` | GET | Get a SIWE nonce |+| `/api/auth/siwe/verify` | POST | Verify SIWE signature, create session |+| `/api/auth/session` | GET | Get current session |+| `/api/auth/session` | DELETE | Logout / destroy session |+| `/api/auth/privy/[handler]` | GET/POST | Privy OAuth handlers |+| `/api/auth/wallets` | GET | List wallets linked to current user |+| `/api/auth/wallets` | POST | Link a new wallet |---@@ -1107,15 +1213,15 @@ Requires auth. Returns all API keys for the current user. Plaintext key values a```json{- "keys": [- {- "id": "key_abc",- "name": "My Integration",- "scopes": ["avatars:read", "avatars:write"],- "created_at": "2025-01-15T10:00:00Z",- "last_used_at": "2025-01-20T08:30:00Z"- }- ]+ "keys": [+ {+ "id": "key_abc",+ "name": "My Integration",+ "scopes": ["avatars:read", "avatars:write"],+ "created_at": "2025-01-15T10:00:00Z",+ "last_used_at": "2025-01-20T08:30:00Z"+ }+ ]}```@@ -1133,26 +1239,26 @@ Requires auth.```json{- "name": "My Integration",- "scopes": ["avatars:read", "avatars:write"]+ "name": "My Integration",+ "scopes": ["avatars:read", "avatars:write"]}```**Available scopes**-| Scope | Description |-|-------|-------------|-| `avatars:read` | Read agents and avatars |-| `avatars:write` | Create and update agents and avatars |-| `avatars:delete` | Delete agents and avatars |-| `profile` | Read user profile data |+| Scope | Description |+| ---------------- | ------------------------------------ |+| `avatars:read` | Read agents and avatars |+| `avatars:write` | Create and update agents and avatars |+| `avatars:delete` | Delete agents and avatars |+| `profile` | Read user profile data |**Response**```json{- "id": "key_abc",- "key": "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+ "id": "key_abc",+ "key": "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}```@@ -1186,35 +1292,35 @@ Paginated search over ERC-8004 registered agents. No auth required.**Query parameters**-| Parameter | Type | Description |-|-----------|------|-------------|-| `q` | string | Full-text search query |-| `only3d` | `1` | Filter to agents with 3D avatars only |-| `chain` | integer | Filter by chain ID |-| `cursor` | string | ISO 8601 timestamp cursor for keyset pagination |-| `limit` | integer | Max results (default: 20) |+| Parameter | Type | Description |+| --------- | ------- | ----------------------------------------------- |+| `q` | string | Full-text search query |+| `only3d` | `1` | Filter to agents with 3D avatars only |+| `chain` | integer | Filter by chain ID |+| `cursor` | string | ISO 8601 timestamp cursor for keyset pagination |+| `limit` | integer | Max results (default: 20) |**Response**```json{- "agents": [- {- "id": "onchain_abc",- "name": "Aria",- "description": "Product guide",- "avatar_url": "https://cdn.example.com/aria.glb",- "thumbnail_url": "https://cdn.example.com/aria.png",- "chain_id": 8453,- "chain_agent_id": 42,- "registered_at": "2025-01-15T10:00:00Z",- "services": [],- "explorer_url": "https://basescan.org/..."- }- ],- "total": 142,- "total_3d": 89,- "cursor": "2025-01-10T10:00:00Z"+ "agents": [+ {+ "id": "onchain_abc",+ "name": "Aria",+ "description": "Product guide",+ "avatar_url": "https://cdn.example.com/aria.glb",+ "thumbnail_url": "https://cdn.example.com/aria.png",+ "chain_id": 8453,+ "chain_agent_id": 42,+ "registered_at": "2025-01-15T10:00:00Z",+ "services": [],+ "explorer_url": "https://basescan.org/..."+ }+ ],+ "total": 142,+ "total_3d": 89,+ "cursor": "2025-01-10T10:00:00Z"}```@@ -1230,13 +1336,13 @@ Public directory of ERC-8004 agents with 3D avatars, for homepage and gallery us**Query parameters**-| Parameter | Type | Description |-|-----------|------|-------------|-| `net` | string | `mainnet`, `testnet`, or `all` (default: `all`) |-| `sort` | string | `newest` or `oldest` |-| `chain` | integer | Filter by chain ID |-| `limit` | integer | Max results (default: 20) |-| `cursor` | string | Keyset pagination cursor (`registered_at,chain_id,agent_id` tuple) |+| Parameter | Type | Description |+| --------- | ------- | ------------------------------------------------------------------ |+| `net` | string | `mainnet`, `testnet`, or `all` (default: `all`) |+| `sort` | string | `newest` or `oldest` |+| `chain` | integer | Filter by chain ID |+| `limit` | integer | Max results (default: 20) |+| `cursor` | string | Keyset pagination cursor (`registered_at,chain_id,agent_id` tuple) |**Response:** Same shape as `/api/explore`. Cursor encodes the full keyset tuple for stable pagination under concurrent inserts.@@ -1294,16 +1400,16 @@ Model Context Protocol endpoint — exposes three.ws as a JSON-RPC 2.0 tool serv### Available tools-| Tool | Scope required | Description |-|------|---------------|-------------|-| `list_my_avatars` | `avatars:read` | List authenticated user's avatars |-| `get_avatar` | `avatars:read` | Fetch single avatar by ID or owner+slug |-| `search_public_avatars` | none | Search the public avatar gallery |-| `render_avatar` | `avatars:read` | Generate `<model-viewer>` HTML embed |-| `delete_avatar` | `avatars:delete` | Soft-delete an avatar |-| `validate_model` | none | Run Khronos glTF-Validator on a remote URL |-| `inspect_model` | none | Parse GLB/glTF and return structural stats |-| `optimize_model` | none | Return optimization suggestions for a model |+| Tool | Scope required | Description |+| ----------------------- | ---------------- | ------------------------------------------- |+| `list_my_avatars` | `avatars:read` | List authenticated user's avatars |+| `get_avatar` | `avatars:read` | Fetch single avatar by ID or owner+slug |+| `search_public_avatars` | none | Search the public avatar gallery |+| `render_avatar` | `avatars:read` | Generate `<model-viewer>` HTML embed |+| `delete_avatar` | `avatars:delete` | Soft-delete an avatar |+| `validate_model` | none | Run Khronos glTF-Validator on a remote URL |+| `inspect_model` | none | Parse GLB/glTF and return structural stats |+| `optimize_model` | none | Return optimization suggestions for a model |`render_avatar` enforces the agent's embed policy (allowed origins, allowed surfaces). Model URLs must be HTTPS — SSRF protections block private IP ranges.@@ -1311,13 +1417,13 @@ Model Context Protocol endpoint — exposes three.ws as a JSON-RPC 2.0 tool serv```json{- "jsonrpc": "2.0",- "id": 1,- "method": "tools/call",- "params": {- "name": "get_avatar",- "arguments": { "id": "abc123" }- }+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {+ "name": "get_avatar",+ "arguments": { "id": "abc123" }+ }}```@@ -1341,13 +1447,13 @@ Add a single `siwx:` block to `paidEndpoint(spec)`:```jspaidEndpoint({- route: '/api/x402/my-endpoint',- // …other fields…- siwx: {- statement: 'Sign in to refresh the catalog without re-paying.',- ttlSeconds: 24 * 3600, // grant lifetime; null = permanent- expirationSeconds: 300, // SIWX message validity window- },+ route: '/api/x402/my-endpoint',+ // …other fields…+ siwx: {+ statement: 'Sign in to refresh the catalog without re-paying.',+ ttlSeconds: 24 * 3600, // grant lifetime; null = permanent+ expirationSeconds: 300, // SIWX message validity window+ },});```@@ -1365,12 +1471,12 @@ Each asset has its own SIWX grant key: the endpoint passes a `resourceUrlBuilder```json{- "siwx": {- "configured": true,- "paymentsRowCount": 42,- "noncesRowCount": 17,- "evmVerifierConfigured": true- }+ "siwx": {+ "configured": true,+ "paymentsRowCount": 42,+ "noncesRowCount": 17,+ "evmVerifierConfigured": true+ }}```@@ -1387,10 +1493,10 @@ Paid MCP and A2MCP endpoints advertise **every settlement rail the deployment caBoth header names are read case-insensitively and both receipt names are emitted, so a buyer speaking either dialect is served. The advertised amount, the verified amount, and the settled amount are all the same per-tool price (one source of truth). Endpoints that speak this rail:-| Endpoint | Kind | Rails advertised |-|---|---|---|-| `POST /api/mcp-3d` | MCP (Streamable HTTP) | Base + X Layer (+ Solana when configured) |-| `POST /api/okx/3d/<service>` | A2MCP (decomposed 3D studio) | X Layer first, then Solana/Base |+| Endpoint | Kind | Rails advertised |+| ---------------------------- | ---------------------------- | ----------------------------------------- |+| `POST /api/mcp-3d` | MCP (Streamable HTTP) | Base + X Layer (+ Solana when configured) |+| `POST /api/okx/3d/<service>` | A2MCP (decomposed 3D studio) | X Layer first, then Solana/Base |The full seller-side wire contract — challenge fields, verify→work→settle order, the `PAYMENT-SIGNATURE` payload shape, and the settlement receipt — is pinned in [`specs/okx-agent-payments.md`](../specs/okx-agent-payments.md). The per-service catalog and runnable curls are in [`docs/okx-marketplace.md`](okx-marketplace.md).@@ -1413,30 +1519,52 @@ GET /api/coin/detail?contract=<solana-mint>**Query parameters**-| Parameter | Type | Description |-|-----------|------|-------------|-| `id` | string | CoinGecko coin id (lowercase slug). Required unless `contract` is given |-| `contract` | string | Base58 Solana mint address — resolves via the contract lookup |+| Parameter | Type | Description |+| ---------- | ------ | ----------------------------------------------------------------------- |+| `id` | string | CoinGecko coin id (lowercase slug). Required unless `contract` is given |+| `contract` | string | Base58 Solana mint address — resolves via the contract lookup |**Response**```json{- "coin": {- "id": "…", "symbol": "…", "name": "…", "image": "https://…", "rank": 1,- "categories": ["…"],- "description": "plain text, HTML stripped server-side",- "links": { "homepage": "…", "twitter": "…", "reddit": "…", "telegram": "…", "github": "…", "explorers": ["…"] },- "platforms": { "<chain>": "<contract address>" },- "market": {- "price": 0, "market_cap": 0, "fdv": 0, "volume_24h": 0,- "high_24h": 0, "low_24h": 0, "change_24h_abs": 0,- "change_pct": { "h24": 0, "d7": 0, "d30": 0, "y1": 0 },- "circulating": 0, "total": 0, "max": 0,- "ath": 0, "ath_date": "…", "ath_change_pct": 0, "atl": 0, "atl_date": "…"- },- "last_updated": "…"- }+ "coin": {+ "id": "…",+ "symbol": "…",+ "name": "…",+ "image": "https://…",+ "rank": 1,+ "categories": ["…"],+ "description": "plain text, HTML stripped server-side",+ "links": {+ "homepage": "…",+ "twitter": "…",+ "reddit": "…",+ "telegram": "…",+ "github": "…",+ "explorers": ["…"]+ },+ "platforms": { "<chain>": "<contract address>" },+ "market": {+ "price": 0,+ "market_cap": 0,+ "fdv": 0,+ "volume_24h": 0,+ "high_24h": 0,+ "low_24h": 0,+ "change_24h_abs": 0,+ "change_pct": { "h24": 0, "d7": 0, "d30": 0, "y1": 0 },+ "circulating": 0,+ "total": 0,+ "max": 0,+ "ath": 0,+ "ath_date": "…",+ "ath_change_pct": 0,+ "atl": 0,+ "atl_date": "…"+ },+ "last_updated": "…"+ }}```@@ -1479,12 +1607,14 @@ GET /api/coin/global```json{- "market": {- "market_cap_usd": 0, "volume_24h_usd": 0, "market_cap_change_pct_24h": 0,- "active_coins": 0,- "dominance": [{ "symbol": "…", "pct": 0 }]- },- "fear_greed": { "value": 0, "label": "…" }+ "market": {+ "market_cap_usd": 0,+ "volume_24h_usd": 0,+ "market_cap_change_pct_24h": 0,+ "active_coins": 0,+ "dominance": [{ "symbol": "…", "pct": 0 }]+ },+ "fear_greed": { "value": 0, "label": "…" }}```@@ -1506,9 +1636,9 @@ history to return.```json{- "current": { "value": 0, "label": "…", "ts": 0 },- "previous_week": { "value": 0, "label": "…", "ts": 0 },- "history": [{ "ts": 0, "value": 0, "label": "…" }]+ "current": { "value": 0, "label": "…", "ts": 0 },+ "previous_week": { "value": 0, "label": "…", "ts": 0 },+ "history": [{ "ts": 0, "value": 0, "label": "…" }]}```@@ -1532,18 +1662,20 @@ plus USD cost estimates from the live ETH price.```json{- "tiers": [- {- "key": "slow|standard|fast",- "base_fee_gwei": 0, "priority_fee_gwei": 0,- "gas_price_gwei": 0, "gas_price_wei": 0,- "actions": [{ "key": "transfer", "label": "ETH transfer", "gas": 21000, "usd": 0 }]- }- ],- "base_fee_gwei": 0,- "eth_price_usd": 0,- "actions": [{ "key": "transfer", "label": "ETH transfer", "gas": 21000 }],- "updated_at": 0+ "tiers": [+ {+ "key": "slow|standard|fast",+ "base_fee_gwei": 0,+ "priority_fee_gwei": 0,+ "gas_price_gwei": 0,+ "gas_price_wei": 0,+ "actions": [{ "key": "transfer", "label": "ETH transfer", "gas": 21000, "usd": 0 }]+ }+ ],+ "base_fee_gwei": 0,+ "eth_price_usd": 0,+ "actions": [{ "key": "transfer", "label": "ETH transfer", "gas": 21000 }],+ "updated_at": 0}```@@ -1552,6 +1684,27 @@ live). Cached 15 s — no API key required.---+### Market tools (categories, exchanges, derivatives, rates, DeFi)++Read-only, key-free proxies powering the `/categories`, `/exchanges`,+`/derivatives`, `/converter`, `/defi`, `/chains`, and `/stablecoins` pages.++| Endpoint | Upstream | Returns |+| --------------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `GET /api/coin/categories` | CoinGecko `/coins/categories` | `{ categories: [{ id, name, market_cap, market_cap_change_24h, volume_24h, top_3_coins }] }` |+| `GET /api/coin/exchanges` | CoinGecko `/exchanges` + `/simple/price` | `{ exchanges: [{ id, name, image, trust_score, trust_score_rank, volume_24h_btc, volume_24h_usd, year_established, country, url }], btc_usd, updated_at }` |+| `GET /api/coin/derivatives` | CoinGecko `/derivatives` | `{ tickers: [{ market, symbol, index_id, price, change_24h, funding_rate, open_interest, volume_24h }], updated_at }` (perpetuals only, top 100 by volume) |+| `GET /api/coin/rates` | CoinGecko `/exchange_rates` | `{ fiats: [{ code, name, unit, per_btc }], updated_at }` (USD first; `per_btc` = units per 1 BTC) |+| `GET /api/defi/protocols` | DeFiLlama `/protocols` | `{ total_tvl, protocol_count, protocols: [{ name, logo, symbol, category, chains, chain_count, tvl, change_1d, change_7d, mcap }], updated_at }` (CEX category excluded; top 100) |+| `GET /api/defi/chains` | DeFiLlama `/v2/chains` | `{ total_tvl, chain_count, chains: [{ name, tvl, token_symbol, share_pct }], updated_at }` (top 100) |+| `GET /api/defi/stablecoins` | DeFiLlama `stablecoins.llama.fi` | `{ total_mcap, count, stablecoins: [{ name, symbol, price, peg_type, peg_mechanism, circulating_usd, chains, chain_count }], updated_at }` (top 100) |++All are GET-only, CORS-open, rate-limited per IP, and return `502 upstream_error`+when their source is briefly unavailable. Cache windows: 300 s (categories,+rates, DeFi), 120 s (exchanges), 60 s (derivatives). No API key required.++---+### Related news```@@ -1565,6 +1718,150 @@ feeds directly (`source: "rss"`).---+## Unified API — `/api/v1/x` aggregator++One catch-all route (`api/v1/x/[...slug].js`) bundles every third-party API+three.ws re-offers as one API, registered in `api/v1/_providers.js`. Adding a+new upstream — or a new endpoint on an existing one — is a descriptor there;+no new route file. Providers today: **CoinGecko** (`coingecko`), **DefiLlama**+(`defillama`), **Jupiter** (`jupiter`, Solana prices/quotes/search),+**DexScreener** (`dexscreener`, DEX pairs/search/profiles/boosts for any+token), **Solana reads** (`solana`, balance/token-holdings/token-supply/+largest-holders/transaction/account/priority-fees via public RPC),+**OpenAI-compatible LLM** (`openai`).++```+GET /api/v1/x # discovery: every provider + endpoint+GET /api/v1/x/<provider>/<endpoint>?… # most endpoints (GET)+POST /api/v1/x/<provider>/<endpoint> # a few (e.g. openai/chat)+```++Each call resolves to one of four billing lanes, in this order:++| Lane | How | Notes |+| -------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------- |+| **free** | send no credentials on an endpoint marked `free` | per-IP quota, zero setup — see below |+| **BYOK** | send your own upstream key via the provider's header (e.g. `x-provider-key`) | pure pass-through, no markup, no key custody |+| **plan** | authenticate with a three.ws API key / OAuth token / session | uses the platform's upstream key, counts against your plan |+| **x402** | send no credentials, no free quota left | pay per call in USDC — the standard HTTP 402 challenge |++### The free tier++This is what makes "free crypto API" true instead of marketing copy: an agent+can call a `free`-marked endpoint with **zero wallet setup** and get real data.+Each free-marked endpoint descriptor carries its own quota —+`free: { perMin, perDay }` — enforced per (provider, endpoint, IP). Both+windows must pass; whichever one blocks a request drives the response headers.++```bash+curl -s "https://three.ws/api/v1/x/coingecko/price?ids=solana"+```++```json+{+ "data": { "solana": { "usd": 141.23 } },+ "_meta": {+ "provider": "coingecko",+ "endpoint": "price",+ "billing": "free",+ "free_remaining": { "per_min": 29, "per_day": 1999 }+ }+}+```++**Response headers on every free-lane call:**++| Header | Meaning |+| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |+| `X-Free-Tier: 1` | this response was served on the free lane |+| `RateLimit-Limit` / `RateLimit-Remaining` / `RateLimit-Reset` | the quota window that governed this request (burst `perMin` if it was the tighter one, else the daily `perDay` budget) |+| `X-Free-Tier-Reset` | only sent when the quota is exhausted — ISO timestamp for when the free lane reopens |++Once the quota is exhausted, the exact same URL keeps working — it just falls+through to the standard x402 402 challenge (pay per call), or succeeds+immediately if you send a three.ws API key or a BYOK header instead. No dead+end, no silent downgrade.++**Current free quotas** (also machine-readable via `GET /api/v1/x` below —+every endpoint's `free` field is `{ perMin, perDay }` or `false`):++| Provider/endpoint | perMin | perDay |+| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------ |+| `coingecko/price`, `coingecko/markets` | 30 | 2000 |+| `defillama/protocols`, `defillama/tvl` | 30 | 2000 |+| `jupiter/price`, `jupiter/quote`, `jupiter/token-search` | 20 | 2000 |+| `dexscreener/token`, `dexscreener/search`, `dexscreener/pair` | 30 | 3000 |+| `dexscreener/profiles`, `dexscreener/boosts` | 10 | 500 |+| `solana/balance`, `/token-holdings`, `/token-supply`, `/largest-holders`, `/transaction`, `/account`, `/priority-fees` | 20 | 2000 |+| `openai/chat` | not free — real per-call LLM spend, BYOK or plan/x402 only |++**DexScreener** (`dexscreener`) — live DEX pair data for any token: price,+liquidity, volume, 24h change, txns. Works for any chain DexScreener indexes,+not just Solana.++```bash+curl -s "https://three.ws/api/v1/x/dexscreener/token?addresses=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"+```++**Solana reads** (`solana`) — public-RPC reads with no key required: SOL+balance, SPL token holdings, mint supply, largest-holder concentration, a+transaction by signature, raw account info, and current prioritization fees.++```bash+curl -s "https://three.ws/api/v1/x/solana/balance?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"+```++### Discovery++```+GET /api/v1/x+```++Returns every provider and endpoint, each endpoint's price (USDC atomics),+required OAuth scope, and its `free` quota (or `false`):++```json+{+ "data": {+ "base_url": "/api/v1/x",+ "billing": { "byok": "…", "plan": "…", "free": "…", "x402": "…" },+ "providers": [+ {+ "id": "coingecko",+ "name": "CoinGecko",+ "category": "crypto-market-data",+ "key": "optional",+ "byok": true,+ "endpoints": [+ {+ "id": "price",+ "method": "GET",+ "path": "/api/v1/x/coingecko/price",+ "scope": "agents:read",+ "price_usdc_atomics": "1000",+ "summary": "Spot price for one or more coins in any fiat/crypto.",+ "params": { "ids": "…" },+ "free": { "perMin": 30, "perDay": 2000 }+ }+ ]+ }+ ]+ }+}+```++### BYOK / plan / x402 lanes++BYOK sends the provider's own key header (e.g. `x-provider-key`) and gets pure+pass-through with no markup. Plan callers send `Authorization: Bearer+<three.ws API key>` (or an OAuth token, or a browser session) and pay the+endpoint's price against their plan. Neither present, and the free quota (if+any) is exhausted → the standard x402 `HTTP 402` challenge (see+[x402 Paid Endpoints](#x402-paid-endpoints--sign-in-with-x-siwx) above for the+wire format); pay in USDC and the identical upstream call runs.++---+## Animations Library API```@@ -1577,10 +1874,10 @@ Each entry's `url` is an absolute CDN URL to the baked clip JSON (`THREE.Animati**Query parameters** (optional — omit for the full catalog)-| Param | Description |-| --- | --- |-| `limit` | Page size, `1`–`1000`. When set, the response is a bounded page instead of the whole catalog — use this to keep a single response small as the library grows. |-| `offset` | Zero-based start index into the ordered catalog. Default `0`. |+| Param | Description |+| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `limit` | Page size, `1`–`1000`. When set, the response is a bounded page instead of the whole catalog — use this to keep a single response small as the library grows. |+| `offset` | Zero-based start index into the ordered catalog. Default `0`. |The manifest is a stable ordered array, so paging is offset-based. A paged response adds `offset` and `next_offset` (`null` on the last page); `total` is always the full catalog size. Page until `next_offset` is `null`:@@ -1595,19 +1892,19 @@ Omitting `limit` returns the full array exactly as before (no `offset`/`next_off```json{- "clips": [- {- "name": "mx-hip-hop-dancing",- "label": "Hip Hop Dancing",- "icon": "💃",- "loop": true,- "duration": 4.4,- "bytes": 1174283,- "url": "https://cdn.three.ws/animations/library/clips/mx-hip-hop-dancing.json"- }- ],- "total": 2400,- "generated_at": "2026-07-04T00:00:00.000Z"+ "clips": [+ {+ "name": "mx-hip-hop-dancing",+ "label": "Hip Hop Dancing",+ "icon": "💃",+ "loop": true,+ "duration": 4.4,+ "bytes": 1174283,+ "url": "https://cdn.three.ws/animations/library/clips/mx-hip-hop-dancing.json"+ }+ ],+ "total": 2400,+ "generated_at": "2026-07-04T00:00:00.000Z"}```@@ -1627,7 +1924,7 @@ Returns public platform configuration. No auth required. CORS open.```json{- "walletConnectProjectId": "..."+ "walletConnectProjectId": "..."}```@@ -1649,21 +1946,21 @@ Responses always include `total`, `limit`, and `offset`.## Error codes-| Code | HTTP Status | Description |-|------|-------------|-------------|-| `UNAUTHORIZED` | 401 | Missing or invalid auth |-| `FORBIDDEN` | 403 | Authenticated but not allowed |-| `NOT_FOUND` | 404 | Resource doesn't exist |-| `RATE_LIMITED` | 429 | Too many requests |-| `INVALID_INPUT` | 400 | Request body validation failed |-| `AGENT_NOT_FOUND` | 404 | Agent ID not found |-| `WIDGET_NOT_FOUND` | 404 | Widget ID not found |-| `CHAIN_NOT_SUPPORTED` | 400 | chainId not in supported list |-| `IPFS_FAILED` | 503 | IPFS pinning service unavailable |-| `LLM_ERROR` | 502 | LLM provider returned an error |-| `TTS_LIMIT_EXCEEDED` | 429 | Character limit for TTS exceeded |-| `QUOTA_EXCEEDED` | 429 | Agent's monthly token budget exhausted |-| `EMBED_POLICY_DENIED` | 403 | Request origin blocked by agent embed policy |+| Code | HTTP Status | Description |+| --------------------- | ----------- | -------------------------------------------- |+| `UNAUTHORIZED` | 401 | Missing or invalid auth |+| `FORBIDDEN` | 403 | Authenticated but not allowed |+| `NOT_FOUND` | 404 | Resource doesn't exist |+| `RATE_LIMITED` | 429 | Too many requests |+| `INVALID_INPUT` | 400 | Request body validation failed |+| `AGENT_NOT_FOUND` | 404 | Agent ID not found |+| `WIDGET_NOT_FOUND` | 404 | Widget ID not found |+| `CHAIN_NOT_SUPPORTED` | 400 | chainId not in supported list |+| `IPFS_FAILED` | 503 | IPFS pinning service unavailable |+| `LLM_ERROR` | 502 | LLM provider returned an error |+| `TTS_LIMIT_EXCEEDED` | 429 | Character limit for TTS exceeded |+| `QUOTA_EXCEEDED` | 429 | Agent's monthly token budget exhausted |+| `EMBED_POLICY_DENIED` | 403 | Request origin blocked by agent embed policy |---@@ -1677,11 +1974,11 @@ import { AgentAPI } from '@three-ws/sdk';const api = new AgentAPI({ apiKey: 'sk_live_xxxxx' });const agents = await api.agents.list({ limit: 10 });-const agent = await api.agents.get('abc123');+const agent = await api.agents.get('abc123');const widget = await api.widgets.create({- agentId: 'abc123',- type: 'turntable',- config: { auto_rotate_speed: 0.5, preset: 'venice' }+ agentId: 'abc123',+ type: 'turntable',+ config: { auto_rotate_speed: 0.5, preset: 'venice' },});```diff --git a/docs/bnb-babt-findings.md b/docs/bnb-babt-findings.mdnew file mode 100644index 000000000..d7668dd1a--- /dev/null+++ b/docs/bnb-babt-findings.md@@ -0,0 +1,189 @@+# BABT (Binance Account Bound Token) — verification findings++**Verdict: REAL, LIVE on BSC mainnet AND testnet, and third-party queryable on-chain+today via a single free `eth_call`.** This closes the open question left in+`prompts/bnb-chain/00-CONTEXT.md` ("BABT sybil-gating is unverified"). A `hasBabt()`+lib and a free `/api/bnb/babt-check` endpoint ship alongside this doc.++Verified 2026-07-08 by direct on-chain probes against public BSC RPCs (via+`api/_lib/bnb/chains.js`) plus Binance's own developer documentation. Every number+below is a live read, not a claim taken on faith.++---++## 1. Contract identity++| Network | Address | Status |+|---|---|---|+| BSC mainnet (56) | `0x2B09d47D550061f995A3b5C6F0Fd58005215D7c8` | Deployed, verified on BscScan, actively minting |+| BSC testnet (97) | `0x984E6a7b9cb73cB7884c9ca9b1Ee625546F9D0E3` | Deployed, actively minting |++Both addresses come from Binance's own developer docs+(`developers.binance.com/docs/babt/apis-spec`) and were independently confirmed with+a raw `eth_getCode` call — real bytecode is deployed at both, not an empty/self-destructed+proxy shell:++```+$ node scripts probe (viem eth_getCode via getPublicClient from chains.js)+mainnet 0x2b09d47d550061f995a3b5c6f0fd58005215d7c8 → bytecode length 3622 bytes, has code: true+testnet 0x984E6a7b9cb73cB7884c9ca9b1Ee625546F9D0E3 → bytecode length 3622 bytes, has code: true+```++Both contracts respond to `name()` with the string `"Binance Account Bound Token"` and+to `totalSupply()`:++```+mainnet name() = "Binance Account Bound Token" totalSupply() = 1164243+testnet name() = "Binance Account Bound Token" totalSupply() = 1252+```++The mainnet contract is BscScan-listed with 1,163,690+ holders and 1.4M+ transactions+as of late June 2026 — this is a heavily used, actively minting production system, not+an abandoned experiment. The testnet deployment also has real mint activity (1,252+tokens), so — contrary to the working assumption in `00-CONTEXT.md` — **a testnet+deployment does exist** and can be used for our normal testnet-first flow, though it+holds far fewer real KYC'd identities than mainnet (developers testing the mint flow,+not real Binance users) and its `eth_getLogs` (archive-node history) is not available on+the free public RPC we use — direct `eth_call` reads (`balanceOf`, `tokenIdOf`,+`totalSupply`) work fine on both networks.++## 2. Interface — real read proof++BABT "extends from ERC-721" (per Binance's own docs) but is a soulbound (SBT) variant:+non-transferable after mint, and revocable/re-mintable by Binance to a new wallet (which+rotates the `tokenId` — Binance's docs explicitly warn callers not to treat `tokenId` as+a stable identity; use the token metadata's immutable `id` field for that instead).++Read functions relevant to third-party gating:++| Function | Params | Returns | Purpose |+|---|---|---|---|+| `balanceOf(address owner)` | `owner` | `uint256` | 0 or 1 — the standard "does X hold a BABT" check |+| `tokenIdOf(address from)` | `from` | `uint256` | current token id for a holder (reverts if none) |+| `ownerOf(uint256 tokenId)` | `tokenId` | `address` | reverse lookup |+| `totalSupply()` | — | `uint256` | running mint count |++**Live proof against a real mainnet holder**, found by scanning recent `Transfer`+(mint) events on the mainnet contract and reading the resulting holder back through+`balanceOf`/`tokenIdOf` — no test double, no mock:++```+mint event found in blocks 108689374–108694374:+ holder = 0x04d1c36842430a169d132ada68006e6bb9e3808b+ tokenId (from Transfer log) = 0x1417cf++balanceOf(0x04d1c36842430a169d132ada68006e6bb9e3808b) = 1+tokenIdOf(0x04d1c36842430a169d132ada68006e6bb9e3808b) = 1316815++sanity check — balanceOf(0x000000000000000000000000000000000000dEaD) = 0+```++`balanceOf` returning `1` for a real, freshly-minted holder and `0` for the burn+address is exactly the expected soulbound-membership signal, and it cost one+`eth_call` against a free public RPC — no API key, no Binance account, no rate-limited+private endpoint.++## 3. Can an arbitrary third party query this today?++**Yes, unconditionally, for free.** `balanceOf`/`tokenIdOf` are public `view` functions+on a verified contract reachable through any standard BSC RPC (the same public+endpoints `api/_lib/bnb/chains.js` already uses for everything else in this campaign).+No API key, allowlist, or Binance relationship is required to *read* BABT ownership —+only to *mint* one (that part does require a KYC'd Binance account and wallet+signature, which is the whole point).++Binance/BNB Chain actively encourage this: BNB Chain's own blog post ("How to+Integrate BAB Tokens") exists specifically to help third-party projects gate features+on BABT ownership, and points to the same `developers.binance.com/docs/babt` docs used+here. No usage terms restrict read-only on-chain verification; Binance's BABT FAQ does+not impose additional restrictions on third-party integrations beyond standard BNB+Chain project participation.++## 4. Limitations (documented honestly — do not overstate)++- **KYC dependency, not our KYC.** A "holds BABT" signal proves the address is bound+ to *some* identity-verified Binance account — it says nothing about who that person+ is, and we cannot verify KYC ourselves; we trust Binance's attestation. Anyone who+ never completed Binance Identity Verification (or never bothered getting a Binance+ account) simply won't have one, whether or not they're a real unique human.+- **Binance-account gated, not wallet-gated.** A single KYC'd person can (per Binance's+ own docs) revoke and re-mint their BABT to a different wallet, which changes the+ `tokenId` returned by `tokenIdOf` for that wallet. `balanceOf` on the old wallet+ correctly returns `0` after a revoke, so the *current* check is always accurate, but+ historical `tokenId` values are not stable identity anchors.+ Binance's docs explicitly say: don't use `tokenId` as identity — the (private,+ off-chain) metadata `id` field is the stable identifier, and it is not something a+ third-party contract can read on-chain.+ Practical consequence for sybil-resistance: BABT proves "this address belongs to+ *a* KYC'd Binance user right now," not "this is address is permanently tied to+ person P forever" — good enough for point-in-time gating (mint an NFT, join an+ allowlist), not for building a long-lived on-chain identity graph.+ It does **not**, by itself, stop one KYC'd person from participating from N different+ addresses *sequentially* (mint BABT on wallet A, use it, ask Binance to re-mint to+ wallet B) — though each re-mint requires going back through Binance's flow, which+ raises the cost of doing this at scale far above a normal sybil attack.+- **Mainnet-primary.** The overwhelming majority of real KYC identities (1.16M++ holders) are on mainnet; the testnet contract is a real, live, minting deployment+ useful for exercising *our* integration code end-to-end, but it does not carry real+ user identities — do not treat a testnet-only check as meaningful sybil resistance.+- **No SDK is required or exists as an npm package** — the interface is 4 tiny read+ functions on a verified contract, callable directly via any EVM client (we use viem,+ already a dependency). Nothing to install.+- **Binance-operated, single point of trust.** Unlike a decentralized identity+ protocol, minting/revocation policy is entirely Binance's — an outage or policy+ change on Binance's side affects who *can* mint, not the on-chain read path itself+ (already-minted tokens remain independently readable).++## 5. Honest comparison vs. other sybil-resistance options++| Signal | Chain | KYC-backed | Third-party read cost | Holder base (2026-07) | Centralization |+|---|---|---|---|---|---|+| **BABT** | BSC only (mainnet + testnet) | Yes — real government-ID KYC via Binance | Free, 1 `eth_call`, no API key | 1.16M+ mainnet | Single company (Binance) issues + can revoke |+| Gitcoin Passport | Any EVM (off-chain aggregator, on-chain attestations via EAS) | No — behavioral/stamp aggregation (Discord age, ENS, BrightID, etc.), not government ID | Free reads via EAS/Passport API | Millions of stamps across many chains, no single "holder count" | Decentralized scoring, no single revoker |+| World ID | Any chain via bridge (Worldcoin/World Chain native) | Yes — biometric (iris scan via Orb), not government ID | Free on-chain verify (semaphore proof) | Tens of millions of Orb-verified humans globally, chain-agnostic | Single foundation (Tools for Humanity) controls Orb hardware/enrollment |+| Coinbase "Verified" attestations (Base) | Base/Ethereum | Yes — Coinbase KYC | Free on-chain read (EAS attestation) | Coinbase's KYC'd user base (not published as an on-chain holder count) | Single company (Coinbase) |++**Where BABT wins for a BNB-Chain-native product:** it is the *cheapest, simplest*+KYC-backed signal to integrate on BSC specifically — one `balanceOf` call, zero setup,+zero dependency on an off-chain oracle or bridge, and it is already deployed with over+a million real holders. For a three.ws feature that specifically targets the BNB Chain+ecosystem (matching this campaign's "unique to BNB Chain" framing), it's a strong fit.++**Where it loses:** it is chain-local (BSC only — a Solana- or Base-native product gets+nothing from it) and single-issuer (Binance controls minting policy entirely, unlike+World ID's dedicated identity infrastructure or Gitcoin's decentralized scoring). Coinbase's+Base-native equivalent is the closer functional peer, but is comparably centralized to+one company rather than being an independent identity network. If the goal were+maximum decentralization or cross-chain portability, World ID or Gitcoin Passport are+the better fit; if the goal is "cheapest KYC-backed signal specifically for a BSC+product, today," BABT wins outright — free, live, and provably real.++## 6. What shipped++Given the verdict above (real + third-party-queryable), the build half of this spike+shipped:++- **`api/_lib/bnb/babt.js`** — `hasBabt(address, network?, opts?)` reads `balanceOf`+ (and, when positive, `tokenIdOf`) against the real contract via+ `api/_lib/bnb/chains.js`. Returns+ `{ address, network, holdsBabt, tokenId, contract, checkedAt }`. Defaults to+ mainnet (where the real KYC'd holder base lives); `network: 'bscTestnet'` is+ supported for exercising the integration without touching mainnet.+- **`GET /api/bnb/babt-check?address=&network=`** — free, rate-limited (reuses the+ existing `limits.publicIp` bucket), validates the address, and surfaces+ `contract_unreachable` (502) honestly on an RPC outage rather than silently+ returning a false negative.+- **`tests/bnb-babt.test.js`** — unit tests for `hasBabt` (mocked `balanceOf`/`+ tokenIdOf` reads: `>0` → `holdsBabt:true`, `0` → `false`, contract-read failure →+ typed error) and the endpoint (input validation, success, upstream failure).++## Sources++- BscScan mainnet contract: https://bscscan.com/token/0x2b09d47d550061f995a3b5c6f0fd58005215d7c8+- Binance BABT developer docs: https://developers.binance.com/docs/babt/introduction+ and https://developers.binance.com/docs/babt/apis-spec+- BNB Chain integration guide: https://www.bnbchain.org/en/blog/how-to-integrate-bab-tokens+- Binance BABT FAQ: https://www.binance.com/en/support/faq/frequently-asked-questions-on-binance-account-bound-bab-token-adbd05fe149344d59a348f82d5bf359d+- Live probes: raw `eth_getCode`/`eth_call` against public BSC mainnet + testnet RPCs,+ 2026-07-08 (this repo, via `api/_lib/bnb/chains.js`; see `tests/bnb-babt.test.js` and+ `prompts/bnb-chain/PROGRESS.md` for the captured output).diff --git a/docs/coin-pages.md b/docs/coin-pages.mdindex 575567ae2..8e4408946 100644--- a/docs/coin-pages.md+++ b/docs/coin-pages.md@@ -56,8 +56,7 @@ one cross-links back into the markets table and the coin detail pages.Every top coin as a tile in a squarified treemap, **sized by market cap** and**colored by its price move** (green up, red down, brightness scaling with the-move). Toggle the color between 24h and 7d, and the set between top 50 and top-100. Hover any tile for a price · 24h · 7d · market-cap tooltip; click it to open+move). Toggle the color between 24h and 7d, and the set between top 50 and top 100. Hover any tile for a price · 24h · 7d · market-cap tooltip; click it to openthe coin's detail page. The layout is computed client-side from the existing`/api/coin/markets` feed — no extra endpoint.@@ -88,19 +87,51 @@ highlighted. Add coins with the search type-ahead; the selection is mirrored to`?ids=…` so any matchup is a shareable link. Reuses `/api/coin/markets` (search),`/api/coin/detail`, and `/api/coin/ohlc` — no new endpoint.+## More market tools++Eight further tools round out the suite, same design system, same "real key-free+data" rule:++- **`/screener`** — filter the top 250 coins by search, gainers/losers, minimum+ market cap, and minimum 24h volume; every column sorts. Reuses+ `/api/coin/markets` (no new endpoint).+- **`/categories`** — every crypto sector ranked by market cap with 24h change,+ volume, and the top coins in each. New `/api/coin/categories` (CoinGecko+ `/coins/categories`).+- **`/exchanges`** — top exchanges by trust score and 24h volume (USD, derived+ from the live BTC price). New `/api/coin/exchanges`.+- **`/derivatives`** — perpetual-futures markets: price, funding rate, open+ interest, volume, filterable by index. New `/api/coin/derivatives`.+- **`/converter`** — convert any crypto ⇄ any major fiat at live rates+ (USD-anchored math covers all four directions). New `/api/coin/rates`+ (CoinGecko `/exchange_rates`) + `/api/coin/markets`/`detail`.+- **`/defi`** — total DeFi TVL and the top protocols by TVL (CEX reserves+ excluded), category-filterable. New `/api/defi/protocols` (DeFiLlama).+- **`/chains`** — every chain ranked by TVL with a dominance share bar. New+ `/api/defi/chains` (DeFiLlama).+- **`/stablecoins`** — stablecoins by circulating market cap with live peg+ health and backing mechanism. New `/api/defi/stablecoins` (DeFiLlama).+## Where the data comes fromAll data is real and fetched at runtime — nothing is hardcoded or sampled:-| Endpoint | Upstream | Cache |-|---|---|---|-| `/api/coin/detail` | CoinGecko `/coins/{id}` or `/coins/solana/contract/{mint}` | 60 s |-| `/api/coin/ohlc` | CoinGecko `/coins/{id}/market_chart` | 120 s |-| `/api/coin/markets` | CoinGecko `/coins/markets`, `/search` | 60 s / 300 s |-| `/api/coin/global` | CoinGecko `/global` + alternative.me Fear & Greed | 120 s |-| `/api/coin/fear-greed` | alternative.me `/fng` (current + history) | 300 s |-| `/api/coin/gas` | public Ethereum RPC `eth_feeHistory` + CoinGecko ETH price | 15 s |-| `/api/coin/news` | cryptocurrency.cv aggregator → first-party RSS fallback | 300 s |+| Endpoint | Upstream | Cache |+| ----------------------- | ---------------------------------------------------------- | ------------ |+| `/api/coin/detail` | CoinGecko `/coins/{id}` or `/coins/solana/contract/{mint}` | 60 s |+| `/api/coin/ohlc` | CoinGecko `/coins/{id}/market_chart` | 120 s |+| `/api/coin/markets` | CoinGecko `/coins/markets`, `/search` | 60 s / 300 s |+| `/api/coin/categories` | CoinGecko `/coins/categories` | 300 s |+| `/api/coin/exchanges` | CoinGecko `/exchanges` + `/simple/price` (BTC) | 300 s |+| `/api/coin/derivatives` | CoinGecko `/derivatives` | 60 s |+| `/api/coin/rates` | CoinGecko `/exchange_rates` | 300 s |+| `/api/defi/protocols` | DeFiLlama `/protocols` (CEX excluded) | 300 s |+| `/api/defi/chains` | DeFiLlama `/v2/chains` | 300 s |+| `/api/defi/stablecoins` | DeFiLlama `stablecoins.llama.fi/stablecoins` | 300 s |+| `/api/coin/global` | CoinGecko `/global` + alternative.me Fear & Greed | 120 s |+| `/api/coin/fear-greed` | alternative.me `/fng` (current + history) | 300 s |+| `/api/coin/gas` | public Ethereum RPC `eth_feeHistory` + CoinGecko ETH price | 15 s |+| `/api/coin/news` | cryptocurrency.cv aggregator → first-party RSS fallback | 300 s |Full request/response shapes: [api-reference.md → Coin Market Data API](api-reference.md#coin-market-data-api).@@ -113,17 +144,21 @@ text before they reach the client.## Code map-| Piece | Location |-|---|---|-| Markets page | [`pages/coins.html`](../pages/coins.html) + [`src/coins-index.js`](../src/coins-index.js) |-| Detail page | [`pages/coin.html`](../pages/coin.html) + [`src/coin-page.js`](../src/coin-page.js) |-| Heatmap | [`pages/heatmap.html`](../pages/heatmap.html) + [`src/heatmap.js`](../src/heatmap.js) |-| Fear & Greed | [`pages/fear-greed.html`](../pages/fear-greed.html) + [`src/fear-greed.js`](../src/fear-greed.js) |-| Gas tracker | [`pages/gas.html`](../pages/gas.html) + [`src/gas.js`](../src/gas.js) |-| Compare | [`pages/compare.html`](../pages/compare.html) + [`src/compare.js`](../src/compare.js) |-| Shared design system | [`src/coin-pages.css`](../src/coin-pages.css) (Source Serif 4 self-hosted in `public/fonts/`) |-| Shared formatters | [`src/shared/coin-format.js`](../src/shared/coin-format.js) — unit-tested in [`tests/coin-format.test.js`](../tests/coin-format.test.js) |-| API proxies | [`api/coin/`](../api/coin) — `detail.js`, `ohlc.js`, `markets.js`, `global.js`, `fear-greed.js`, `gas.js`, `news.js` |+| Piece | Location |+| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |+| Markets page | [`pages/coins.html`](../pages/coins.html) + [`src/coins-index.js`](../src/coins-index.js) |+| Detail page | [`pages/coin.html`](../pages/coin.html) + [`src/coin-page.js`](../src/coin-page.js) |+| Heatmap | [`pages/heatmap.html`](../pages/heatmap.html) + [`src/heatmap.js`](../src/heatmap.js) |+| Fear & Greed | [`pages/fear-greed.html`](../pages/fear-greed.html) + [`src/fear-greed.js`](../src/fear-greed.js) |+| Gas tracker | [`pages/gas.html`](../pages/gas.html) + [`src/gas.js`](../src/gas.js) |+| Compare | [`pages/compare.html`](../pages/compare.html) + [`src/compare.js`](../src/compare.js) |+| Screener / Categories | `pages/screener.html`, `pages/categories.html` (+ `src/*.js`, `src/*.css`) |+| Exchanges / Derivatives | `pages/exchanges.html`, `pages/derivatives.html` (+ `src/*.js`, `src/*.css`) |+| Converter | `pages/converter.html` + `src/converter.js` + `src/converter.css` |+| DeFi / Chains / Stablecoins | `pages/{defi,chains,stablecoins}.html` (+ `src/*.js`, `src/*.css`), APIs in [`api/defi/`](../api/defi) |+| Shared design system | [`src/coin-pages.css`](../src/coin-pages.css) (Source Serif 4 self-hosted in `public/fonts/`) |+| Shared formatters | [`src/shared/coin-format.js`](../src/shared/coin-format.js) — unit-tested in [`tests/coin-format.test.js`](../tests/coin-format.test.js) |+| API proxies | [`api/coin/`](../api/coin) — `detail.js`, `ohlc.js`, `markets.js`, `global.js`, `fear-greed.js`, `gas.js`, `news.js` |Routing: `vercel.json` rewrites `/coins`, `/coin/<id>`, `/heatmap`,`/fear-greed`, `/gas`, and `/compare` to their pages in production; the Vite devdiff --git a/docs/embedding.md b/docs/embedding.mdindex e1e35da72..46e9b6239 100644--- a/docs/embedding.md+++ b/docs/embedding.md@@ -68,10 +68,27 @@ The element accepts several ways to point at an agent — pick one:| `agent-id` (CAIP-10) | `agent-id="eip155:8453:0xReg…:42"` | Fully qualified on-chain reference || `agent-id` (backend) | `agent-id="a_abc123"` | Legacy backend account ID || `manifest` | `ipfs://bafy.../manifest.json` | IPFS or HTTPS manifest URL |-| `body` | `./avatar.glb` | Bare GLB for ad-hoc (vieweronly, no persona) |+| `body` | `./avatar.glb` | Bare GLB for an ad-hoc agent (viewer-only unless you also set `brain`) |When multiple are set, priority is `src` > `agent-id` > `manifest` > `body`.+**Ad-hoc agents talk too:** `body` (and a bare-GLB `src`) default to a silent+viewer. Add `brain="free"` to give it a real conversation with zero setup — no+API key, no backend, no per-token cost — routed through three.ws's host-paid+free-tier proxy. Pair it with `instructions` for a system prompt:++```html+<agent-3d+ body="./avatar.glb"+ brain="free"+ instructions="You are Maya, a friendly guide to this site."+></agent-3d>+```++Set `brain` to a specific model id (e.g. `claude-sonnet-4-6`) instead of `free`+to use a paid model via your three.ws dashboard key, or `brain="none"` to keep+it a pure display embed (see [Performance tips](#performance-tips)).+### SizingThe element has no intrinsic size — it fills its CSS `width` and `height`. Always set both or the element will collapse to zero.diff --git a/docs/embody.md b/docs/embody.mdnew file mode 100644index 000000000..d57bdf003--- /dev/null+++ b/docs/embody.md@@ -0,0 +1,103 @@+# Embody — give your agent a 3D body in one paid call++`POST /api/x402/embody` is the only embodiment endpoint in the x402 ecosystem.+An agent on any framework pays **$1 USDC** and gets back an embeddable, animated,+voiced 3D presence: a rigged GLB, a durable persona that reloads by id in any+future session, a voice, and a copy-paste `<iframe>` embed for any website.++No account, no wallet setup beyond the x402 payment itself, no API key.++## Why this exists++The three.ws thesis is that every AI agent should have a body. Until now that+capability lived behind the web UI and the MCP server. Embody puts it on the open+x402 rail: any autonomous agent can buy itself a face, drop the embed on its+site, and be seen — in a single HTTP call.++## The call++```+POST https://three.ws/api/x402/embody+```++Body:++| Field | Required | Notes |+| ----- | -------- | ----- |+| `name` | yes | Display name, ≤64 chars. |+| `prompt` | one of | Text description of the body to generate. |+| `image_url` | one of | A reference image URL to reconstruct into 3D. Provide **exactly one** of `prompt` / `image_url`. |+| `personality` | no | Flavor text stored on the persona, ≤600 chars. |+| `voice` | no | A TTS voice id (see `GET /api/tts/voices`). Defaults to `nova`. |++Response (`200`):++```json+{+ "agent_id": "persona_8f2a1c9d4b",+ "glb_url": "https://…/personas/persona_8f2a1c9d4b.glb",+ "viewer_url": "https://three.ws/viewer?src=…",+ "profile_url": "https://three.ws/embodiment/embed?persona=persona_8f2a1c9d4b",+ "embed_html": "<iframe src=\"https://three.ws/embodiment/embed?persona=persona_8f2a1c9d4b\" width=\"480\" height=\"640\" …></iframe>",+ "reload_url": "https://three.ws/api/mcp3d/persona?id=persona_8f2a1c9d4b",+ "voice": "nova",+ "rigged": true,+ "name": "Nova Scout"+}+```++- **`agent_id`** is a durable persona id. Reload the exact same body in any future+ session with `GET /api/mcp3d/persona?id=<agent_id>` (`reload_url`).+- **`embed_html`** is the real one-tag embed — drop it into any page and the body+ renders, idles, lip-syncs, and emotes (the same embodiment component the 3D+ Studio uses).+- **`profile_url`** is the hosted presence page the iframe frames.+- **`rigged`** is `true` when the auto-rig succeeded. A model that can't be+ skeleton-rigged (e.g. a non-humanoid prop) falls back to the un-rigged mesh and+ `rigged` is `false` — never a broken T-pose.++## Payment & failure semantics++Embody is **synchronous and settles on delivery**. The generate → rig → persona+chain runs inside the single paid request, and payment is captured only when a+finished body is returned. If generation times out or fails, the payment is+verified but **never settled** — you are not charged for a body you didn't get.+This is a deliberate, more consumer-fair reading than a submit-then-poll job:+there are no orphaned paid jobs, and the returned bundle is complete on the one+call. Because the chain is real GPU work, allow up to a few minutes for the+response.++## Example++```bash+# 1. Unpaid call returns a 402 challenge with the accepts[] (Solana + Base).+curl -si https://three.ws/api/x402/embody \+ -H 'content-type: application/json' \+ -d '{"name":"Nova Scout","prompt":"a friendly explorer robot in a teal jumpsuit","voice":"nova"}'++# 2. Settle the challenge with your x402 client (see docs/x402-buyer.md), then+# re-send with the X-PAYMENT header. On success you get the bundle above.+#+# 3. Reload the body later by id:+curl -s "https://three.ws/api/mcp3d/persona?id=persona_8f2a1c9d4b"++# 4. Drop the returned embed_html into any web page — the avatar renders and idles.+```++## What it reuses++Embody is a thin, honest wire over pieces that already exist — no new pipeline:++- the free NVIDIA TRELLIS **generate → auto-rig** chain the 3D Studio runs+ (`api/_mcp-studio/forge-client.js`);+- the durable **persona store** behind the embodiment embed+ (`api/_lib/persona-store.js`), so the body survives the provider URL expiring+ and reloads by id;+- the hosted **embodiment embed** page that lip-syncs and emotes.++## Related++- [Live embodiment](./mcp-studio.md) — the 3D Studio tools that persist and drive a body in chat.+- [x402 Paid Endpoints](./x402-endpoints.md) — the full paid catalog and pricing.+- [x402 Buyer Client](./x402-buyer.md) — how to settle a 402 challenge from code.+- [Create a 3D avatar](./create-3d-avatar.md) — generate a rigged avatar in the web UI.diff --git a/docs/pay-skills-listing.md b/docs/pay-skills-listing.mdindex f122160bb..32d156e5f 100644--- a/docs/pay-skills-listing.md+++ b/docs/pay-skills-listing.md@@ -26,13 +26,12 @@ are the source of truth and match what the 402 challenges advertise; verify with| `/api/mcp` | POST | $0.001 | MCP 2025-06-18 Streamable HTTP — 3D model tools + Solana agent data as JSON-RPC 2.0 || `/api/x402/model-check` | GET | $0.001 | Fetch a glTF/GLB from a URL, return vertex/triangle counts, materials, textures, animations, extensions, and optimization hints. CDP-Bazaar-cataloged. || `/api/x402/mint-to-mesh` | GET | $0.001 | Pass a Solana SPL mint, get a binary glTF (GLB) cube themed for that token (color + texture derived from on-chain metadata). CDP-Bazaar-cataloged. |-| `/api/insights/revenue-vision` | GET | $0.001 | Hand over a `mission_brief`, get back a Claude-generated `{ insight, recommended_move, confidence }` payload. CDP-Bazaar-cataloged. || `/api/x402/symbol-availability` | GET | $0.001 | Pre-launch ticker collision check against three.ws's pump.fun mint index; returns exact and trigram-similar matches || `/api/x402/skill-marketplace` | GET | $0.001 | List active skill listings and prices across all three.ws agents; filter by skill name to find the cheapest provider || `/api/x402/permit2-paid-demo` | GET | $0.001 | Permit2 + EIP-2612 gas-sponsoring demo (Base only). Forces the gasless Permit2 path for fresh wallets holding USDC but zero ETH. Listed only when CDP credentials are configured. || `/api/x402/onchain-identity-verify` | GET | $0.005 | Verify an agent's ownership of a Solana contract/mint from three.ws's on-chain identity index; returns tx_hash + wallet evidence || `/api/x402/agent-reputation` | GET | $0.01 | Reputation snapshot for a three.ws agent: USDC paid in, distinct payers, deployed mints, distribution success rate, attestation count |-| `/api/x402/pump-agent-audit` | GET | $0.02 | Full operational audit of a pump.fun agent-payments token: USDC in, distribute/buyback history, latest error reasons, risk flags |+| `/api/x402/fact-check` | POST | $0.10 | Sourced fact-check verdict (supported/contradicted/mixed/insufficient) with cited sources, authority weights, and a SHA-256 attestation || `/api/x402/mint-to-mesh-batch` | POST | $0.05 | Resolve 1–10 Solana SPL mints to themed GLB cubes in one call; per-mint failures report individually || `/api/x402/pump-launch` | POST | $5.00 | Deploy a brand-new pump.fun token in one paid call. Supply name + symbol + (metadataUri or imageUrl); the server fronts the SOL deploy cost and signs the create-coin tx. Creator rewards accrue to any Solana wallet you nominate; optional vanity mint address. Returns mint + tx signature + pump.fun URL |@@ -74,7 +73,7 @@ const { glb } = await res2.json(); // base64 GLB bytes## CORS-All paid endpoints (`/api/mcp`, `/api/x402/*`, `/api/insights/revenue-vision`) and the+All paid endpoints (`/api/mcp`, `/api/x402/*`) and thepublic discovery docs (`/.well-known/x402`, `/.well-known/x402.json`, `/openapi.json`)respond with `Access-Control-Allow-Origin: *` on both the OPTIONS preflight and theactual request. The CORS layer also exposes `PAYMENT-REQUIRED`, `x-payment-response`,diff --git a/docs/spatial-mcp.md b/docs/spatial-mcp.mdnew file mode 100644index 000000000..84302c2c4--- /dev/null+++ b/docs/spatial-mcp.md@@ -0,0 +1,103 @@+# Spatial MCP — return 3D as a native MCP response++Spatial MCP is an open shape for returning a **live, interactive 3D scene** as an MCP tool result instead of a URL in text. A conformant host renders it inline — orbit, animate, place in AR — with an embedded component. three.ws is the reference implementation; the shape is renderer-agnostic and carries **no** payment, wallet, or coin surface, so it drops into crypto-free app stores unchanged.++- **Spec:** [`specs/SPATIAL_MCP.md`](../specs/SPATIAL_MCP.md) (v0.1, CC0)+- **Validator (code):** [`api/_lib/spatial-mcp.js`](../api/_lib/spatial-mcp.js) — `validateSpatialArtifact()`, `buildSpatialArtifact()`+- **Validator (MCP tool):** `validate_spatial_response({ artifact })` on the three.ws 3D Studio server+- **Reference renderer:** [`/spatial-mcp`](https://three.ws/spatial-mcp) — `public/spatial-mcp/spatial-renderer.js`++## Quick start — emit a conformant artifact++Put the artifact in your tool result's `structuredContent`. Only `spatialMcpVersion`, `kind`, and `scene.glbUrl` are required:++```js+import { buildSpatialArtifact } from './spatial-mcp.js';++const spatial = buildSpatialArtifact({+ glbUrl: 'https://cdn.example.com/model.glb', // https .glb — required+ kind: 'model', // model | mesh | avatar | rigged-model | scene+ viewerUrl: 'https://example.com/viewer?src=…',+ prompt: 'a battle-worn sci-fi helmet',+});++return {+ content: [{ type: 'text', text: 'Here is your 3D model.' }],+ structuredContent: { glbUrl: spatial.scene.glbUrl, spatial },+};+```++`buildSpatialArtifact` always returns a valid artifact and omits any field you don't provide — no empty scaffolding.++## Validate before you ship++```js+import { validateSpatialArtifact } from './spatial-mcp.js';++const { valid, errors, warnings } = validateSpatialArtifact(spatial);+if (!valid) throw new Error('non-conformant: ' + errors.map(e => `${e.path}: ${e.message}`).join('; '));+```++`errors` and `warnings` each name the offending `path` and the fix, so you can correct output rather than guess. Wire it into CI as an invariant over every 3D tool's real output (three.ws does — see `tests/spatial-mcp.test.js`).++Agents can validate over MCP without importing anything:++```jsonc+// tools/call → validate_spatial_response+{ "artifact": { "spatialMcpVersion": "0.1", "kind": "model",+ "scene": { "glbUrl": "https://cdn.example.com/model.glb", "format": "glb" } } }+// → structuredContent: { valid: true, errors: [], warnings: [...] }+```++## Adopt from a foreign tool result++If your existing 3D tool returns some other shape, a tiny adapter makes it conformant — no change to your generation pipeline:++```js+// Your tool already returns something like this:+const foreign = { model_url: 'https://cdn.example.com/model.glb', thumbnail: null, name: 'A helmet' };++// A 6-line adapter → conformant artifact:+function toSpatialArtifact(f) {+ return {+ spatialMcpVersion: '0.1',+ kind: 'model',+ scene: { glbUrl: f.model_url, format: 'glb', ...(f.thumbnail ? { poster: f.thumbnail } : {}) },+ camera: { autoRotate: true },+ affordances: { orbit: true, zoom: true },+ meta: { title: f.name },+ };+}+```++The live demo at [`/spatial-mcp`](https://three.ws/spatial-mcp) renders exactly this transform beside a native three.ws artifact — the same renderer displays both, proving portability.++## Render it yourself++The reference renderer is framework-free and reusable independent of three.ws:++```html+<script type="module" src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"></script>+<div id="mount" style="height:360px"></div>+<script type="module">+ import { renderSpatialArtifact } from 'https://three.ws/spatial-mcp/spatial-renderer.js';+ renderSpatialArtifact(document.getElementById('mount'), artifact);+</script>+```++It applies `camera`/`environment`/`affordances`, plays `animation` when present, offers AR when `ar` (or the GLB) supports it, and shows a designed fallback for an unusable payload — never a blank frame.++## Data minimization (required for store-safe adoption)++`meta` is human-facing only. Never place session/job/creation/prediction/trace ids, wallet addresses, prices, or any auth/coin field anywhere in the artifact. Strip them at emit time — this is what keeps the shape reusable across the Claude and OpenAI tracks.++## Who emits it on three.ws++Free 3D Studio (`structuredContent.spatial`): `forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`, `refine_model`. Paid 3D Studio: `preview_3d`. Conformance gate: `validate_spatial_response`.++## Related++- [`specs/SPATIAL_MCP.md`](../specs/SPATIAL_MCP.md) — the normative spec+- [`docs/mcp-studio.md`](./mcp-studio.md) — the free 3D Studio MCP server+- AR handoff (`ar` block) ties to the AR export path (`export_ar`, `docs/ar.md`)+- Persona hook (`persona` block) ties to the embodiment tools (prompt 07)diff --git a/docs/tutorials/animate-your-avatar.md b/docs/tutorials/animate-your-avatar.mdindex 55c9be1e2..1629d275f 100644--- a/docs/tutorials/animate-your-avatar.md+++ b/docs/tutorials/animate-your-avatar.md@@ -163,13 +163,18 @@ This is the remix loop: find a motion someone else published, open it in the Stu## Emotion and expression on the live agent-Applying clips in the Studio is the **authoring** side. On a *running* agent, the same library drives emotion and gesture automatically through two complementary channels:+Applying clips in the Studio is the **authoring** side. On a *running* agent, the same library drives emotion and gesture automatically through two channels that share one emotional state — the avatar's **Empathy Layer** ([src/agent-avatar.js](../../src/agent-avatar.js)):**Gesture slots** ([src/runtime/animation-slots.js](../../src/runtime/animation-slots.js)) — a fixed emotional vocabulary the agent plays in conversation: `idle`, `wave`, `nod`, `shake`, `think`, `celebrate`, `concern`, `bow`, `point`, `shrug`, `dance`. Each slot resolves to a concrete library clip at runtime (e.g. `celebrate` → the `celebrate` clip, `think` → `pray`). An agent picks a slot when the moment calls for it; the clip retargets onto that agent's avatar exactly as in the Studio. You can override any slot per agent via `meta.edits.animations` — point `wave` at a different clip, or map a slot to a motion you authored yourself.-**Facial expression** ([src/runtime/arkit52.js](../../src/runtime/arkit52.js)) — independent of the skeleton. If your avatar carries ARKit-52 blendshapes (most modern avatar-platform exports do, as do VRoid models), the runtime resolves those morph targets and drives expression and lip-sync directly on the face. A skeletal clip plays the body; the blendshape layer plays the eyes, brows, and mouth on top.+**Facial expression** ([src/runtime/arkit52.js](../../src/runtime/arkit52.js)) — driven from the same blend of morph targets as the gesture layer, not a separate track. If your avatar carries ARKit-52 blendshapes (most modern avatar-platform exports do, as do VRoid models), the runtime resolves those morph targets and drives expression and lip-sync directly on the face. A skeletal clip plays the body; the blendshape layer plays the eyes, brows, and mouth on top.-The division of labor: **clips move the body, blendshapes move the face, slots choose *which* body motion fits the emotion.** All three ride the same universal-rig foundation — name your bones (and your blendshapes) in a convention the resolvers know, and everything just works.+The two channels are wired to the *same* emotional state, at two different timescales, so the body and the face never disagree:++- **Momentary events** (an error just happened, a skill just finished) inject a transient emotion spike — `concern`, `celebration`, `curiosity`, and friends — that decays over seconds. A spike crossing threshold both reshapes the face immediately *and* biases the gesture slot the avatar plays next (e.g. sustained `celebration` picks the `celebrate` slot).+- **Sustained mood** — the agent's resting valence/arousal, set via `setMood()` (see [docs/tutorials/emotion-from-data.md](emotion-from-data.md)) — is the continuous baseline between events. It biases the resting face (a soft smile at high valence, a worried brow at low) and posture (lean, gaze) every frame, and, once nothing more urgent claims the gesture slot, biases *which* ambient gesture plays too: a sustained up-and-energetic mood leans toward the `celebrate` slot, a sustained down-and-subdued mood toward `concern` — the opposite bias, never the energetic one. A momentary event always takes priority over the ambient mood bias, and slot overrides via `meta.edits.animations` apply identically whether the trigger was a spike or the resting mood.++The division of labor: **clips move the body, blendshapes move the face, slots choose *which* body motion fits the emotion — and one emotional state, not two independent tracks, drives all of it.** All three ride the same universal-rig foundation — name your bones (and your blendshapes) in a convention the resolvers know, and everything just works.---diff --git a/docs/tutorials/emotion-from-data.md b/docs/tutorials/emotion-from-data.mdindex 893d2ada1..a7e08e876 100644--- a/docs/tutorials/emotion-from-data.md+++ b/docs/tutorials/emotion-from-data.md@@ -197,7 +197,7 @@ function reactIfConfident(clipOrEmoteName, { confident, useExactClip = false } =## A note on the facial layer-`agent.play()` / `agent.playEmote()` drive the *body* — the skeleton, via the shared animation-clip library. There's a separate, independent layer for the *face*: `agent.setMood(valence, arousal)` / `agent.expressEmotion(trigger, weight)` drive ARKit-52 blendshapes (smile, brow, gaze) on avatars that carry them, without touching the skeleton at all. The two compose — a `celebrate` clip moves the arms while the face layer, if you're also driving it, can separately smile — but they're distinct systems with distinct APIs. This tutorial covers the body; if you want the face to track data too, the same fetch/cooldown pattern above applies, just swapping in `setMood()`/`expressEmotion()`.+`agent.play()` / `agent.playEmote()` drive the *body* directly — the skeleton, via the shared animation-clip library, for a one-shot performance you chose explicitly. `agent.setMood(valence, arousal)` / `agent.expressEmotion(trigger, weight)` primarily drive the *face* — ARKit-52 blendshapes (smile, brow, gaze) on avatars that carry them, without touching the skeleton. They're still distinct APIs for distinct calls (`play`/`playEmote` for "perform this exact gesture now" vs. `setMood`/`expressEmotion` for "this is how the agent feels"), but they're not fully independent: once nothing more urgent (like a `play()`/`playEmote()` call or a fresh `expressEmotion()` spike) already claims the ambient gesture slot, a *sustained* `setMood()` also lightly biases which idle-time gesture the body reaches for — energetic-positive moods lean toward `celebrate`, subdued-negative moods toward `concern` — so a happy agent doesn't just smile while standing dead still. See [Animate your avatar → Emotion and expression on the live agent](animate-your-avatar.md#emotion-and-expression-on-the-live-agent) for the full wiring. This tutorial covers explicit body triggers; if you want the face (and the ambient body bias) to track data too, the same fetch/cooldown pattern above applies, just swapping in `setMood()`/`expressEmotion()`.---diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.mdindex a5afade79..719a482eb 100644--- a/docs/x402-endpoints.md+++ b/docs/x402-endpoints.md@@ -122,6 +122,7 @@ for to feed the oracle and sniper.| Endpoint | Default | Returns || ----------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------- || `/api/x402/forge` | tiered | Text/image → 3D model (price by tier; GPU-bound). See [Avatar pipeline](avatar-pipeline.md). |+| `/api/x402/embody` | $1.00 | **Embodiment.** One call, an agent buys itself a body: prompt or image in → rigged, voiced 3D avatar out, plus a durable persona id and a one-tag `<iframe>` embed for any website. Settles on delivery — a failed generation never charges. See [Embodiment](embody.md). || `/api/x402/pipeline` | per stage | **One call, full 3D asset pipeline** — text or GLB in, rigged/optimized game-ready GLB out. Ordered chain of `generate → rig → remesh → gameready → stylize`; the 402 quote is the exact sum of the requested stages. Poll free at `/api/forge?job=<id>` for per-stage progress. See [3D pipeline](3d-pipeline.md). || `/api/x402/pipeline-rig` | $0.05 | **Pipeline — Rig.** Static GLB in → animation-ready rigged GLB out (skeleton + skin weights). One paid call, durable URL. See [3D pipeline](3d-pipeline.md). || `/api/x402/pipeline-remesh` | $0.03 | **Pipeline — Remesh.** Retopologize a GLB (triangle/quad/lowpoly, repair, decimate to a face budget) with texture re-baked. GLB in → GLB out. See [3D pipeline](3d-pipeline.md). |diff --git a/package-lock.json b/package-lock.jsonindex dc344db4a..ef53c166c 100644--- a/package-lock.json+++ b/package-lock.json@@ -66,6 +66,7 @@"@aws-sdk/client-marketplace-metering": "^3.1063.0","@aws-sdk/client-s3": "^3.1063.0","@aws-sdk/s3-request-presigner": "^3.1063.0",+ "@bnb-chain/mpp": "^0.2.0","@bonfida/spl-name-service": "0.1.67","@chenglou/pretext": "^0.0.7","@coin-communities/sdk": "^1.2.1",@@ -157,6 +158,7 @@"livekit-client": "^2.19.2","livepeer": "^3.5.0","meshoptimizer": "^1.1.1",+ "mppx": "^0.6.31","multiformats": "^9.9.0","nanoid": "^3.3.11","nipplejs": "^1.0.4",@@ -4442,6 +4444,19 @@"resolved": "https://registry.npmjs.org/@better-fetch/fetch/-/fetch-1.1.21.tgz","integrity": "sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A=="},+ "node_modules/@bnb-chain/mpp": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/@bnb-chain/mpp/-/mpp-0.2.0.tgz",+ "integrity": "sha512-y/n32lXWwwV9CiCtgUXQlzbax42gx21hVGMT+LJVisOlGMmBLB7i8mL7mFFKQc5ysnUlgcEiJIa4JIO7ZU95xw==",+ "license": "MIT",+ "engines": {+ "node": ">=22"+ },+ "peerDependencies": {+ "mppx": "^0.6.28",+ "viem": "^2.51.0"+ }+ },"node_modules/@bonfida/name-offers": {"version": "0.0.4","resolved": "https://registry.npmjs.org/@bonfida/name-offers/-/name-offers-0.0.4.tgz",@@ -4534,6 +4549,12 @@"integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==","license": "(Apache-2.0 AND BSD-3-Clause)"},+ "node_modules/@cfworker/json-schema": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz",+ "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==",+ "license": "MIT"+ },"node_modules/@chainsafe/as-chacha20poly1305": {"version": "0.1.0","resolved": "https://registry.npmjs.org/@chainsafe/as-chacha20poly1305/-/as-chacha20poly1305-0.1.0.tgz",@@ -12604,6 +12625,27 @@"node": ">= 0.8"}},+ "node_modules/@modelcontextprotocol/server": {+ "version": "2.0.0-beta.2",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0-beta.2.tgz",+ "integrity": "sha512-XK+sgFntT5ZzeqtTGpT9uti+Sqmq7YJZdx/N76eLJv9UA9vKvP04Qh9Hc45LCeIHGfTKRwDG6eh4C1Hs4omyIg==",+ "license": "MIT",+ "dependencies": {+ "zod": "^4.2.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@modelcontextprotocol/server/node_modules/zod": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },"node_modules/@msgpack/msgpack": {"version": "3.1.3","resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz",@@ -17180,6 +17222,15 @@"node": ">=16"}},+ "node_modules/@scalar/openapi-types": {+ "version": "0.8.0",+ "resolved": "https://registry.npmjs.org/@scalar/openapi-types/-/openapi-types-0.8.0.tgz",+ "integrity": "sha512-WmaxVSfvY5K/TwcG2B2TU1WOe1As1uc2s7myswtP6dBlcjU3hM08SApxv/jmyGaCE8t4gO5BBhmHY4pDUfmr2g==",+ "license": "MIT",+ "engines": {+ "node": ">=22"+ }+ },"node_modules/@scure/base": {"version": "1.2.6","resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz",@@ -21391,6 +21442,12 @@"node": ">=18"}},+ "node_modules/@toon-format/toon": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@toon-format/toon/-/toon-2.3.0.tgz",+ "integrity": "sha512-/Ew9etdRQKVMnm9fDaCG0JjyAOK/O7T0M97oum1aW4W+UR8ZhVVPBanIV7oWgHBiGlnVxV9M55PWQCHofDV07w==",+ "license": "MIT"+ },"node_modules/@tootallnate/quickjs-emscripten": {"version": "0.23.0","resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",@@ -33780,6 +33837,37 @@"node": ">=0.8.19"}},+ "node_modules/incur": {+ "version": "0.4.11",+ "resolved": "https://registry.npmjs.org/incur/-/incur-0.4.11.tgz",+ "integrity": "sha512-3mAuuiaA1YaSFm5Ydz76kYZpJAkICPjN/Ep4AyldwTm4x9IsBvKhrOPH8FkzU7T/XSGu+qSN/Av4zc2n5bwYjQ==",+ "license": "MIT",+ "dependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "@modelcontextprotocol/server": "^2.0.0-alpha.2",+ "@scalar/openapi-types": "^0.8.0",+ "@toon-format/toon": "^2.1.0",+ "tokenx": "^1.3.0",+ "yaml": "^2.8.2",+ "zod": "^4.3.6"+ },+ "bin": {+ "incur": "dist/bin.js",+ "incur.src": "src/bin.ts"+ },+ "engines": {+ "node": ">=22"+ }+ },+ "node_modules/incur/node_modules/zod": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },"node_modules/indent-string": {"version": "4.0.0","resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz",@@ -40228,6 +40316,108 @@"main-event": "^1.0.0"}},+ "node_modules/mppx": {+ "version": "0.6.31",+ "resolved": "https://registry.npmjs.org/mppx/-/mppx-0.6.31.tgz",+ "integrity": "sha512-euHHDLjNa9DQdPSzpayRBhUb3YVGSNZhVAzoOPmjzqxcEb77ry59uaeSBsWr3IjSxqmpR45cB6aR0uiNSgO6kA==",+ "license": "MIT",+ "dependencies": {+ "incur": "^0.4.8",+ "ox": "0.14.27",+ "zod": "^4.4.3"+ },+ "bin": {+ "mppx": "dist/bin.js",+ "mppx.src": "src/bin.ts"+ },+ "peerDependencies": {+ "@modelcontextprotocol/sdk": ">=1.25.0",+ "elysia": ">=1",+ "express": ">=5",+ "hono": ">=4.12.18",+ "viem": ">=2.51.0"+ },+ "peerDependenciesMeta": {+ "@modelcontextprotocol/sdk": {+ "optional": true+ },+ "elysia": {+ "optional": true+ },+ "express": {+ "optional": true+ },+ "hono": {+ "optional": true+ }+ }+ },+ "node_modules/mppx/node_modules/@adraffy/ens-normalize": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz",+ "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==",+ "license": "MIT"+ },+ "node_modules/mppx/node_modules/@noble/curves": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz",+ "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==",+ "license": "MIT",+ "dependencies": {+ "@noble/hashes": "1.8.0"+ },+ "engines": {+ "node": "^14.21.3 || >=16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/mppx/node_modules/eventemitter3": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz",+ "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==",+ "license": "MIT"+ },+ "node_modules/mppx/node_modules/ox": {+ "version": "0.14.27",+ "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.27.tgz",+ "integrity": "sha512-+xhLHo/f+f4BH121/1Pomm/1vgBBda1wYiFpTvjSo8o5OcEj76Pf1hGPJiepoYMTQoTm2SKdSBvWkFWk5l07PA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/wevm"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@adraffy/ens-normalize": "^1.11.0",+ "@noble/ciphers": "^1.3.0",+ "@noble/curves": "1.9.1",+ "@noble/hashes": "^1.8.0",+ "@scure/bip32": "^1.7.0",+ "@scure/bip39": "^1.6.0",+ "abitype": "^1.2.3",+ "eventemitter3": "5.0.1"+ },+ "peerDependencies": {+ "typescript": ">=5.4.0"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },+ "node_modules/mppx/node_modules/zod": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },"node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",@@ -47055,6 +47245,12 @@"node": ">=0.6"}},+ "node_modules/tokenx": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/tokenx/-/tokenx-1.3.0.tgz",+ "integrity": "sha512-NLdXTEZkKiO0gZuLtMoZKjCXTREXeZZt8nnnNeyoXtNZAfG/GKGSbQtLU5STspc0rMSwcA+UJfWZkbNU01iKmQ==",+ "license": "MIT"+ },"node_modules/toml": {"version": "3.0.0","resolved": "https://registry.npmjs.org/toml/-/toml-3.0.0.tgz",diff --git a/package.json b/package.jsonindex 985cabc7a..e48b46df7 100644--- a/package.json+++ b/package.json@@ -46,6 +46,7 @@"multiplayer","packages/avatar-schema","packages/avatar-cli",+ "packages/defi-utils","packages/viewer-presets","packages/avatar-agent-mcp","packages/pumpfun-mcp",@@ -237,6 +238,7 @@"@aws-sdk/client-marketplace-metering": "^3.1063.0","@aws-sdk/client-s3": "^3.1063.0","@aws-sdk/s3-request-presigner": "^3.1063.0",+ "@bnb-chain/mpp": "^0.2.0","@bonfida/spl-name-service": "0.1.67","@chenglou/pretext": "^0.0.7","@coin-communities/sdk": "^1.2.1",@@ -328,6 +330,7 @@"livekit-client": "^2.19.2","livepeer": "^3.5.0","meshoptimizer": "^1.1.1",+ "mppx": "^0.6.31","multiformats": "^9.9.0","nanoid": "^3.3.11","nipplejs": "^1.0.4",diff --git a/packages/defi-utils/README.md b/packages/defi-utils/README.mdnew file mode 100644index 000000000..b49718e72--- /dev/null+++ b/packages/defi-utils/README.md@@ -0,0 +1,112 @@+# @three-ws/defi-utils++Zero-dependency¹ single source of truth for chain and token constants across the+EVM chains three.ws touches **and** Solana. Chain IDs, native gas tokens, common+token addresses, minimal ERC-20 ABI fragments, and address/amount validation ++display formatting — one place, so handlers and packages stop duplicating these+ad hoc.++Ported from the owner's SperaxOS `defi-utils` (the EVM maps are kept verbatim,+including the Sperax integration tokens **SPA** and **USDs** on Arbitrum) and+extended with a Solana section SperaxOS lacks.++> ¹ One tiny runtime dependency: `bs58`, used only to validate that a Solana+> address decodes to 32 bytes. It is already a root dependency of this repo.++## Install / import++Internal workspace package (`"private": true`) — import it by name from anywhere+in the monorepo:++```js+import {+ getChainId,+ resolveTokenAddress,+ resolveSolanaMint,+ isEvmAddress,+ isSolanaAddress,+ fmtUsd,+} from '@three-ws/defi-utils';+```++Sub-path imports are available too: `@three-ws/defi-utils/chains`,+`/validation`, `/format`.++## Usage++```js+import {+ getChainId,+ getNativeToken,+ resolveTokenAddress,+ resolveSolanaMint,+ validateAddress,+ validateSolanaAddress,+ isEvmAddress,+ isSolanaAddress,+ fmtUsd,+ fmtPct,+ fmtAmount,+} from '@three-ws/defi-utils';++getChainId('arbitrum'); // 42161 (unknown names default to Arbitrum)+getNativeToken(56); // 'BNB'+resolveTokenAddress('USDs', 42161); // '0xD74f5255D557944cf7Dd0E45FF521520002D5748'+resolveTokenAddress('SPA', 42161); // '0x5575552988A3A80504bBaeB1311674fCFd40aD4B'+resolveSolanaMint('THREE'); // 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump'++validateAddress('0x123'); // 'Invalid wallet address. Expected format: …' (null when valid)+validateSolanaAddress('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // null (valid)+isEvmAddress('0xA0b8…eB48'); // true+isSolanaAddress('0xA0b8…eB48'); // false — discriminate EVM vs Solana++fmtUsd(1234.5); // '$1,234.50'+fmtPct(5.42); // '5.42%'+fmtAmount(0.00001); // '<0.0001'+```++## Exports++### Chains & tokens (`./chains`)++| Export | Description |+|--------|-------------|+| `CHAIN_IDS` | Chain name → EVM chain ID map. |+| `getChainId(chain)` | Resolve a chain name (case-insensitive); defaults to Arbitrum (42161). |+| `NATIVE_TOKENS` | Chain ID → native gas-token symbol map. |+| `getNativeToken(chainId)` | Native gas-token symbol; defaults to `'ETH'`. |+| `isNativeToken(symbol)` | True for native aliases (ETH/BNB/MATIC/AVAX/FTM/xDAI/S). |+| `TOKEN_ADDRESSES` | Chain ID → symbol → contract address (incl. SPA/USDs on Arbitrum). |+| `resolveTokenAddress(symbol, chainId)` | Symbol → address (case-insensitive); passes through a raw `0x…` address. |+| `SOLANA_MINTS` | Solana symbol → mint (SOL/USDC/THREE). |+| `resolveSolanaMint(symbol)` | Symbol → mint; passes through a raw base58 mint. |+| `ERC20_ABI` | The six ERC-20 fragments three.ws calls (symbol/decimals/balanceOf/transfer/approve/allowance). |++### Validation (`./validation`)++| Export | Description |+|--------|-------------|+| `validateAddress(addr)` | EVM address check → error string or `null`. |+| `validateAmount(amount)` | Positive-number / `"max"` check → error string or `null`. |+| `validateSolanaAddress(addr)` | base58, 32–44 chars, decodes to 32 bytes → error string or `null`. |+| `isEvmAddress(addr)` | Boolean EVM discriminator. |+| `isSolanaAddress(addr)` | Boolean Solana discriminator. |++### Formatting (`./format`)++| Export | Description |+|--------|-------------|+| `fmtUsd(value)` | `1234.5` → `'$1,234.50'`. |+| `fmtPct(value)` | `5.42` → `'5.42%'`. |+| `fmtAmount(value)` | Magnitude-scaled precision; `0.00001` → `'<0.0001'`. |++The Solana section (`SOLANA_MINTS`, `resolveSolanaMint`, `validateSolanaAddress`,+`isEvmAddress`/`isSolanaAddress`) is the three.ws extension over the SperaxOS+source. Formatter output strings are intentionally stable — downstream snapshots+depend on the exact format.++## Test++```bash+npx vitest run packages/defi-utils+```diff --git a/packages/defi-utils/package.json b/packages/defi-utils/package.jsonnew file mode 100644index 000000000..1f2136923--- /dev/null+++ b/packages/defi-utils/package.json@@ -0,0 +1,49 @@+{+ "name": "@three-ws/defi-utils",+ "version": "0.1.0",+ "description": "Zero-dependency single source of truth for chain IDs, native tokens, token addresses, ERC-20 ABI fragments, and address/amount validation + formatting across EVM chains and Solana.",+ "keywords": [+ "three.ws",+ "defi",+ "evm",+ "solana",+ "chain-id",+ "erc20",+ "token-address",+ "address-validation"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/defi-utils"+ },+ "private": true,+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "exports": {+ ".": {+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./chains": "./src/chains.js",+ "./validation": "./src/validation.js",+ "./format": "./src/format.js"+ },+ "files": [+ "src",+ "README.md"+ ],+ "dependencies": {+ "bs58": "^6.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ }+}diff --git a/packages/defi-utils/src/chains.js b/packages/defi-utils/src/chains.jsnew file mode 100644index 000000000..f8e65a758--- /dev/null+++ b/packages/defi-utils/src/chains.js@@ -0,0 +1,263 @@+/**+ * Chain & token constants — single source of truth for chain IDs, native+ * tokens, common token addresses, and ERC-20 ABI fragments across the EVM+ * chains three.ws touches, plus a Solana section (mints + native pseudo-mint).+ *+ * Ported from the SperaxOS `defi-utils` library and extended with Solana, which+ * SperaxOS lacks and three.ws needs. EVM maps are kept verbatim; the Sperax+ * tokens (SPA, USDs on Arbitrum) are the integration constants that motivated+ * the port. Zero runtime dependencies here — the base58 work lives in+ * `validation.js`.+ */++// ============================================================================+// Chain IDs+// ============================================================================++/**+ * Canonical chain name → EVM chain ID.+ * @type {Record<string, number>}+ */+export const CHAIN_IDS = {+ arbitrum: 42_161,+ avalanche: 43_114,+ base: 8453,+ bsc: 56,+ ethereum: 1,+ gnosis: 100,+ optimism: 10,+ polygon: 137,+ sonic: 146,+};++/**+ * Resolve a chain name (case-insensitive) to its EVM chain ID. Defaults to+ * Arbitrum (42161) for unknown names — matching the SperaxOS source.+ * @param {string} chain+ * @returns {number}+ */+export const getChainId = (chain) => CHAIN_IDS[chain.toLowerCase()] ?? 42_161;++// ============================================================================+// Native gas token symbols per chain+// ============================================================================++/**+ * EVM chain ID → native gas-token symbol.+ * @type {Record<number, string>}+ */+export const NATIVE_TOKENS = {+ 1: 'ETH',+ 10: 'ETH',+ 56: 'BNB',+ 100: 'xDAI',+ 137: 'MATIC',+ 146: 'S',+ 8453: 'ETH',+ 42_161: 'ETH',+ 43_114: 'AVAX',+};++/**+ * Native gas-token symbol for a chain. Defaults to 'ETH'.+ * @param {number} chainId+ * @returns {string}+ */+export const getNativeToken = (chainId) => NATIVE_TOKENS[chainId] ?? 'ETH';++// ============================================================================+// Native token aliases+// ============================================================================++const NATIVE_ALIASES = new Set(['ETH', 'BNB', 'MATIC', 'AVAX', 'FTM', 'xDAI', 'S']);++/**+ * True when a symbol represents a native (non-ERC-20) gas token. Checks both an+ * upper-cased form and the raw symbol so mixed-case aliases like `xDAI` match.+ * @param {string} symbol+ * @returns {boolean}+ */+export const isNativeToken = (symbol) =>+ NATIVE_ALIASES.has(symbol.toUpperCase()) || NATIVE_ALIASES.has(symbol);++// ============================================================================+// Common token addresses per chain (EVM)+// ============================================================================++/**+ * EVM chain ID → token symbol (upper-case) → contract address.+ * @type {Record<number, Record<string, string>>}+ */+export const TOKEN_ADDRESSES = {+ // Ethereum Mainnet+ 1: {+ DAI: '0x6B175474E89094C44Da98b954EedeAC495271d0F',+ LINK: '0x514910771AF9Ca656af840dff83E8264EcF986CA',+ UNI: '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',+ USDC: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',+ USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',+ WBTC: '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599',+ WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',+ },+ // Optimism+ 10: {+ DAI: '0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1',+ OP: '0x4200000000000000000000000000000000000042',+ USDC: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',+ USDT: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58',+ WETH: '0x4200000000000000000000000000000000000006',+ },+ // BNB Chain+ 56: {+ BUSD: '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56',+ CAKE: '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82',+ USDC: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',+ USDT: '0x55d398326f99059fF775485246999027B3197955',+ WBNB: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',+ },+ // Polygon+ 137: {+ DAI: '0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063',+ USDC: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',+ USDT: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F',+ WETH: '0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619',+ WMATIC: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',+ },+ // Base+ 8453: {+ DAI: '0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb',+ USDC: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ WETH: '0x4200000000000000000000000000000000000006',+ },+ // Arbitrum — carries the Sperax integration tokens (SPA, USDs).+ 42_161: {+ ARB: '0x912CE59144191C1204E64559FE8253a0e49E6548',+ DAI: '0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1',+ GMX: '0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a',+ SPA: '0x5575552988A3A80504bBaeB1311674fCFd40aD4B',+ USDC: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',+ 'USDC.e': '0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8',+ USDT: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',+ USDs: '0xD74f5255D557944cf7Dd0E45FF521520002D5748',+ WBTC: '0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f',+ WETH: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',+ },+ // Avalanche+ 43_114: {+ DAI: '0xd586E7F844cEa2F87f50152665BCbc2C279D8d70',+ USDC: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',+ USDT: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7',+ WAVAX: '0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7',+ WETH: '0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB',+ },+};++/**+ * Resolve a token symbol to its contract address on a given EVM chain. If the+ * input already looks like an address (`0x` + 40 hex chars) it is returned+ * as-is. Symbol lookup is case-insensitive — some map keys are intentionally+ * mixed-case for display (`USDs`, `USDC.e`), so this matches on the+ * upper-cased form of both sides rather than assuming keys are pre-uppercased.+ * Returns `undefined` when unknown.+ * @param {string} symbol+ * @param {number} chainId+ * @returns {string | undefined}+ */+export const resolveTokenAddress = (symbol, chainId) => {+ if (symbol.startsWith('0x') && symbol.length === 42) return symbol;+ const tokens = TOKEN_ADDRESSES[chainId];+ if (!tokens) return undefined;+ const upper = symbol.toUpperCase();+ const key = Object.keys(tokens).find((candidate) => candidate.toUpperCase() === upper);+ return key ? tokens[key] : undefined;+};++// ============================================================================+// Solana section (three.ws extension — not in the SperaxOS source)+// ============================================================================++/**+ * Solana mint addresses. `SOL` is the wrapped-SOL native pseudo-mint used by+ * SPL tooling; `THREE` is the platform's promoted coin.+ * @type {Record<string, string>}+ */+export const SOLANA_MINTS = {+ SOL: 'So11111111111111111111111111111111111111112',+ USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ THREE: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+};++/**+ * Resolve a Solana token symbol (case-insensitive) to its mint. If the input+ * already looks like a base58 mint (32–44 chars, no `0x`) it is returned as-is.+ * Returns `undefined` for unknown symbols.+ * @param {string} symbol+ * @returns {string | undefined}+ */+export const resolveSolanaMint = (symbol) => {+ if (!symbol) return undefined;+ if (!symbol.startsWith('0x') && symbol.length >= 32 && symbol.length <= 44) return symbol;+ return SOLANA_MINTS[symbol.toUpperCase()];+};++// ============================================================================+// Minimal ERC-20 ABI fragments+// ============================================================================++/**+ * The read/write ERC-20 fragments three.ws actually calls: `symbol`,+ * `decimals`, `balanceOf`, `transfer`, `approve`, `allowance`.+ */+export const ERC20_ABI = [+ {+ inputs: [],+ name: 'symbol',+ outputs: [{ internalType: 'string', name: '', type: 'string' }],+ stateMutability: 'view',+ type: 'function',+ },+ {+ inputs: [],+ name: 'decimals',+ outputs: [{ internalType: 'uint8', name: '', type: 'uint8' }],+ stateMutability: 'view',+ type: 'function',+ },+ {+ inputs: [{ internalType: 'address', name: 'account', type: 'address' }],+ name: 'balanceOf',+ outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],+ stateMutability: 'view',+ type: 'function',+ },+ {+ inputs: [+ { internalType: 'address', name: 'to', type: 'address' },+ { internalType: 'uint256', name: 'amount', type: 'uint256' },+ ],+ name: 'transfer',+ outputs: [{ internalType: 'bool', name: '', type: 'bool' }],+ stateMutability: 'nonpayable',+ type: 'function',+ },+ {+ inputs: [+ { internalType: 'address', name: 'spender', type: 'address' },+ { internalType: 'uint256', name: 'amount', type: 'uint256' },+ ],+ name: 'approve',+ outputs: [{ internalType: 'bool', name: '', type: 'bool' }],+ stateMutability: 'nonpayable',+ type: 'function',+ },+ {+ inputs: [+ { internalType: 'address', name: 'owner', type: 'address' },+ { internalType: 'address', name: 'spender', type: 'address' },+ ],+ name: 'allowance',+ outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],+ stateMutability: 'view',+ type: 'function',+ },+];diff --git a/packages/defi-utils/src/format.js b/packages/defi-utils/src/format.jsnew file mode 100644index 000000000..0d42f3077--- /dev/null+++ b/packages/defi-utils/src/format.js@@ -0,0 +1,44 @@+/**+ * DeFi display formatting — ported verbatim from the SperaxOS `defi-utils`.+ * Output strings are intentionally stable: downstream snapshots depend on the+ * exact formatting, so do not "improve" these.+ */++/**+ * Format a USD value with a `$` currency symbol and 2 decimal places+ * (e.g. `1234.5` → `"$1,234.50"`).+ * @param {number} value+ * @returns {string}+ */+export function fmtUsd(value) {+ return value.toLocaleString('en-US', {+ currency: 'USD',+ maximumFractionDigits: 2,+ minimumFractionDigits: 2,+ style: 'currency',+ });+}++/**+ * Format a percentage value (e.g. `5.42` → `"5.42%"`).+ * @param {number} value+ * @returns {string}+ */+export function fmtPct(value) {+ return `${value.toFixed(2)}%`;+}++/**+ * Format a token amount with precision that scales to its magnitude: tiny+ * values collapse to `"<0.0001"`, sub-1 values get 6 decimals, sub-1000 get 4,+ * and larger values get grouped thousands with ≤2 decimals.+ * @param {number} value+ * @returns {string}+ */+export function fmtAmount(value) {+ if (value === 0) return '0';+ if (value < 0.0001) return '<0.0001';+ if (value < 1) return value.toFixed(6);+ if (value < 1000) return value.toFixed(4);+ return value.toLocaleString('en-US', { maximumFractionDigits: 2 });+}diff --git a/packages/defi-utils/src/index.js b/packages/defi-utils/src/index.jsnew file mode 100644index 000000000..3362aa99a--- /dev/null+++ b/packages/defi-utils/src/index.js@@ -0,0 +1,38 @@+/**+ * @three-ws/defi-utils — shared DeFi constants & helpers+ *+ * Single source of truth for chain IDs, native tokens, token addresses, ERC-20+ * ABI fragments, and address/amount validation + formatting across EVM chains+ * and Solana. Import from here instead of duplicating chain/token constants in+ * individual packages and API handlers.+ *+ * @example+ * import { getChainId, resolveTokenAddress, isSolanaAddress, fmtUsd } from '@three-ws/defi-utils';+ * getChainId('arbitrum'); // 42161+ * resolveTokenAddress('USDs', 42161); // '0xD74f5255…'+ * isSolanaAddress('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // true+ * fmtUsd(1234.5); // '$1,234.50'+ */++export {+ CHAIN_IDS,+ ERC20_ABI,+ NATIVE_TOKENS,+ SOLANA_MINTS,+ TOKEN_ADDRESSES,+ getChainId,+ getNativeToken,+ isNativeToken,+ resolveSolanaMint,+ resolveTokenAddress,+} from './chains.js';++export {+ isEvmAddress,+ isSolanaAddress,+ validateAddress,+ validateAmount,+ validateSolanaAddress,+} from './validation.js';++export { fmtAmount, fmtPct, fmtUsd } from './format.js';diff --git a/packages/defi-utils/src/validation.js b/packages/defi-utils/src/validation.jsnew file mode 100644index 000000000..46a4c36f2--- /dev/null+++ b/packages/defi-utils/src/validation.js@@ -0,0 +1,79 @@+/**+ * DeFi input validation — EVM address + amount checks ported verbatim from the+ * SperaxOS `defi-utils`, extended with Solana base58 address validation and+ * EVM/Solana discriminators. `validateAddress`/`validateAmount` return a+ * human-readable error string or `null` (null = valid) so callers can surface+ * the message straight to a user; the `is*` helpers return booleans.+ */++import bs58 from 'bs58';++/**+ * Validate an Ethereum address format. Returns an error message, or `null` when+ * the address is well-formed (`0x` + 40 hex chars, any case).+ * @param {string} address+ * @returns {string | null}+ */+export function validateAddress(address) {+ if (!address || !/^0x[\da-f]{40}$/i.test(address)) {+ return 'Invalid wallet address. Expected format: 0x followed by 40 hex characters.';+ }+ return null;+}++/**+ * Validate a positive amount string. Accepts the literal `"max"`+ * (case-insensitive). Returns an error message, or `null` when valid.+ * @param {string} amount+ * @returns {string | null}+ */+export function validateAmount(amount) {+ if (!amount || amount.trim() === '') {+ return 'Amount is required.';+ }+ if (amount.toLowerCase() === 'max') return null;+ const num = Number(amount);+ if (Number.isNaN(num) || num <= 0) {+ return `Invalid amount: "${amount}". Must be a positive number or "max".`;+ }+ return null;+}++/**+ * Validate a Solana address: base58, 32–44 chars, decoding to exactly 32 bytes.+ * Returns an error message, or `null` when valid.+ * @param {string} address+ * @returns {string | null}+ */+export function validateSolanaAddress(address) {+ if (!address || typeof address !== 'string') {+ return 'Invalid Solana address. Expected a base58 string.';+ }+ if (address.length < 32 || address.length > 44) {+ return 'Invalid Solana address. Expected 32–44 base58 characters.';+ }+ let decoded;+ try {+ decoded = bs58.decode(address);+ } catch {+ return 'Invalid Solana address. Contains non-base58 characters.';+ }+ if (decoded.length !== 32) {+ return 'Invalid Solana address. Must decode to 32 bytes.';+ }+ return null;+}++/**+ * True when the input is a well-formed EVM address (`0x` + 40 hex chars).+ * @param {string} address+ * @returns {boolean}+ */+export const isEvmAddress = (address) => validateAddress(address) === null;++/**+ * True when the input is a well-formed Solana address (base58, 32 bytes).+ * @param {string} address+ * @returns {boolean}+ */+export const isSolanaAddress = (address) => validateSolanaAddress(address) === null;diff --git a/packages/defi-utils/tests/defi-utils.test.js b/packages/defi-utils/tests/defi-utils.test.jsnew file mode 100644index 000000000..a80b88f99--- /dev/null+++ b/packages/defi-utils/tests/defi-utils.test.js@@ -0,0 +1,171 @@+import { describe, it, expect } from 'vitest';+import {+ CHAIN_IDS,+ ERC20_ABI,+ NATIVE_TOKENS,+ SOLANA_MINTS,+ TOKEN_ADDRESSES,+ getChainId,+ getNativeToken,+ isNativeToken,+ resolveSolanaMint,+ resolveTokenAddress,+ isEvmAddress,+ isSolanaAddress,+ validateAddress,+ validateAmount,+ validateSolanaAddress,+ fmtAmount,+ fmtPct,+ fmtUsd,+} from '../src/index.js';++describe('chain-id resolution', () => {+ it('resolves known names case-insensitively', () => {+ expect(getChainId('arbitrum')).toBe(42_161);+ expect(getChainId('Ethereum')).toBe(1);+ expect(getChainId('BSC')).toBe(56);+ expect(getChainId('base')).toBe(8453);+ });+ it('defaults unknown chains to Arbitrum', () => {+ expect(getChainId('nonexistent-chain')).toBe(42_161);+ });+ it('exposes the raw CHAIN_IDS map', () => {+ expect(CHAIN_IDS.polygon).toBe(137);+ expect(CHAIN_IDS.sonic).toBe(146);+ });+});++describe('native-token detection', () => {+ it('returns the native symbol per chain, defaulting to ETH', () => {+ expect(getNativeToken(1)).toBe('ETH');+ expect(getNativeToken(56)).toBe('BNB');+ expect(getNativeToken(137)).toBe('MATIC');+ expect(getNativeToken(99999)).toBe('ETH');+ expect(NATIVE_TOKENS[43_114]).toBe('AVAX');+ });+ it('detects native token aliases in mixed case', () => {+ expect(isNativeToken('eth')).toBe(true);+ expect(isNativeToken('BNB')).toBe(true);+ expect(isNativeToken('xDAI')).toBe(true);+ expect(isNativeToken('USDC')).toBe(false);+ });+});++describe('token resolution', () => {+ it('resolves symbols to addresses per chain', () => {+ expect(resolveTokenAddress('USDC', 1)).toBe('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48');+ expect(resolveTokenAddress('usdc', 8453)).toBe('0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913');+ });+ it('resolves the Sperax integration tokens on Arbitrum (42161)', () => {+ expect(resolveTokenAddress('SPA', 42_161)).toBe('0x5575552988A3A80504bBaeB1311674fCFd40aD4B');+ expect(resolveTokenAddress('USDs', 42_161)).toBe('0xD74f5255D557944cf7Dd0E45FF521520002D5748');+ expect(TOKEN_ADDRESSES[42_161].SPA).toBeDefined();+ });+ it('resolves mixed-case map keys regardless of input casing', () => {+ // USDs and USDC.e are stored mixed-case for display; lookup must not+ // assume every key is pre-uppercased.+ expect(resolveTokenAddress('usds', 42_161)).toBe('0xD74f5255D557944cf7Dd0E45FF521520002D5748');+ expect(resolveTokenAddress('USDS', 42_161)).toBe('0xD74f5255D557944cf7Dd0E45FF521520002D5748');+ expect(resolveTokenAddress('USDC.e', 42_161)).toBe('0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8');+ expect(resolveTokenAddress('usdc.e', 42_161)).toBe('0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8');+ });+ it('returns an address input as-is', () => {+ const addr = '0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8';+ expect(resolveTokenAddress(addr, 42_161)).toBe(addr);+ });+ it('returns undefined for unknown symbols', () => {+ expect(resolveTokenAddress('NOPE', 1)).toBeUndefined();+ expect(resolveTokenAddress('USDC', 99999)).toBeUndefined();+ });+});++describe('Solana mints', () => {+ it('resolves symbols to mints case-insensitively', () => {+ expect(resolveSolanaMint('SOL')).toBe(SOLANA_MINTS.SOL);+ expect(resolveSolanaMint('usdc')).toBe('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');+ expect(resolveSolanaMint('THREE')).toBe('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');+ });+ it('returns a mint-looking input as-is', () => {+ const mint = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+ expect(resolveSolanaMint(mint)).toBe(mint);+ });+ it('returns undefined for unknown symbols', () => {+ expect(resolveSolanaMint('NOPE')).toBeUndefined();+ expect(resolveSolanaMint('')).toBeUndefined();+ });+});++describe('EVM address validation', () => {+ it('accepts checksummed and lowercase addresses', () => {+ expect(validateAddress('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')).toBeNull();+ expect(validateAddress('0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')).toBeNull();+ expect(isEvmAddress('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')).toBe(true);+ });+ it('rejects malformed addresses with a message', () => {+ expect(validateAddress('0x123')).toMatch(/Invalid wallet address/);+ expect(validateAddress('not-an-address')).toMatch(/Invalid wallet address/);+ expect(validateAddress('')).toMatch(/Invalid wallet address/);+ expect(isEvmAddress('0x123')).toBe(false);+ });+});++describe('amount validation', () => {+ it('accepts positive numbers and "max"', () => {+ expect(validateAmount('1.5')).toBeNull();+ expect(validateAmount('max')).toBeNull();+ expect(validateAmount('MAX')).toBeNull();+ });+ it('rejects empty, zero, negative, and non-numeric amounts', () => {+ expect(validateAmount('')).toMatch(/required/);+ expect(validateAmount('0')).toMatch(/Invalid amount/);+ expect(validateAmount('-5')).toMatch(/Invalid amount/);+ expect(validateAmount('abc')).toMatch(/Invalid amount/);+ });+});++describe('Solana address validation', () => {+ it('accepts valid 32-byte base58 mints', () => {+ expect(validateSolanaAddress('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v')).toBeNull();+ expect(validateSolanaAddress('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')).toBeNull();+ expect(isSolanaAddress('So11111111111111111111111111111111111111112')).toBe(true);+ });+ it('rejects too-short strings', () => {+ expect(validateSolanaAddress('abc')).toMatch(/32–44|32-44/);+ expect(isSolanaAddress('abc')).toBe(false);+ });+ it('rejects non-base58 characters', () => {+ // 0 and O and l and I are not in the base58 alphabet; length in range.+ expect(validateSolanaAddress('0OIl0OIl0OIl0OIl0OIl0OIl0OIl0OIl0OIl')).toMatch(/base58|32 bytes/);+ });+ it('rejects EVM addresses (wrong shape for Solana)', () => {+ expect(isSolanaAddress('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')).toBe(false);+ });+});++describe('formatters (exact output)', () => {+ it('fmtUsd', () => {+ expect(fmtUsd(1234.5)).toBe('$1,234.50');+ expect(fmtUsd(0)).toBe('$0.00');+ expect(fmtUsd(1000000)).toBe('$1,000,000.00');+ });+ it('fmtPct', () => {+ expect(fmtPct(5.42)).toBe('5.42%');+ expect(fmtPct(0)).toBe('0.00%');+ expect(fmtPct(100)).toBe('100.00%');+ });+ it('fmtAmount scales precision by magnitude', () => {+ expect(fmtAmount(0)).toBe('0');+ expect(fmtAmount(0.00001)).toBe('<0.0001');+ expect(fmtAmount(0.5)).toBe('0.500000');+ expect(fmtAmount(12.3456)).toBe('12.3456');+ expect(fmtAmount(12345.678)).toBe('12,345.68');+ });+});++describe('ERC20_ABI', () => {+ it('exposes the six fragments three.ws calls', () => {+ const names = ERC20_ABI.map((f) => f.name).sort();+ expect(names).toEqual(['allowance', 'approve', 'balanceOf', 'decimals', 'symbol', 'transfer']);+ });+});diff --git a/packages/naming-mcp/package.json b/packages/naming-mcp/package.jsonindex c11cf9130..2d8c0d589 100644--- a/packages/naming-mcp/package.json+++ b/packages/naming-mcp/package.json@@ -52,6 +52,7 @@},"dependencies": {"@modelcontextprotocol/sdk": "^1.29.0",+ "@three-ws/tool-sdk": "file:../tool-sdk","zod": "^3.23.8"}}diff --git a/packages/tool-sdk/package.json b/packages/tool-sdk/package.jsonnew file mode 100644index 000000000..702df566f--- /dev/null+++ b/packages/tool-sdk/package.json@@ -0,0 +1,46 @@+{+ "name": "@three-ws/tool-sdk",+ "version": "0.1.0",+ "description": "Typed tool authoring for three.ws MCP servers: defineTool + defineExecutor + per-tool permission manifests (network allowlist, rate limits, wallet access), plus a one-call adapter into the repo's MCP tool-registration shape.",+ "keywords": [+ "three.ws",+ "mcp",+ "model-context-protocol",+ "tool-sdk",+ "zod",+ "agent-tools",+ "json-schema"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/tool-sdk"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "private": true,+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "files": [+ "src",+ "README.md"+ ],+ "engines": {+ "node": ">=18"+ },+ "scripts": {+ "test": "vitest run tests"+ },+ "dependencies": {+ "zod": "^3.23.8",+ "zod-to-json-schema": "^3.25.2"+ }+}diff --git a/packages/tool-sdk/src/define-executor.js b/packages/tool-sdk/src/define-executor.jsnew file mode 100644index 000000000..f3764f065--- /dev/null+++ b/packages/tool-sdk/src/define-executor.js@@ -0,0 +1,144 @@+// `defineExecutor` — wire a typed implementation map onto a tool defined+// with `defineTool`. Every call goes through one `invoke(apiName, params, ctx)`+// entry point that:+//+// 1. Rejects unknown API names / unimplemented methods with a structured error.+// 2. Enforces the tool's declared rate limit (if any), per API name.+// 3. Validates `params` against the API's Zod schema before calling the method.+// 4. Wraps thrown errors into `{ success: false, error: { message, code } }`+// instead of letting them propagate.+// 5. Normalizes a successful return into `{ success: true, content, state }`+// — unless the implementation already returned that shape itself (an+// implementation is free to return a full result envelope when it needs+// to set `content` and `state` to different values).+//+// Ported from the owner's SperaxOS `@sperax/plugin-sdk` (`defineExecutor.ts`);+// adapted from TypeScript to plain ESM + JSDoc, and extended with the+// rate-limit + Zod-validation enforcement this repo's permission manifest adds.++import { createRateLimiter } from './permissions.js';++/**+ * @typedef {object} ToolResult+ * @property {boolean} success+ * @property {*} [content] Present on success (and on `ExecutorError` failures,+ * as a human-readable summary — mirrors the reference SDK's shape).+ * @property {*} [state] Present on success — structured data for callers that+ * want more than the rendered `content`.+ * @property {{ message: string, code?: string, issues?: unknown, body?: unknown }} [error]+ * Present on failure.+ */++/**+ * @param {ReturnType<import('./define-tool.js').defineTool>} tool+ * @param {Record<string, (params: any, ctx?: object) => Promise<*> | *>} implementation+ * Map of API name → handler. A handler may return plain data (wrapped into+ * `{ success: true, content, state }` automatically) or a full `ToolResult`+ * envelope (passed through unchanged).+ * @returns {{+ * id: string,+ * getApiNames(): string[],+ * hasApi(name: string): boolean,+ * invoke(apiName: string, params: any, ctx?: object): Promise<ToolResult>,+ * }}+ *+ * @example+ * ```js+ * import { defineExecutor } from '@three-ws/tool-sdk';+ * import { priceTool } from './index.js';+ *+ * export const executor = defineExecutor(priceTool, {+ * async getPrice({ symbol }) {+ * const res = await fetch(`https://api.example.com/v1/price/${symbol}`);+ * const data = await res.json();+ * return { symbol, price: data.price }; // wrapped into { success: true, content, state }+ * },+ * });+ *+ * const result = await executor.invoke('getPrice', { symbol: 'ETH' });+ * ```+ */+export function defineExecutor(tool, implementation) {+ if (!tool?.manifest || !Array.isArray(tool._apis)) {+ throw new TypeError('defineExecutor: first argument must be a tool returned by defineTool()');+ }+ if (!implementation || typeof implementation !== 'object') {+ throw new TypeError('defineExecutor: an implementation map is required');+ }++ const identifier = tool.manifest.id;+ const apiByName = new Map(tool._apis.map((api) => [api.name, api]));+ const limiter = createRateLimiter(tool.manifest.permissions?.rateLimit);++ return {+ id: identifier,++ getApiNames() {+ return [...apiByName.keys()];+ },++ hasApi(apiName) {+ return apiByName.has(apiName);+ },++ async invoke(apiName, params, ctx = {}) {+ const api = apiByName.get(apiName);+ if (!api) {+ return {+ success: false,+ error: {+ message: `[${identifier}] Unknown API: "${apiName}". Supported: ${[...apiByName.keys()].join(', ')}`,+ code: 'API_NOT_FOUND',+ },+ };+ }++ const method = implementation[apiName];+ if (typeof method !== 'function') {+ return {+ success: false,+ error: { message: `[${identifier}] Method not implemented: "${apiName}"`, code: 'METHOD_NOT_IMPLEMENTED' },+ };+ }++ if (limiter && !limiter.tryTake(apiName)) {+ return {+ success: false,+ error: { message: `[${identifier}.${apiName}] rate limit exceeded`, code: 'RATE_LIMITED' },+ };+ }++ const parsed = api.parametersZod.safeParse(params ?? {});+ if (!parsed.success) {+ const message = parsed.error.issues+ .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)+ .join('; ');+ return {+ success: false,+ error: {+ message: `[${identifier}.${apiName}] invalid params: ${message}`,+ code: 'INVALID_PARAMS',+ issues: parsed.error.issues,+ },+ };+ }++ try {+ const result = await method(parsed.data, ctx);+ if (result && typeof result === 'object' && 'success' in result) {+ // The implementation already returned a full ToolResult envelope.+ return result;+ }+ return { success: true, content: result, state: result };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;+ return {+ success: false,+ content: `${identifier}.${apiName} failed: ${message}`,+ error: { message, code, body: error instanceof Error ? undefined : error },+ };+ }+ },+ };+}diff --git a/packages/tool-sdk/src/define-tool.js b/packages/tool-sdk/src/define-tool.jsnew file mode 100644index 000000000..e8dbb4d21--- /dev/null+++ b/packages/tool-sdk/src/define-tool.js@@ -0,0 +1,139 @@+// `defineTool` — declare a tool's identity, API surface, and permission+// manifest once, and derive everything else (JSON-Schema params for the+// manifest, a raw Zod shape for MCP registration, per-API metadata for the+// executor) from that single declaration.+//+// Ported from the owner's SperaxOS `@sperax/plugin-sdk` (`defineTool.ts`),+// adapted from TypeScript to plain ESM + JSDoc to match this repo's other JS+// packages, and re-scoped from a chat-UI plugin manifest (`BuiltinToolManifest`,+// LLM system-role text, marketplace category) to a portable MCP tool manifest+// with an explicit permission model. See `packages/tool-sdk/README.md` for the+// full API + a runnable example.++import { zodToJsonSchema } from 'zod-to-json-schema';++import { normalizePermissions } from './permissions.js';++/**+ * @typedef {object} PluginApiConfig+ * @property {string} name API name — the method key on the executor's+ * implementation map, and (via `toMcpTools`) the registered MCP tool name.+ * @property {string} description Short, LLM-facing description of what this+ * API does.+ * @property {import('zod').ZodObject<any>} parameters A `z.object({...})`+ * schema for the API's parameters. Converted to JSON Schema for the+ * manifest, and kept as a raw Zod shape for MCP registration.+ * @property {string} [title] Human-facing title for this specific API.+ * Defaults to the tool's `title`.+ * @property {object} [annotations] MCP `ToolAnnotations` for this API+ * (`readOnlyHint`, `idempotentHint`, `openWorldHint`, `destructiveHint`).+ */++/**+ * @typedef {object} PluginToolConfig+ * @property {string} id Unique identifier, e.g. "sns-resolve". Kebab-case.+ * @property {string} title Display name shown to the calling agent/UI.+ * @property {string} description Short description of the tool as a whole.+ * @property {string} version Semantic version, e.g. "1.0.0".+ * @property {import('./permissions.js').PluginPermissions} [permissions]+ * Permission manifest — network allowlist, rate limit, wallet access.+ * @property {PluginApiConfig[]} apis API surface of the tool. Must be non-empty.+ */++/**+ * Define a three.ws tool: convert each API's Zod parameter schema to JSON+ * Schema (for manifests / documentation) while keeping the original Zod+ * schema attached (for runtime validation in `defineExecutor` and MCP+ * registration in `toMcpTools`).+ *+ * @param {PluginToolConfig} config+ * @returns {{+ * manifest: { id: string, title: string, description: string, version: string, permissions: object, apis: Array<{ name: string, title: string, description: string, parameters: object }> },+ * _apis: Array<{ name: string, title: string, description: string, annotations: object | undefined, parametersJsonSchema: object, parametersZod: import('zod').ZodObject<any> }>,+ * _config: PluginToolConfig,+ * }}+ *+ * @example+ * ```js+ * import { defineTool, z } from '@three-ws/tool-sdk';+ *+ * export const priceTool = defineTool({+ * id: 'my-org-price-feed',+ * title: 'My Price Feed',+ * description: 'Fetches token prices from My API.',+ * version: '1.0.0',+ * permissions: { network: ['api.example.com'] },+ * apis: [{+ * name: 'getPrice',+ * description: 'Get the current USD price for a token symbol.',+ * parameters: z.object({ symbol: z.string().describe('Token ticker, e.g. "ETH"') }),+ * }],+ * });+ * ```+ */+export function defineTool(config) {+ if (!config || typeof config !== 'object') {+ throw new TypeError('defineTool: a config object is required');+ }+ const { id, title, description, version, permissions, apis } = config;++ if (!id || typeof id !== 'string') throw new TypeError('defineTool: "id" (string) is required');+ if (!title || typeof title !== 'string') throw new TypeError('defineTool: "title" (string) is required');+ if (!description || typeof description !== 'string') {+ throw new TypeError('defineTool: "description" (string) is required');+ }+ if (!version || typeof version !== 'string') throw new TypeError('defineTool: "version" (string) is required');+ if (!Array.isArray(apis) || apis.length === 0) {+ throw new TypeError('defineTool: "apis" must be a non-empty array');+ }++ const seenNames = new Set();+ const resolvedApis = apis.map((apiConfig) => {+ if (!apiConfig || typeof apiConfig !== 'object' || !apiConfig.name) {+ throw new TypeError('defineTool: every entry in "apis" needs a "name"');+ }+ if (seenNames.has(apiConfig.name)) {+ throw new TypeError(`defineTool: duplicate api name "${apiConfig.name}"`);+ }+ seenNames.add(apiConfig.name);++ if (!apiConfig.description || typeof apiConfig.description !== 'string') {+ throw new TypeError(`defineTool: api "${apiConfig.name}" needs a "description"`);+ }+ if (!apiConfig.parameters || typeof apiConfig.parameters.safeParse !== 'function') {+ throw new TypeError(`defineTool: api "${apiConfig.name}" needs a Zod schema in "parameters"`);+ }++ const jsonSchema = /** @type {Record<string, any>} */ (+ zodToJsonSchema(apiConfig.parameters, { $refStrategy: 'none', target: 'jsonSchema7' })+ );+ // zod-to-json-schema adds a top-level `$schema` meta key — strip it so+ // the manifest carries a lean, self-contained object schema.+ delete jsonSchema.$schema;++ return {+ name: apiConfig.name,+ title: apiConfig.title ?? title,+ description: apiConfig.description,+ annotations: apiConfig.annotations,+ parametersJsonSchema: jsonSchema,+ parametersZod: apiConfig.parameters,+ };+ });++ const manifest = {+ id,+ title,+ description,+ version,+ permissions: normalizePermissions(permissions),+ apis: resolvedApis.map((api) => ({+ name: api.name,+ title: api.title,+ description: api.description,+ parameters: api.parametersJsonSchema,+ })),+ };++ return { manifest, _apis: resolvedApis, _config: config };+}diff --git a/packages/tool-sdk/src/index.js b/packages/tool-sdk/src/index.jsnew file mode 100644index 000000000..5f8cd7c72--- /dev/null+++ b/packages/tool-sdk/src/index.js@@ -0,0 +1,45 @@+/**+ * @three-ws/tool-sdk+ *+ * Typed tool authoring for three.ws MCP servers: define a tool's identity,+ * API surface, and permission manifest once with `defineTool`, wire an+ * implementation with `defineExecutor`, and adapt it into a live MCP server+ * with `toMcpTools`.+ *+ * Quick start:+ * ```js+ * import { defineTool, defineExecutor, toMcpTools, z } from '@three-ws/tool-sdk';+ *+ * export const priceTool = defineTool({+ * id: 'my-org-price-feed',+ * title: 'My Price Feed',+ * description: 'Fetches live token prices.',+ * version: '1.0.0',+ * permissions: { network: ['api.example.com'], rateLimit: { calls: 30, perSeconds: 60 } },+ * apis: [{+ * name: 'getPrice',+ * description: 'Get the current USD price for a token symbol.',+ * parameters: z.object({ symbol: z.string() }),+ * }],+ * });+ *+ * export const priceExecutor = defineExecutor(priceTool, {+ * async getPrice({ symbol }) {+ * const res = await fetch(`https://api.example.com/v1/price/${symbol}`);+ * const data = await res.json();+ * return { symbol, price: data.price };+ * },+ * });+ *+ * export const mcpTools = toMcpTools(priceTool, priceExecutor);+ * ```+ *+ * See `README.md` in this package for the full API reference, permission+ * model, and a complete runnable example.+ */++export { defineTool } from './define-tool.js';+export { defineExecutor } from './define-executor.js';+export { toMcpTools } from './mcp-adapter.js';+export { guardedFetch, createRateLimiter, normalizePermissions } from './permissions.js';+export { z } from 'zod';diff --git a/packages/tool-sdk/src/mcp-adapter.js b/packages/tool-sdk/src/mcp-adapter.jsnew file mode 100644index 000000000..9004c910f--- /dev/null+++ b/packages/tool-sdk/src/mcp-adapter.js@@ -0,0 +1,97 @@+// `toMcpTools` — the piece that makes this port ours: adapt a `defineTool` ++// `defineExecutor` pair into the exact registration shape three.ws's MCP+// servers already use, so adoption is one call.+//+// Target shape (derived from `packages/naming-mcp/src/tools/*.js` and+// `packages/naming-mcp/src/index.js`'s `server.registerTool(name, { title,+// description, inputSchema, annotations }, handler)`):+//+// {+// name: string,+// title: string,+// description: string,+// inputSchema: Record<string, ZodTypeAny>, // raw Zod shape, NOT JSON Schema —+// // the MCP SDK converts this itself.+// annotations: { readOnlyHint, idempotentHint, openWorldHint, ... },+// async handler(args, extra) { ... }, // returns data on success, THROWS on failure+// }+//+// One tool-sdk API becomes one MCP tool (three.ws's convention: each MCP+// tool exposes exactly one operation). The handler throws on failure instead+// of returning a `{ success: false }` envelope, matching every hand-written+// tool in `packages/*-mcp/src/tools/` and `mcp-server/src/tools/`, whose+// server wrappers `try { await tool.handler(...) } catch (err) { ...isError }`.++const DEFAULT_ANNOTATIONS = Object.freeze({+ readOnlyHint: false,+ idempotentHint: false,+ openWorldHint: true,+});++/**+ * @param {ReturnType<import('./define-tool.js').defineTool>} tool+ * @param {ReturnType<import('./define-executor.js').defineExecutor>} executor+ * @returns {Array<{+ * name: string,+ * title: string,+ * description: string,+ * inputSchema: Record<string, import('zod').ZodTypeAny>,+ * annotations: object,+ * handler: (args: any, extra?: object) => Promise<*>,+ * }>}+ *+ * @example+ * ```js+ * import { defineTool, defineExecutor, toMcpTools, z } from '@three-ws/tool-sdk';+ * import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+ *+ * const tool = defineTool({+ * id: 'my-org-price-feed', title: 'Price Feed', description: '...', version: '1.0.0',+ * apis: [{ name: 'getPrice', description: '...', parameters: z.object({ symbol: z.string() }) }],+ * });+ * const executor = defineExecutor(tool, {+ * async getPrice({ symbol }) { return { symbol, price: 42 }; },+ * });+ *+ * const server = new McpServer({ name: 'my-server', version: '1.0.0' });+ * for (const def of toMcpTools(tool, executor)) {+ * server.registerTool(def.name, { title: def.title, description: def.description, inputSchema: def.inputSchema, annotations: def.annotations }, def.handler);+ * }+ * ```+ */+export function toMcpTools(tool, executor) {+ if (!tool?._apis || !Array.isArray(tool._apis)) {+ throw new TypeError('toMcpTools: first argument must be a tool returned by defineTool()');+ }+ if (!executor || typeof executor.invoke !== 'function') {+ throw new TypeError('toMcpTools: second argument must be an executor returned by defineExecutor()');+ }++ return tool._apis.map((api) => {+ const shape = api.parametersZod?.shape;+ if (!shape) {+ throw new TypeError(+ `toMcpTools: api "${api.name}" must declare "parameters" as a z.object({...}) schema (found no .shape)`,+ );+ }++ return {+ name: api.name,+ title: api.title,+ description: api.description,+ inputSchema: shape,+ annotations: api.annotations ?? DEFAULT_ANNOTATIONS,+ async handler(args, extra) {+ const result = await executor.invoke(api.name, args, extra ?? {});+ if (!result.success) {+ const err = new Error(result.error?.message ?? `${tool.manifest.id}.${api.name} failed`);+ if (result.error?.code !== undefined) err.code = result.error.code;+ if (result.error?.status !== undefined) err.status = result.error.status;+ if (result.error?.body !== undefined) err.body = result.error.body;+ throw err;+ }+ return result.content;+ },+ };+ });+}diff --git a/packages/tool-sdk/src/permissions.js b/packages/tool-sdk/src/permissions.jsnew file mode 100644index 000000000..3448a9fcb--- /dev/null+++ b/packages/tool-sdk/src/permissions.js@@ -0,0 +1,143 @@+// Permission-manifest primitives for @three-ws/tool-sdk.+//+// A tool declares what it is allowed to do — which hosts it may fetch from,+// how often each API may be called, and whether it may read wallet context —+// as plain, inspectable data (`PluginPermissions`, see define-tool.js). This+// module turns that declaration into two things that are cheap to enforce at+// the SDK layer, without a host runtime:+//+// 1. An in-memory token-bucket rate limiter, keyed per API name.+// 2. `guardedFetch(permissions)` — a `fetch` wrapper that throws on any+// host outside the declared `network` allowlist. Deny-by-default: a+// tool that declares no `network` permission may not fetch anything.+//+// Wallet access is declarative only — the SDK does not (and cannot) enforce+// it; enforcement stays with the host that grants a signer to the executor's+// `ctx`.++/**+ * @typedef {object} PluginPermissions+ * @property {string[]} [network] Allowlisted hostnames the executor may fetch+ * from (exact match — no wildcards). Omit or leave empty to deny all+ * outbound network access via `guardedFetch`.+ * @property {{ calls: number, perSeconds: number }} [rateLimit] Token-bucket+ * rate limit applied per API name (e.g. `{ calls: 60, perSeconds: 60 }` for+ * 60 calls/minute).+ * @property {boolean} [wallet] Whether the executor may read a wallet address+ * from its invocation context. Declarative metadata only.+ */++/**+ * Normalize a raw `permissions` config into a stable, deduplicated shape.+ * Safe to call with `undefined` — returns the "no permissions" default+ * (empty network allowlist, no rate limit, no wallet access).+ *+ * @param {Partial<PluginPermissions>} [permissions]+ * @returns {{ network: string[], rateLimit: { calls: number, perSeconds: number } | null, wallet: boolean }}+ */+export function normalizePermissions(permissions = {}) {+ const network = Array.isArray(permissions.network)+ ? [...new Set(permissions.network.filter((host) => typeof host === 'string' && host.length > 0))]+ : [];++ const rawRateLimit = permissions.rateLimit;+ const rateLimit =+ rawRateLimit &&+ Number.isFinite(rawRateLimit.calls) &&+ rawRateLimit.calls > 0 &&+ Number.isFinite(rawRateLimit.perSeconds) &&+ rawRateLimit.perSeconds > 0+ ? { calls: rawRateLimit.calls, perSeconds: rawRateLimit.perSeconds }+ : null;++ return { network, rateLimit, wallet: Boolean(permissions.wallet) };+}++/**+ * Create an in-memory token-bucket rate limiter for a normalized `rateLimit`+ * config. Returns `null` when no rate limit is declared, so callers can+ * `limiter?.tryTake(...)` unconditionally.+ *+ * Buckets are keyed by an arbitrary string (typically the API name), so one+ * limiter instance can track independent quotas per API.+ *+ * @param {{ calls: number, perSeconds: number } | null | undefined} rateLimit+ * @returns {{ tryTake(key?: string, now?: number): boolean, reset(key?: string): void } | null}+ */+export function createRateLimiter(rateLimit) {+ if (!rateLimit) return null;+ const { calls, perSeconds } = rateLimit;+ const refillPerSecond = calls / perSeconds;+ /** @type {Map<string, { tokens: number, updatedAt: number }>} */+ const buckets = new Map();++ return {+ /**+ * Attempt to take one token from the bucket identified by `key`.+ * @param {string} [key]+ * @param {number} [now] Injectable clock (ms) — primarily for tests.+ * @returns {boolean} `true` if the call is allowed, `false` if rate-limited.+ */+ tryTake(key = 'default', now = Date.now()) {+ let bucket = buckets.get(key);+ if (!bucket) {+ bucket = { tokens: calls, updatedAt: now };+ buckets.set(key, bucket);+ }+ const elapsedSeconds = Math.max(0, (now - bucket.updatedAt) / 1000);+ bucket.tokens = Math.min(calls, bucket.tokens + elapsedSeconds * refillPerSecond);+ bucket.updatedAt = now;++ if (bucket.tokens >= 1) {+ bucket.tokens -= 1;+ return true;+ }+ return false;+ },++ /**+ * Reset one bucket (by key) or every bucket (no key).+ * @param {string} [key]+ */+ reset(key) {+ if (key === undefined) buckets.clear();+ else buckets.delete(key);+ },+ };+}++/**+ * Build a `fetch`-compatible function that refuses any host outside the+ * tool's declared `network` permission. Deny-by-default: if no `network`+ * hosts are declared, every call is refused.+ *+ * @param {Partial<PluginPermissions>} permissions+ * @returns {(input: string | URL | Request, init?: RequestInit) => Promise<Response>}+ */+export function guardedFetch(permissions) {+ const { network: allowlist } = normalizePermissions(permissions);+ const allow = new Set(allowlist);++ return async function guardedFetchImpl(input, init) {+ const rawUrl = typeof input === 'string' || input instanceof URL ? input : input?.url;++ let hostname;+ try {+ hostname = new URL(rawUrl).hostname;+ } catch {+ throw Object.assign(new Error(`guardedFetch: could not parse a hostname from "${rawUrl}"`), {+ code: 'INVALID_URL',+ });+ }++ if (!allow.has(hostname)) {+ const detail = allow.size > 0 ? `allowlist: [${[...allow].join(', ')}]` : 'no hosts allowlisted (deny-all by default)';+ throw Object.assign(new Error(`guardedFetch: host "${hostname}" is not permitted — ${detail}`), {+ code: 'NETWORK_NOT_ALLOWED',+ hostname,+ });+ }++ return fetch(input, init);+ };+}diff --git a/packages/tool-sdk/tests/tool-sdk.test.js b/packages/tool-sdk/tests/tool-sdk.test.jsnew file mode 100644index 000000000..68295a78d--- /dev/null+++ b/packages/tool-sdk/tests/tool-sdk.test.js@@ -0,0 +1,370 @@+import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';+import { z } from 'zod';++import { defineTool } from '../src/define-tool.js';+import { defineExecutor } from '../src/define-executor.js';+import { toMcpTools } from '../src/mcp-adapter.js';+import { guardedFetch, createRateLimiter, normalizePermissions } from '../src/permissions.js';++// ---------------------------------------------------------------------------+// Fixtures+// ---------------------------------------------------------------------------++function makeTool(overrides = {}) {+ return defineTool({+ id: 'test-org-price-feed',+ title: 'Test Price Feed',+ description: 'Fetches token prices from a test API.',+ version: '1.0.0',+ permissions: { network: ['api.example.com'] },+ apis: [+ {+ name: 'getPrice',+ description: 'Get the current USD price for a token symbol.',+ parameters: z.object({ symbol: z.string().min(1).describe('Token ticker, e.g. "ETH"') }),+ },+ ],+ ...overrides,+ });+}++// ---------------------------------------------------------------------------+// defineTool: schema -> JSON Schema conversion+// ---------------------------------------------------------------------------++describe('defineTool', () => {+ test('converts each api Zod schema to a JSON Schema on the manifest', () => {+ const tool = makeTool();+ expect(tool.manifest.id).toBe('test-org-price-feed');+ expect(tool.manifest.apis).toHaveLength(1);++ const [api] = tool.manifest.apis;+ expect(api.name).toBe('getPrice');+ expect(api.parameters).toMatchObject({+ type: 'object',+ properties: {+ symbol: { type: 'string', minLength: 1, description: 'Token ticker, e.g. "ETH"' },+ },+ required: ['symbol'],+ });+ // zod-to-json-schema's `$schema` meta key must be stripped.+ expect(api.parameters.$schema).toBeUndefined();+ });++ test('normalizes permissions onto the manifest', () => {+ const tool = makeTool();+ expect(tool.manifest.permissions).toEqual({+ network: ['api.example.com'],+ rateLimit: null,+ wallet: false,+ });+ });++ test('keeps the original Zod schema on _apis for executor validation', () => {+ const tool = makeTool();+ expect(tool._apis[0].parametersZod).toBeInstanceOf(z.ZodObject);+ });++ test('throws on missing required config fields', () => {+ expect(() => defineTool({})).toThrow(/"id"/);+ expect(() => defineTool({ id: 'x' })).toThrow(/"title"/);+ expect(() =>+ defineTool({ id: 'x', title: 'X', description: 'd', version: '1.0.0', apis: [] }),+ ).toThrow(/non-empty array/);+ });++ test('throws on duplicate api names', () => {+ expect(() =>+ makeTool({+ apis: [+ { name: 'getPrice', description: 'a', parameters: z.object({}) },+ { name: 'getPrice', description: 'b', parameters: z.object({}) },+ ],+ }),+ ).toThrow(/duplicate api name/);+ });+});++// ---------------------------------------------------------------------------+// defineExecutor: validation + success/error wrapping+// ---------------------------------------------------------------------------++describe('defineExecutor', () => {+ test('validates params against the Zod schema before invoking the method', async () => {+ const tool = makeTool();+ const method = vi.fn(async ({ symbol }) => ({ symbol, price: 100 }));+ const executor = defineExecutor(tool, { getPrice: method });++ const result = await executor.invoke('getPrice', {});+ expect(result.success).toBe(false);+ expect(result.error.code).toBe('INVALID_PARAMS');+ expect(result.error.message).toMatch(/symbol/);+ expect(method).not.toHaveBeenCalled();+ });++ test('wraps a plain return value into { success: true, content, state }', async () => {+ const tool = makeTool();+ const executor = defineExecutor(tool, {+ async getPrice({ symbol }) {+ return { symbol, price: 42 };+ },+ });++ const result = await executor.invoke('getPrice', { symbol: 'ETH' });+ expect(result).toEqual({+ success: true,+ content: { symbol: 'ETH', price: 42 },+ state: { symbol: 'ETH', price: 42 },+ });+ });++ test('passes through an implementation-returned full result envelope unchanged', async () => {+ const tool = makeTool();+ const envelope = { success: true, content: 'custom content', state: { raw: true } };+ const executor = defineExecutor(tool, { async getPrice() { return envelope; } });++ const result = await executor.invoke('getPrice', { symbol: 'ETH' });+ expect(result).toBe(envelope);+ });++ test('wraps a thrown error into { success: false, error: { message, code } }', async () => {+ const tool = makeTool();+ const executor = defineExecutor(tool, {+ async getPrice() {+ throw Object.assign(new Error('upstream exploded'), { code: 'upstream_error' });+ },+ });++ const result = await executor.invoke('getPrice', { symbol: 'ETH' });+ expect(result.success).toBe(false);+ expect(result.error.message).toBe('upstream exploded');+ expect(result.error.code).toBe('upstream_error');+ expect(result.content).toMatch(/getPrice failed: upstream exploded/);+ });++ test('rejects unknown API names without touching the implementation', async () => {+ const tool = makeTool();+ const executor = defineExecutor(tool, { async getPrice() { return {}; } });++ const result = await executor.invoke('nonexistent', {});+ expect(result.success).toBe(false);+ expect(result.error.code).toBe('API_NOT_FOUND');+ });++ test('rejects a declared api with no implemented method', async () => {+ const tool = makeTool();+ const executor = defineExecutor(tool, {});++ const result = await executor.invoke('getPrice', { symbol: 'ETH' });+ expect(result.success).toBe(false);+ expect(result.error.code).toBe('METHOD_NOT_IMPLEMENTED');+ });++ test('getApiNames / hasApi reflect the tool manifest', () => {+ const tool = makeTool();+ const executor = defineExecutor(tool, { async getPrice() { return {}; } });+ expect(executor.getApiNames()).toEqual(['getPrice']);+ expect(executor.hasApi('getPrice')).toBe(true);+ expect(executor.hasApi('nope')).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// Rate limiting (fake timers)+// ---------------------------------------------------------------------------++describe('rate limiting', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(0);+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ test('createRateLimiter allows up to `calls` within the window, then blocks', () => {+ const limiter = createRateLimiter({ calls: 2, perSeconds: 60 });+ expect(limiter.tryTake('k', 0)).toBe(true);+ expect(limiter.tryTake('k', 0)).toBe(true);+ expect(limiter.tryTake('k', 0)).toBe(false);+ });++ test('createRateLimiter refills tokens over time', () => {+ const limiter = createRateLimiter({ calls: 1, perSeconds: 10 });+ expect(limiter.tryTake('k', 0)).toBe(true);+ expect(limiter.tryTake('k', 1000)).toBe(false); // 1s elapsed, not enough to refill 1 token over 10s+ expect(limiter.tryTake('k', 10_000)).toBe(true); // full window elapsed -> refilled+ });++ test('createRateLimiter returns null when no rate limit is declared', () => {+ expect(createRateLimiter(null)).toBeNull();+ expect(createRateLimiter(undefined)).toBeNull();+ });++ test('defineExecutor enforces the tool-declared rate limit per API name', async () => {+ const tool = makeTool({ permissions: { rateLimit: { calls: 1, perSeconds: 60 } } });+ const method = vi.fn(async ({ symbol }) => ({ symbol, price: 1 }));+ const executor = defineExecutor(tool, { getPrice: method });++ const first = await executor.invoke('getPrice', { symbol: 'ETH' });+ expect(first.success).toBe(true);++ const second = await executor.invoke('getPrice', { symbol: 'ETH' });+ expect(second.success).toBe(false);+ expect(second.error.code).toBe('RATE_LIMITED');+ expect(method).toHaveBeenCalledTimes(1);+ });+});++// ---------------------------------------------------------------------------+// guardedFetch+// ---------------------------------------------------------------------------++describe('guardedFetch', () => {+ const originalFetch = globalThis.fetch;+ beforeEach(() => {+ globalThis.fetch = vi.fn(async () => new Response('ok'));+ });+ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ test('allows a request to an allowlisted host', async () => {+ const fetchGuarded = guardedFetch({ network: ['api.example.com'] });+ await fetchGuarded('https://api.example.com/v1/price');+ expect(globalThis.fetch).toHaveBeenCalledWith('https://api.example.com/v1/price', undefined);+ });++ test('denies a request to a host outside the allowlist', async () => {+ const fetchGuarded = guardedFetch({ network: ['api.example.com'] });+ await expect(fetchGuarded('https://evil.example.net/steal')).rejects.toMatchObject({+ code: 'NETWORK_NOT_ALLOWED',+ hostname: 'evil.example.net',+ });+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ test('denies everything when no network permission is declared (deny-by-default)', async () => {+ const fetchGuarded = guardedFetch({});+ await expect(fetchGuarded('https://api.example.com/v1/price')).rejects.toMatchObject({+ code: 'NETWORK_NOT_ALLOWED',+ });+ });++ test('normalizePermissions dedupes hosts and drops invalid rate limits', () => {+ expect(normalizePermissions({ network: ['a.com', 'a.com', 'b.com'] })).toEqual({+ network: ['a.com', 'b.com'],+ rateLimit: null,+ wallet: false,+ });+ expect(normalizePermissions({ rateLimit: { calls: 0, perSeconds: 60 } }).rateLimit).toBeNull();+ expect(normalizePermissions({ rateLimit: { calls: 5, perSeconds: 60 } }).rateLimit).toEqual({+ calls: 5,+ perSeconds: 60,+ });+ });+});++// ---------------------------------------------------------------------------+// toMcpTools: adapter output shape vs. the repo's current registration format+// ---------------------------------------------------------------------------++describe('toMcpTools', () => {+ // Fixture mirrors packages/naming-mcp/src/tools/sns-resolve.js's `def` shape+ // exactly, so this test doubles as a regression guard on the adapter contract.+ const CURRENT_REGISTRATION_FIXTURE_KEYS = ['name', 'title', 'description', 'inputSchema', 'annotations', 'handler'];++ function makeAnnotatedTool() {+ return defineTool({+ id: 'sns-resolve',+ title: 'Resolve a .sol name to its owner wallet',+ description: 'Resolve a Solana Name Service (.sol) name to the base58 wallet address that owns it.',+ version: '1.0.0',+ permissions: { network: ['three.ws'] },+ apis: [+ {+ name: 'sns_resolve',+ description: 'Resolve a .sol name to its owner wallet.',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ parameters: z.object({+ name: z.string().min(1).describe('A .sol label to resolve.'),+ }),+ },+ ],+ });+ }++ test('produces one MCP tool def per api, matching the current registration keys exactly', () => {+ const tool = makeAnnotatedTool();+ const executor = defineExecutor(tool, { async sns_resolve({ name }) { return { ok: true, name, address: null, resolved: false }; } });++ const defs = toMcpTools(tool, executor);+ expect(defs).toHaveLength(1);+ expect(Object.keys(defs[0]).sort()).toEqual(CURRENT_REGISTRATION_FIXTURE_KEYS.sort());+ });++ test('inputSchema is a raw Zod shape (not JSON Schema) — what McpServer.registerTool expects', () => {+ const tool = makeAnnotatedTool();+ const executor = defineExecutor(tool, { async sns_resolve({ name }) { return { name }; } });+ const [def] = toMcpTools(tool, executor);++ expect(def.inputSchema.name).toBeInstanceOf(z.ZodType);+ // A raw shape has no `type`/`properties` at the top level (unlike JSON Schema).+ expect(def.inputSchema.type).toBeUndefined();+ });++ test('annotations pass through per-api, with a safe default when omitted', () => {+ const tool = makeAnnotatedTool();+ const executor = defineExecutor(tool, { async sns_resolve() { return {}; } });+ const [def] = toMcpTools(tool, executor);+ expect(def.annotations).toEqual({ readOnlyHint: true, idempotentHint: false, openWorldHint: true });++ const unannotated = defineTool({+ id: 'x', title: 'X', description: 'd', version: '1.0.0',+ apis: [{ name: 'op', description: 'd', parameters: z.object({}) }],+ });+ const unannotatedExecutor = defineExecutor(unannotated, { async op() { return {}; } });+ expect(toMcpTools(unannotated, unannotatedExecutor)[0].annotations).toEqual({+ readOnlyHint: false,+ idempotentHint: false,+ openWorldHint: true,+ });+ });++ test('handler returns the content on success (matching hand-written tool handlers)', async () => {+ const tool = makeAnnotatedTool();+ const executor = defineExecutor(tool, {+ async sns_resolve({ name }) {+ return { ok: true, name, address: 'Fw1ETanDZafof7xEULsnq9UY6o71Tpds89tNwPkWLb1v', resolved: true };+ },+ });+ const [def] = toMcpTools(tool, executor);++ const out = await def.handler({ name: 'bonfida' });+ expect(out).toEqual({ ok: true, name: 'bonfida', address: 'Fw1ETanDZafof7xEULsnq9UY6o71Tpds89tNwPkWLb1v', resolved: true });+ });++ test('handler throws on failure (matching hand-written tools whose server wrapper try/catches)', async () => {+ const tool = makeAnnotatedTool();+ const executor = defineExecutor(tool, {+ async sns_resolve() {+ throw Object.assign(new Error('three.ws /api/sns timed out after 20000ms'), { code: 'timeout' });+ },+ });+ const [def] = toMcpTools(tool, executor);++ await expect(def.handler({ name: 'bonfida' })).rejects.toMatchObject({+ message: 'three.ws /api/sns timed out after 20000ms',+ code: 'timeout',+ });+ });++ test('throws a clear error if an api parameter schema is not a z.object', () => {+ const badTool = defineTool({+ id: 'bad', title: 'Bad', description: 'd', version: '1.0.0',+ apis: [{ name: 'op', description: 'd', parameters: z.string() }],+ });+ const executor = defineExecutor(badTool, { async op() { return {}; } });+ expect(() => toMcpTools(badTool, executor)).toThrow(/z\.object/);+ });+});diff --git a/packages/viewer-presets/README.md b/packages/viewer-presets/README.mdindex 5879f94fe..4b6c44449 100644--- a/packages/viewer-presets/README.md+++ b/packages/viewer-presets/README.md@@ -93,6 +93,34 @@ so the plane fades in seamlessly.`luminanceSmoothing`, `mipmapBlur`, `intensity`, `kernelSize`).`bloomConfig(overrides?)` merges your changes over it.+### Materials (`./materials`)++Where the rig above tunes how a scene is *lit*, this module tunes how a model's+*surfaces* read. `MATERIAL_PRESETS` is a curated set of physically-plausible+MeshStandardMaterial looks — `chrome`, `gold`, `copper`, `brushedSteel`,+`gunmetal`, `matte`, `glossy`, `rubber`, `ceramic`, `glass`, `wood`, `stone`,+`neon`, `holographic` — each a frozen parameter set (color, metalness, roughness,+emissive, envMapIntensity, and transparency for glass).++```js+import { applyMaterialPreset, materialVariants } from '@three-ws/viewer-presets/materials';++// Re-skin every standard material on a loaded glTF, non-destructively:+const handle = applyMaterialPreset(THREE, gltf.scene, 'chrome');+// … later, put it back exactly as it was:+handle.restore();++// Fan a base look out into reproducible colorway variants (same seed → same set):+const variants = materialVariants('gold', { seed: 42, count: 6 });+variants.forEach((v) => console.log(v.label, v.config.color));+```++`applyMaterialPreset` only touches materials that expose the standard PBR knobs+(a `MeshBasicMaterial`, sprite, or line material is skipped), captures the prior+values, and hands back a `restore()` — so edits are a reversible layer over the+original asset. `materialVariants` is pure and deterministic per `seed`, aligning+with Forge's `seed` semantics so a variant set is shareable by number.+## API| Export | Signature |@@ -103,6 +131,10 @@ so the plane fades in seamlessly.| `FLOOR_REFLECTION_DEFAULTS` | Frozen floor-reflection defaults (no `color`). || `bloomConfig(overrides?)` | `(Partial<BloomProps>) => BloomProps` || `BLOOM_DEFAULTS` | Frozen bloom defaults. |+| `MATERIAL_PRESETS` / `MATERIAL_PRESET_NAMES` | Frozen map of PBR presets, and their ids in order. |+| `materialPreset(idOrConfig, overrides?)` | `(string \| Partial<MaterialPreset>, overrides?) => MaterialPreset`; throws on unknown id. |+| `applyMaterialPreset(THREE, root, idOrConfig, opts?)` | `(THREE, Object3D, preset) => { restore(), count }` — non-destructive. |+| `materialVariants(base, opts?)` | `(preset, { seed, count, hueSpread, jitter }) => MaterialVariant[]` — seeded, reproducible. |## Requirementsdiff --git a/packages/viewer-presets/package.json b/packages/viewer-presets/package.jsonindex a54ba6e53..c5295be07 100644--- a/packages/viewer-presets/package.json+++ b/packages/viewer-presets/package.json@@ -1,7 +1,7 @@{"name": "@three-ws/viewer-presets",- "version": "0.2.0",- "description": "Tuned visual presets for three.ws avatar viewers — light rigs, floor reflection, and bloom configs derived from Ready Player Me's visage (MIT).",+ "version": "0.3.0",+ "description": "Tuned visual presets for three.ws avatar viewers — light rigs, floor reflection, bloom, and PBR material presets (chrome/gold/glass/…) with seeded variants.","keywords": ["three.ws","three.js",@@ -11,6 +11,9 @@"postprocessing","bloom","floor-reflection",+ "pbr",+ "material",+ "restyle","readyplayerme-alternative","visage-derived"],@@ -34,7 +37,8 @@},"./lights": "./src/lights.js","./floor": "./src/floor.js",- "./bloom": "./src/bloom.js"+ "./bloom": "./src/bloom.js",+ "./materials": "./src/materials.js"},"files": ["src",diff --git a/packages/viewer-presets/src/index.d.ts b/packages/viewer-presets/src/index.d.tsindex b2f766fc8..a898710f8 100644--- a/packages/viewer-presets/src/index.d.ts+++ b/packages/viewer-presets/src/index.d.ts@@ -58,9 +58,29 @@ export interface LightRig {shoeTarget: unknown;}+export interface MaterialPreset {+ label?: string;+ color?: string;+ metalness?: number;+ roughness?: number;+ emissive?: string;+ emissiveIntensity?: number;+ envMapIntensity?: number;+ transparent?: boolean;+ opacity?: number;+}++export interface MaterialVariant {+ label: string;+ seed: number;+ config: MaterialPreset;+}+export declare const LIGHT_CONFIG: LightConfig;export declare const FLOOR_REFLECTION_DEFAULTS: Readonly<Omit<FloorReflectionProps, 'color'>>;export declare const BLOOM_DEFAULTS: BloomProps;+export declare const MATERIAL_PRESETS: Readonly<Record<string, Readonly<MaterialPreset>>>;+export declare const MATERIAL_PRESET_NAMES: readonly string[];export declare function buildLightRig(THREE: unknown,@@ -70,3 +90,18 @@ export declare function floorReflectionConfig(props: Partial<Omit<FloorReflectionProps, 'color'>> & { color: string },): FloorReflectionProps;export declare function bloomConfig(overrides?: Partial<BloomProps>): BloomProps;++export declare function materialPreset(+ presetOrConfig: string | Partial<MaterialPreset>,+ overrides?: Partial<MaterialPreset>,+): MaterialPreset;+export declare function applyMaterialPreset(+ THREE: unknown,+ root: unknown,+ presetOrConfig: string | Partial<MaterialPreset>,+ opts?: { overrides?: Partial<MaterialPreset> },+): { restore: () => void; count: number };+export declare function materialVariants(+ base: string | Partial<MaterialPreset>,+ opts?: { seed?: number; count?: number; hueSpread?: number; jitter?: number },+): MaterialVariant[];diff --git a/packages/viewer-presets/src/index.js b/packages/viewer-presets/src/index.jsindex d56f57ed1..89442409a 100644--- a/packages/viewer-presets/src/index.js+++ b/packages/viewer-presets/src/index.js@@ -1,3 +1,10 @@export { LIGHT_CONFIG, buildLightRig } from './lights.js';export { FLOOR_REFLECTION_DEFAULTS, floorReflectionConfig } from './floor.js';export { BLOOM_DEFAULTS, bloomConfig } from './bloom.js';+export {+ MATERIAL_PRESETS,+ MATERIAL_PRESET_NAMES,+ materialPreset,+ applyMaterialPreset,+ materialVariants,+} from './materials.js';diff --git a/packages/viewer-presets/src/materials.js b/packages/viewer-presets/src/materials.jsnew file mode 100644index 000000000..25ed93ffe--- /dev/null+++ b/packages/viewer-presets/src/materials.js@@ -0,0 +1,305 @@+/*+ * PBR material presets for three.ws viewers — data-first and framework-agnostic.+ *+ * Where `lights.js` / `floor.js` / `bloom.js` tune how a scene is *lit*, this module+ * tunes how a model's *surfaces* read: a curated set of physically-plausible+ * MeshStandardMaterial parameter sets (chrome, gold, glass, wood, …) plus helpers to+ * apply one to a loaded glTF non-destructively and to fan a base look out into a set+ * of seeded, reproducible colorway variants.+ *+ * The preset values are hand-tuned for MeshStandardMaterial / MeshPhysicalMaterial —+ * the material every three.ws viewer and Forge export uses — so a caller can drop any+ * preset onto any GLB and get a coherent result. All exports are pure data + pure+ * functions (THREE is passed in, never imported) so the package stays renderer- and+ * framework-agnostic and unit-testable without a WebGL context.+ *+ * Copyright 2026 three.ws contributors, Apache-2.0.+ */++/**+ * Curated PBR looks. Each value is a plain, frozen parameter set applied onto a+ * MeshStandardMaterial. Fields map 1:1 to material properties; `color`/`emissive`+ * are hex strings (parsed via the caller-supplied THREE.Color). `transparent`/+ * `opacity` are only set when present (so opaque presets never touch blending).+ *+ * @type {Readonly<Record<string, Readonly<MaterialPreset>>>}+ */+export const MATERIAL_PRESETS = Object.freeze({+ chrome: freeze({ label: 'Chrome', color: '#c9ced4', metalness: 1, roughness: 0.05, envMapIntensity: 1.6 }),+ gold: freeze({ label: 'Gold', color: '#ffcf5c', metalness: 1, roughness: 0.18, envMapIntensity: 1.4 }),+ copper: freeze({ label: 'Copper', color: '#c4744a', metalness: 1, roughness: 0.28, envMapIntensity: 1.3 }),+ brushedSteel: freeze({ label: 'Brushed steel', color: '#b7bcc2', metalness: 0.95, roughness: 0.45, envMapIntensity: 1.1 }),+ gunmetal: freeze({ label: 'Gunmetal', color: '#3b4048', metalness: 0.9, roughness: 0.5, envMapIntensity: 1 }),+ matte: freeze({ label: 'Matte plastic', color: '#8b90a0', metalness: 0, roughness: 0.9, envMapIntensity: 0.6 }),+ glossy: freeze({ label: 'Glossy plastic', color: '#4f8bff', metalness: 0, roughness: 0.18, envMapIntensity: 1 }),+ rubber: freeze({ label: 'Rubber', color: '#26282c', metalness: 0, roughness: 0.95, envMapIntensity: 0.4 }),+ ceramic: freeze({ label: 'Glazed ceramic', color: '#f2efe9', metalness: 0, roughness: 0.28, envMapIntensity: 1 }),+ glass: freeze({ label: 'Glass', color: '#dff1ff', metalness: 0, roughness: 0.05, envMapIntensity: 1.5, transparent: true, opacity: 0.35 }),+ wood: freeze({ label: 'Wood', color: '#8a5a34', metalness: 0, roughness: 0.72, envMapIntensity: 0.6 }),+ stone: freeze({ label: 'Stone', color: '#8d8b86', metalness: 0, roughness: 0.85, envMapIntensity: 0.5 }),+ neon: freeze({ label: 'Neon', color: '#0b0b12', metalness: 0, roughness: 0.4, emissive: '#00ffd5', emissiveIntensity: 1.6, envMapIntensity: 0.8 }),+ holographic: freeze({ label: 'Holographic', color: '#b6a8ff', metalness: 1, roughness: 0.12, emissive: '#2a1f5c', emissiveIntensity: 0.35, envMapIntensity: 1.8 }),+});++/** Ordered list of preset ids — for building pickers. @type {readonly string[]} */+export const MATERIAL_PRESET_NAMES = Object.freeze(Object.keys(MATERIAL_PRESETS));++/**+ * Resolve a preset (by id or an inline config) and merge overrides — the material+ * analogue of `bloomConfig()`. Unknown ids throw so a typo never silently no-ops.+ *+ * @param {string | Partial<MaterialPreset>} presetOrConfig+ * @param {Partial<MaterialPreset>} [overrides]+ * @returns {MaterialPreset}+ */+export function materialPreset(presetOrConfig, overrides = {}) {+ let base;+ if (typeof presetOrConfig === 'string') {+ base = MATERIAL_PRESETS[presetOrConfig];+ if (!base) {+ throw new Error(+ `unknown material preset "${presetOrConfig}" — known: ${MATERIAL_PRESET_NAMES.join(', ')}`,+ );+ }+ } else if (presetOrConfig && typeof presetOrConfig === 'object') {+ base = presetOrConfig;+ } else {+ throw new Error('materialPreset: pass a preset id or a config object');+ }+ return { ...base, ...overrides };+}++/**+ * Apply a preset onto every compatible material under `root`, non-destructively.+ *+ * Standard-material properties (color, metalness, roughness, emissive, …) are the+ * only ones touched, and only on materials that actually expose them — a+ * MeshBasicMaterial or a sprite is skipped untouched. The previous values are+ * captured on first apply, so the returned `restore()` puts the model back exactly+ * as it was (the caller keeps the original; edits produce a reversible layer).+ *+ * @param {any} THREE the three.js module (for `THREE.Color`)+ * @param {any} root an Object3D with `.traverse` (a loaded glTF scene/group)+ * @param {string | Partial<MaterialPreset>} presetOrConfig+ * @param {{ overrides?: Partial<MaterialPreset> }} [opts]+ * @returns {{ restore: () => void, count: number }}+ */+export function applyMaterialPreset(THREE, root, presetOrConfig, opts = {}) {+ if (!THREE || typeof THREE.Color !== 'function') {+ throw new Error('applyMaterialPreset: first arg must be the three.js module (needs THREE.Color)');+ }+ if (!root || typeof root.traverse !== 'function') {+ throw new Error('applyMaterialPreset: second arg must be an Object3D with .traverse');+ }+ const cfg = materialPreset(presetOrConfig, opts.overrides);+ const captures = [];+ root.traverse((node) => {+ const mats = materialsOf(node);+ for (const m of mats) {+ if (!isStandardLike(m)) continue;+ captures.push(captureMaterial(m));+ assignPreset(THREE, m, cfg);+ }+ });+ return {+ count: captures.length,+ restore() {+ for (const cap of captures) restoreMaterial(cap);+ },+ };+}++/**+ * Fan a base look out into `count` reproducible colorway variants. Given the same+ * base + seed the output is byte-identical (mulberry32 PRNG), so variants are+ * shareable by seed and align with Forge's `seed` semantics. Hue rotates around the+ * base color; saturation/lightness and roughness/metalness jitter within safe+ * bounds. Emissive presets keep their glow. Pure — returns configs, mutates nothing.+ *+ * @param {string | Partial<MaterialPreset>} base+ * @param {{ seed?: number, count?: number, hueSpread?: number, jitter?: number }} [opts]+ * @returns {{ label: string, seed: number, config: MaterialPreset }[]}+ */+export function materialVariants(base, opts = {}) {+ const cfg = materialPreset(base);+ const count = clampInt(opts.count ?? 6, 1, 64);+ const seed = (opts.seed ?? 0) >>> 0;+ const hueSpread = opts.hueSpread ?? 360;+ const jitter = clamp01(opts.jitter ?? 0.18);+ const rand = mulberry32(seed);+ const baseHsl = hexToHsl(cfg.color || '#808080');+ const out = [];+ for (let i = 0; i < count; i++) {+ // Evenly spread the hue across the requested arc, nudged by seeded noise so+ // a set never looks mechanically banded.+ const hue = wrapHue(baseHsl.h + (hueSpread * i) / count + (rand() - 0.5) * (hueSpread / count));+ const sat = clamp01(baseHsl.s * (1 + (rand() - 0.5) * jitter));+ const light = clamp01(baseHsl.l * (1 + (rand() - 0.5) * jitter * 0.6));+ const rough = clamp01((cfg.roughness ?? 0.5) * (1 + (rand() - 0.5) * jitter));+ const metal = clamp01((cfg.metalness ?? 0) * (1 + (rand() - 0.5) * jitter * 0.5));+ out.push({+ label: `${cfg.label || 'variant'} ${i + 1}`,+ seed: (seed + i) >>> 0,+ config: { ...cfg, color: hslToHex(hue, sat, light), roughness: rough, metalness: metal },+ });+ }+ return out;+}++// ── material helpers ─────────────────────────────────────────────────────────++function materialsOf(node) {+ if (!node || !node.material) return [];+ return Array.isArray(node.material) ? node.material.filter(Boolean) : [node.material];+}++// A material we can meaningfully re-skin: it exposes the standard PBR knobs. Covers+// MeshStandardMaterial and MeshPhysicalMaterial; skips Basic/sprite/line materials.+function isStandardLike(m) {+ return !!m && 'metalness' in m && 'roughness' in m && !!m.color && typeof m.color.getHex === 'function';+}++function captureMaterial(m) {+ return {+ m,+ color: m.color.getHex(),+ metalness: m.metalness,+ roughness: m.roughness,+ emissive: m.emissive ? m.emissive.getHex() : null,+ emissiveIntensity: m.emissiveIntensity,+ envMapIntensity: m.envMapIntensity,+ transparent: m.transparent,+ opacity: m.opacity,+ };+}++function restoreMaterial(cap) {+ const { m } = cap;+ m.color.setHex(cap.color);+ m.metalness = cap.metalness;+ m.roughness = cap.roughness;+ if (m.emissive && cap.emissive != null) m.emissive.setHex(cap.emissive);+ m.emissiveIntensity = cap.emissiveIntensity;+ m.envMapIntensity = cap.envMapIntensity;+ m.transparent = cap.transparent;+ m.opacity = cap.opacity;+ m.needsUpdate = true;+}++function assignPreset(THREE, m, cfg) {+ if (cfg.color) m.color.set(cfg.color);+ if (cfg.metalness != null) m.metalness = cfg.metalness;+ if (cfg.roughness != null) m.roughness = cfg.roughness;+ if (m.emissive) {+ m.emissive.set(cfg.emissive || '#000000');+ m.emissiveIntensity = cfg.emissiveIntensity != null ? cfg.emissiveIntensity : cfg.emissive ? 1 : 0;+ }+ if (cfg.envMapIntensity != null && 'envMapIntensity' in m) m.envMapIntensity = cfg.envMapIntensity;+ if (cfg.transparent != null) {+ m.transparent = !!cfg.transparent;+ if (cfg.opacity != null) m.opacity = cfg.opacity;+ } else {+ // Opaque preset: undo any prior transparency so switching glass→chrome is clean.+ m.transparent = false;+ m.opacity = 1;+ }+ m.needsUpdate = true;+}++// ── color + rng helpers (small, inline — no dependency for a few functions) ────++function mulberry32(seed) {+ let a = seed >>> 0;+ return function () {+ a |= 0;+ a = (a + 0x6d2b79f5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++function hexToHsl(hex) {+ const { r, g, b } = hexToRgb(hex);+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;+ let h = 0;+ let s = 0;+ if (max !== min) {+ const d = max - min;+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);+ if (max === r) h = (g - b) / d + (g < b ? 6 : 0);+ else if (max === g) h = (b - r) / d + 2;+ else h = (r - g) / d + 4;+ h *= 60;+ }+ return { h, s, l };+}++function hslToHex(h, s, l) {+ h = wrapHue(h) / 360;+ let r;+ let g;+ let b;+ if (s === 0) {+ r = g = b = l;+ } else {+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;+ const p = 2 * l - q;+ r = hue2rgb(p, q, h + 1 / 3);+ g = hue2rgb(p, q, h);+ b = hue2rgb(p, q, h - 1 / 3);+ }+ return rgbToHex(r, g, b);+}++function hue2rgb(p, q, t) {+ if (t < 0) t += 1;+ if (t > 1) t -= 1;+ if (t < 1 / 6) return p + (q - p) * 6 * t;+ if (t < 1 / 2) return q;+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;+ return p;+}++function hexToRgb(hex) {+ const h = String(hex).replace('#', '');+ const n = h.length === 3 ? h.split('').map((c) => c + c).join('') : h;+ const int = parseInt(n, 16);+ return { r: ((int >> 16) & 255) / 255, g: ((int >> 8) & 255) / 255, b: (int & 255) / 255 };+}++function rgbToHex(r, g, b) {+ const to = (v) => {+ const s = Math.round(clamp01(v) * 255).toString(16);+ return s.length === 1 ? '0' + s : s;+ };+ return `#${to(r)}${to(g)}${to(b)}`;+}++function wrapHue(h) {+ return ((h % 360) + 360) % 360;+}+function clamp01(n) {+ return Math.min(1, Math.max(0, n));+}+function clampInt(n, lo, hi) {+ return Math.min(hi, Math.max(lo, Math.round(n)));+}+function freeze(o) {+ return Object.freeze(o);+}++/**+ * @typedef {Object} MaterialPreset+ * @property {string} [label]+ * @property {string} [color] base color hex+ * @property {number} [metalness] 0..1+ * @property {number} [roughness] 0..1+ * @property {string} [emissive] emissive color hex+ * @property {number} [emissiveIntensity]+ * @property {number} [envMapIntensity]+ * @property {boolean} [transparent]+ * @property {number} [opacity] 0..1, only with transparent+ */diff --git a/packages/viewer-presets/test/presets.test.js b/packages/viewer-presets/test/presets.test.jsindex 07306d5e2..4388b348d 100644--- a/packages/viewer-presets/test/presets.test.js+++ b/packages/viewer-presets/test/presets.test.js@@ -7,8 +7,50 @@ import {buildLightRig,floorReflectionConfig,bloomConfig,+ MATERIAL_PRESETS,+ MATERIAL_PRESET_NAMES,+ materialPreset,+ applyMaterialPreset,+ materialVariants,} from '../src/index.js';+// ── minimal THREE.Color / material / object shims (no WebGL) ──────────────────+class FakeColor {+ constructor(hex = 0) {+ this._hex = typeof hex === 'string' ? parseInt(hex.replace('#', ''), 16) : hex >>> 0;+ }+ set(hex) {+ this._hex = typeof hex === 'string' ? parseInt(hex.replace('#', ''), 16) : hex >>> 0;+ return this;+ }+ setHex(h) {+ this._hex = h >>> 0;+ return this;+ }+ getHex() {+ return this._hex;+ }+}+const FakeTHREE = { Color: FakeColor };+function fakeStandardMaterial() {+ return {+ color: new FakeColor(0x808080),+ emissive: new FakeColor(0x000000),+ metalness: 0.3,+ roughness: 0.6,+ emissiveIntensity: 0,+ envMapIntensity: 1,+ transparent: false,+ opacity: 1,+ needsUpdate: false,+ };+}+// A root with .traverse yielding meshes carrying materials.+function fakeRoot(materials) {+ const nodes = materials.map((m) => ({ material: m }));+ return { traverse: (fn) => nodes.forEach(fn) };+}+test('LIGHT_CONFIG preserves visage angles', () => {assert.equal(LIGHT_CONFIG.fillLightAngle, Math.PI / 3);assert.equal(LIGHT_CONFIG.backLightAngle, Math.PI / 8);@@ -138,3 +180,83 @@ test('buildLightRig accepts overrides without losing defaults', () => {const fill = group.children.find((c) => c.isSpotLight && c.color === '#ff00ff');assert.ok(fill, 'override color should be applied to fill light');});++// ── material presets ─────────────────────────────────────────────────────────++test('MATERIAL_PRESETS are frozen and expose core PBR looks', () => {+ for (const name of ['chrome', 'gold', 'glass', 'wood', 'neon']) {+ assert.ok(MATERIAL_PRESETS[name], `missing preset ${name}`);+ }+ assert.equal(MATERIAL_PRESETS.chrome.metalness, 1);+ assert.equal(MATERIAL_PRESETS.matte.metalness, 0);+ assert.equal(MATERIAL_PRESETS.glass.transparent, true);+ assert.throws(() => {+ MATERIAL_PRESETS.chrome.metalness = 0;+ });+ assert.ok(MATERIAL_PRESET_NAMES.includes('chrome'));+ assert.equal(MATERIAL_PRESET_NAMES.length, Object.keys(MATERIAL_PRESETS).length);+});++test('materialPreset resolves ids, merges overrides, rejects unknowns', () => {+ const gold = materialPreset('gold', { roughness: 0.5 });+ assert.equal(gold.metalness, 1);+ assert.equal(gold.roughness, 0.5); // override wins+ assert.throws(() => materialPreset('unobtanium'), /unknown material preset/);+ assert.throws(() => materialPreset(42), /preset id or a config/);+});++test('applyMaterialPreset mutates standard materials and restore() reverts exactly', () => {+ const mat = fakeStandardMaterial();+ const before = { color: mat.color.getHex(), metalness: mat.metalness, roughness: mat.roughness };+ const handle = applyMaterialPreset(FakeTHREE, fakeRoot([mat]), 'chrome');+ assert.equal(handle.count, 1);+ assert.equal(mat.metalness, 1);+ assert.equal(mat.roughness, MATERIAL_PRESETS.chrome.roughness);+ assert.equal(mat.needsUpdate, true);+ handle.restore();+ assert.equal(mat.color.getHex(), before.color);+ assert.equal(mat.metalness, before.metalness);+ assert.equal(mat.roughness, before.roughness);+});++test('applyMaterialPreset skips non-standard materials untouched', () => {+ const basic = { color: new FakeColor(0x123456), needsUpdate: false }; // no metalness/roughness+ const handle = applyMaterialPreset(FakeTHREE, fakeRoot([basic]), 'gold');+ assert.equal(handle.count, 0);+ assert.equal(basic.color.getHex(), 0x123456);+ assert.equal(basic.needsUpdate, false);+});++test('applyMaterialPreset glass sets transparency; switching to opaque clears it', () => {+ const mat = fakeStandardMaterial();+ applyMaterialPreset(FakeTHREE, fakeRoot([mat]), 'glass');+ assert.equal(mat.transparent, true);+ assert.ok(mat.opacity < 1);+ applyMaterialPreset(FakeTHREE, fakeRoot([mat]), 'chrome');+ assert.equal(mat.transparent, false);+ assert.equal(mat.opacity, 1);+});++test('applyMaterialPreset validates its args', () => {+ assert.throws(() => applyMaterialPreset({}, fakeRoot([]), 'gold'), /three\.js module/);+ assert.throws(() => applyMaterialPreset(FakeTHREE, {}, 'gold'), /Object3D with \.traverse/);+});++test('materialVariants is deterministic per seed and honors count', () => {+ const a = materialVariants('gold', { seed: 7, count: 5 });+ const b = materialVariants('gold', { seed: 7, count: 5 });+ const c = materialVariants('gold', { seed: 8, count: 5 });+ assert.equal(a.length, 5);+ assert.deepEqual(a, b, 'same seed → identical variants');+ assert.notDeepEqual(a[0].config.color, c[0].config.color, 'different seed → different colorway');+ for (const v of a) {+ assert.match(v.config.color, /^#[0-9a-f]{6}$/);+ assert.ok(v.config.roughness >= 0 && v.config.roughness <= 1);+ assert.ok(v.config.metalness >= 0 && v.config.metalness <= 1);+ }+});++test('materialVariants clamps count into [1,64]', () => {+ assert.equal(materialVariants('wood', { count: 0 }).length, 1);+ assert.equal(materialVariants('wood', { count: 999 }).length, 64);+});diff --git a/pages/bnb.html b/pages/bnb.htmlnew file mode 100644index 000000000..f99fdf616--- /dev/null+++ b/pages/bnb.html@@ -0,0 +1,605 @@+<!doctype html>+<html lang="en">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>BNB Chain — three genuinely-unique demos · three.ws</title>+ <meta+ name="description"+ content="Gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world — three product tracks built on BNB Chain's fastest-in-class 0.45s blocks. Live proof, honest coming-soon states for what's not shipped yet."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/bnb" />+ <meta property="og:title" content="BNB Chain — three genuinely-unique demos · three.ws" />+ <meta+ property="og:description"+ content="Three product tracks that exploit capabilities Ethereum L1, Base, and Solana can't match — verified live on BNB Chain. Live 0.45s block-time proof embedded on the page."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=BNB+Chain+%E2%80%94+three+genuinely-unique+demos&d=Gasless+agent+onboarding%2C+an+on-chain-gated+3D+vault%2C+and+a+real-time+on-chain+world%3A+three+product+tracks+built+on+BNB+Chain%27s+fastest-in-class+0.45s+blocks.+Live+proof%2C+honest+%22coming+soon%22+for+what%27s+not+shipped+yet.&p=%2Fbnb"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="BNB Chain — three genuinely-unique demos · three.ws" />+ <meta+ name="twitter:description"+ content="Three product tracks that exploit capabilities Ethereum L1, Base, and Solana can't match — verified live on BNB Chain. Live 0.45s block-time proof embedded on the page."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=BNB+Chain+%E2%80%94+three+genuinely-unique+demos&d=Gasless+agent+onboarding%2C+an+on-chain-gated+3D+vault%2C+and+a+real-time+on-chain+world%3A+three+product+tracks+built+on+BNB+Chain%27s+fastest-in-class+0.45s+blocks.+Live+proof%2C+honest+%22coming+soon%22+for+what%27s+not+shipped+yet.&p=%2Fbnb"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/bnb" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="BNB Chain × three.ws — three genuinely-unique demos" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "BNB Chain — three genuinely-unique demos",+ "description": "Gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world — three product tracks built on BNB Chain's 0.45s blocks, each traced to a verified capability. Live block-time proof embedded on the page.",+ "url": "https://three.ws/bnb",+ "isPartOf": { "@type": "WebSite", "name": "three.ws", "url": "https://three.ws" }+ }+ ]+ }+ </script>++ <style>+ :root {+ color-scheme: dark;+ }+ :root[data-theme='light'] {+ color-scheme: light;+ }+ .bnb-wrap {+ max-width: 1180px;+ margin: 0 auto;+ padding: 0 24px;+ }+ @media (max-width: 600px) {+ .bnb-wrap {+ padding: 0 16px;+ }+ }++ /* ── Hero ─────────────────────────────────────────────────────── */+ .bnb-hero {+ padding: 76px 0 40px;+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ }+ .bnb-eyebrow {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-size: 12px;+ font-weight: 600;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--gold, #f0b90b);+ margin: 0 0 16px;+ }+ .bnb-eyebrow .dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: #f0b90b;+ }+ .bnb-hero h1 {+ font-family: var(--font-display, 'Space Grotesk', system-ui, sans-serif);+ font-size: clamp(34px, 5.4vw, 58px);+ font-weight: 700;+ letter-spacing: -0.03em;+ line-height: 1.06;+ margin: 0 0 20px;+ max-width: 18ch;+ }+ .bnb-hero p.lede {+ font-size: 17px;+ line-height: 1.65;+ color: var(--ink-dim, #888);+ margin: 0 0 28px;+ max-width: 62ch;+ }+ .bnb-hero-meta {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 10px 22px;+ font-size: 13px;+ color: var(--ink-dim, #888);+ }+ .bnb-hero-meta strong {+ color: var(--ink, #e8e8e8);+ font-weight: 600;+ }+ #bnb-progress {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ }+ #bnb-progress::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--ink-dim, #888);+ }+ #bnb-progress[data-any-live='true']::before {+ background: var(--success, #4ade80);+ }++ /* ── Live block-time proof strip ─────────────────────────────── */+ .bnb-proof {+ padding: 40px 0;+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ }+ .bnb-proof-card {+ display: grid;+ grid-template-columns: auto 1fr auto;+ align-items: center;+ gap: 28px;+ padding: 26px 28px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-card, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ }+ @media (max-width: 720px) {+ .bnb-proof-card {+ grid-template-columns: 1fr;+ text-align: left;+ }+ }+ .bnb-proof-num {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: clamp(40px, 6vw, 64px);+ font-weight: 700;+ line-height: 1;+ color: var(--ink, #e8e8e8);+ white-space: nowrap;+ }+ .bnb-proof-num .unit {+ font-size: 0.4em;+ color: var(--ink-dim, #888);+ font-weight: 500;+ margin-left: 4px;+ }+ .bnb-proof-mid {+ display: flex;+ flex-direction: column;+ gap: 6px;+ min-width: 0;+ }+ .bnb-proof-title {+ font-size: 14px;+ font-weight: 600;+ color: var(--ink, #e8e8e8);+ margin: 0;+ }+ .bnb-proof-sub {+ font-size: 12.5px;+ color: var(--ink-dim, #888);+ margin: 0;+ }+ .bnb-proof-sub .delta-fast {+ color: var(--success, #4ade80);+ }+ .bnb-proof-sub .delta-slow {+ color: var(--warn, #fbbf24);+ }+ .bnb-proof-stats {+ display: flex;+ flex-direction: column;+ gap: 4px;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ color: var(--ink-dim, #888);+ text-align: right;+ }+ @media (max-width: 720px) {+ .bnb-proof-stats {+ text-align: left;+ }+ }+ .bnb-proof-stats b {+ color: var(--ink, #e8e8e8);+ font-weight: 600;+ }+ .bnb-proof-loading,+ .bnb-proof-error {+ display: flex;+ align-items: center;+ gap: 10px;+ color: var(--ink-dim, #888);+ font-size: 14px;+ }+ .bnb-spinner {+ width: 14px;+ height: 14px;+ border-radius: 50%;+ border: 2px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-top-color: var(--ink, #e8e8e8);+ animation: bnb-spin 0.8s linear infinite;+ flex-shrink: 0;+ }+ @media (prefers-reduced-motion: reduce) {+ .bnb-spinner {+ animation: none;+ }+ }+ @keyframes bnb-spin {+ to {+ transform: rotate(360deg);+ }+ }+ .bnb-retry {+ padding: 6px 14px;+ border-radius: var(--radius-control, 10px);+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink, #e8e8e8);+ font-family: inherit;+ font-size: 12.5px;+ cursor: pointer;+ transition: background 0.14s;+ }+ .bnb-retry:hover {+ background: rgba(255, 255, 255, 0.1);+ }+ .bnb-retry:active {+ transform: translateY(1px);+ }+ .bnb-retry:focus-visible {+ outline: 2px solid rgba(255, 255, 255, 0.4);+ outline-offset: 2px;+ }++ /* ── Feature card grid ───────────────────────────────────────── */+ .bnb-tracks {+ padding: 52px 0 24px;+ }+ .bnb-section-heading {+ font-family: var(--font-display, 'Space Grotesk', system-ui, sans-serif);+ font-size: 22px;+ font-weight: 700;+ letter-spacing: -0.01em;+ margin: 0 0 8px;+ }+ .bnb-section-sub {+ font-size: 14px;+ color: var(--ink-dim, #888);+ margin: 0 0 32px;+ max-width: 68ch;+ line-height: 1.6;+ }+ .bnb-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 20px;+ }+ @media (max-width: 980px) {+ .bnb-grid {+ grid-template-columns: 1fr;+ }+ }+ .bnb-card {+ display: flex;+ flex-direction: column;+ gap: 14px;+ padding: 26px 24px 24px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-card, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ transition:+ border-color 0.18s,+ transform 0.18s,+ box-shadow 0.18s;+ }+ .bnb-card:hover {+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14));+ transform: translateY(-2px);+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.35);+ }+ .bnb-card-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 10px;+ }+ .bnb-card-icon {+ width: 38px;+ height: 38px;+ border-radius: 10px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: rgba(240, 185, 11, 0.12);+ color: #f0b90b;+ flex-shrink: 0;+ }+ .bnb-card-icon svg {+ width: 20px;+ height: 20px;+ }+ .bnb-status {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 11px;+ font-weight: 500;+ padding: 3px 9px;+ border-radius: 999px;+ white-space: nowrap;+ flex-shrink: 0;+ }+ .bnb-status::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ flex-shrink: 0;+ }+ .bnb-status[data-state='live'] {+ background: rgba(74, 222, 128, 0.1);+ color: var(--success, #4ade80);+ border: 1px solid rgba(74, 222, 128, 0.2);+ }+ .bnb-status[data-state='live']::before {+ background: var(--success, #4ade80);+ }+ .bnb-status[data-state='coming-soon'] {+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink-dim, #888);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ }+ .bnb-status[data-state='coming-soon']::before {+ background: var(--ink-dim, #888);+ }+ .bnb-status[data-state='checking'] {+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink-dim, #888);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ animation: bnb-pulse 1.8s ease-in-out infinite;+ }+ @media (prefers-reduced-motion: reduce) {+ .bnb-status[data-state='checking'] {+ animation: none;+ }+ }+ @keyframes bnb-pulse {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.45;+ }+ }+ .bnb-card h2 {+ font-family: var(--font-display, 'Space Grotesk', system-ui, sans-serif);+ font-size: 18px;+ font-weight: 650;+ letter-spacing: -0.01em;+ margin: 0;+ line-height: 1.3;+ }+ .bnb-card .kicker {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11px;+ color: var(--ink-dim, #888);+ text-transform: uppercase;+ letter-spacing: 0.05em;+ margin: -8px 0 0;+ }+ .bnb-card p.desc {+ font-size: 13.5px;+ line-height: 1.65;+ color: var(--ink-dim, #888);+ margin: 0;+ }+ .bnb-card .caveat {+ font-size: 12px;+ line-height: 1.6;+ color: var(--ink-faint, rgba(255, 255, 255, 0.4));+ margin: 0;+ padding-top: 10px;+ border-top: 1px dashed var(--stroke, rgba(255, 255, 255, 0.08));+ }+ .bnb-card-footer {+ margin-top: auto;+ padding-top: 12px;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 10px;+ }+ .bnb-cta {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 9px 16px;+ border-radius: var(--radius-control, 10px);+ background: var(--surface-3, rgba(255, 255, 255, 0.08));+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ color: var(--ink, #e8e8e8);+ font-size: 13px;+ font-weight: 500;+ transition:+ background 0.14s,+ border-color 0.14s;+ }+ .bnb-cta:hover {+ background: rgba(255, 255, 255, 0.12);+ border-color: rgba(255, 255, 255, 0.22);+ }+ .bnb-cta:active {+ background: rgba(255, 255, 255, 0.16);+ transform: translateY(1px);+ }+ .bnb-cta:focus-visible {+ outline: 2px solid rgba(255, 255, 255, 0.4);+ outline-offset: 2px;+ }+ .bnb-cta[aria-disabled='true'] {+ background: transparent;+ border-color: var(--stroke, rgba(255, 255, 255, 0.08));+ color: var(--ink-dim, #888);+ cursor: default;+ pointer-events: none;+ }+ .bnb-cta-secondary {+ font-size: 12.5px;+ color: var(--ink-dim, #888);+ text-decoration: underline;+ text-underline-offset: 2px;+ }+ .bnb-cta-secondary:hover {+ color: var(--ink, #e8e8e8);+ }+ .bnb-cta-secondary:focus-visible {+ outline: 2px solid rgba(255, 255, 255, 0.4);+ outline-offset: 2px;+ border-radius: 4px;+ }++ /* ── Honesty footer ───────────────────────────────────────────── */+ .bnb-honesty {+ padding: 40px 0 80px;+ }+ .bnb-honesty-card {+ padding: 22px 24px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-card, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ }+ .bnb-honesty-card h3 {+ font-size: 14px;+ font-weight: 600;+ margin: 0 0 10px;+ }+ .bnb-honesty-card ul {+ margin: 0;+ padding-left: 18px;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .bnb-honesty-card li {+ font-size: 12.5px;+ line-height: 1.6;+ color: var(--ink-dim, #888);+ }+ .bnb-honesty-card code {+ font-family: var(--font-mono, ui-monospace, monospace);+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ padding: 1px 5px;+ border-radius: 4px;+ font-size: 11.5px;+ }+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js" defer></script>++ <main id="main-content">+ <div class="bnb-wrap">+ <!-- Hero -->+ <section class="bnb-hero" aria-labelledby="bnb-heading">+ <p class="bnb-eyebrow"><span class="dot" aria-hidden="true"></span>BNB Chain × three.ws</p>+ <h1 id="bnb-heading">Three things only BNB Chain lets us build.</h1>+ <p class="lede">+ Not "20,000 TPS" marketing — three product tracks that exploit capabilities we+ independently verified live on BNB Chain on 2026-07-07, that Ethereum L1, Base, and+ (mostly) Solana genuinely can't match. Each card below traces its claim to what we+ measured, links the real demo when it's shipped, and says "coming soon" — not a dead+ link — when it isn't.+ </p>+ <div class="bnb-hero-meta">+ <span id="bnb-progress" data-any-live="false" role="status" aria-live="polite"+ >Checking which tracks are live…</span+ >+ <span>·</span>+ <span+ >Verified <strong>2026-07-07</strong>, 3-vote adversarial review</span+ >+ </div>+ </section>++ <!-- Live block-time proof -->+ <section class="bnb-proof" aria-label="Live BNB Chain block-time proof">+ <div id="bnb-proof-card"></div>+ </section>++ <!-- Feature cards -->+ <section class="bnb-tracks" aria-label="BNB Chain product tracks">+ <h2 class="bnb-section-heading">Three tracks, each honestly gated</h2>+ <p class="bnb-section-sub">+ A card shows a live demo the moment its API/route actually resolves — checked against+ the running deployment, not a hardcoded flag. Nothing here claims 250ms finality or+ 20,000 TPS; those are BNB's own roadmap promises, not shipped facts.+ </p>+ <div class="bnb-grid" id="bnb-grid"></div>+ </section>++ <!-- Honesty / methodology -->+ <section class="bnb-honesty" aria-label="How these claims are verified">+ <div class="bnb-honesty-card">+ <h3>How we keep this page honest</h3>+ <ul>+ <li>+ The block-time number above is measured live from a public BSC RPC on every page+ load (<code>probeBlockTime</code>, sampling 200 real blocks) — never a hardcoded+ "0.45s".+ </li>+ <li>+ Each card's Live/Coming soon badge is a real HTTP check against its API or route+ on this deployment — a 404 reads as "coming soon," a working endpoint (even one+ that only accepts <code>POST</code>) reads as "live."+ </li>+ <li>+ We never claim BNB's roadmap targets — 20,000 TPS, 250ms finality (BEP-670), or a+ chain-level "AI agent framework" — as shipped. Only what we measured ourselves.+ </li>+ </ul>+ </div>+ </section>+ </div>+ </main>++ <div id="footer-container"></div>+ <script type="module" src="/src/bnb.js"></script>+ <script src="/footer.js" defer></script>+ </body>+</html>diff --git a/pages/categories.html b/pages/categories.htmlnew file mode 100644index 000000000..fca489694--- /dev/null+++ b/pages/categories.html@@ -0,0 +1,123 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Crypto Categories · three.ws</title>+ <meta+ name="description"+ content="Every crypto sector ranked by market cap — Layer 1s, DeFi, memes, AI, RWAs and more. See which categories are leading and lagging with live 24h moves and volume."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/categories" />+ <meta property="og:title" content="Crypto Categories · three.ws" />+ <meta+ property="og:description"+ content="Every crypto sector ranked by market cap — Layer 1s, DeFi, memes, AI, RWAs and more, with live 24h moves and volume."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Crypto+Categories&d=Every+crypto+sector+ranked+by+market+cap%3A+Layer+1s%2C+DeFi%2C+memes%2C+AI%2C+RWAs+and+more%2C+with+live+24h+moves+and+volume.+See+which+categories+lead+the+market&p=%2Fcategories"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Crypto Categories · three.ws" />+ <meta+ name="twitter:description"+ content="Every crypto sector ranked by market cap, with live 24h moves and volume."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Crypto+Categories&d=Every+crypto+sector+ranked+by+market+cap%3A+Layer+1s%2C+DeFi%2C+memes%2C+AI%2C+RWAs+and+more%2C+with+live+24h+moves+and+volume.+See+which+categories+lead+the+market&p=%2Fcategories"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/categories.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/categories" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Crypto Categories — three.ws" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Crypto Categories",+ "description": "Every crypto sector ranked by market cap: Layer 1s, DeFi, memes, AI, RWAs and more, with live 24h market-cap moves and trading volume. See which categories lead the market at a glance, then dig into the coins that make them up.",+ "url": "https://three.ws/categories",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=Crypto+Categories&d=Every+crypto+sector+ranked+by+market+cap%3A+Layer+1s%2C+DeFi%2C+memes%2C+AI%2C+RWAs+and+more%2C+with+live+24h+moves+and+volume.+See+which+categories+lead+the+market&p=%2Fcategories"+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/coins">Markets</a><span class="sep">/</span+ ><span class="here">Categories</span>+ </nav>+ <h1 class="cv-h1">Crypto Categories</h1>+ <p class="cv-sub">+ Every sector of the market, ranked by market cap — Layer 1s, DeFi, memes, AI, RWAs+ and more. See which narratives are leading and lagging, then click through to the+ coins that make them up.+ </p>++ <!-- Summary stat cards. Hydrated by src/categories.js. -->+ <section id="cat-stats" class="cv-section" aria-label="Category statistics"></section>++ <div class="cv-toolbar">+ <h2 class="cv-h2" style="margin: 0">All Categories</h2>+ <div class="cv-pills">+ <a class="cv-pill" href="/coins">All Coins</a>+ <a class="cv-pill" href="/heatmap">Heatmap</a>+ </div>+ </div>++ <!-- Category table. Hydrated by src/categories.js. -->+ <section id="cat-table" aria-label="Crypto categories by market cap"></section>+ <p class="cv-updated" id="cat-updated"></p>+ </main>++ <script type="module" src="/src/categories.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/chains.html b/pages/chains.htmlnew file mode 100644index 000000000..c711ccfc8--- /dev/null+++ b/pages/chains.html@@ -0,0 +1,126 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Blockchain TVL by Chain · three.ws</title>+ <meta+ name="description"+ content="Live total value locked by blockchain — every chain ranked by TVL with its dominance share of the cross-chain total. See which networks hold the most DeFi liquidity at a glance."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/chains" />+ <meta property="og:title" content="Blockchain TVL by Chain · three.ws" />+ <meta+ property="og:description"+ content="Live total value locked by blockchain — every chain ranked by TVL with its dominance share of the cross-chain total. See which networks hold the most DeFi liquidity."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Blockchain+TVL+by+Chain&d=Live+total+value+locked+by+blockchain%3A+every+chain+ranked+by+TVL+with+its+dominance+share+of+the+cross-chain+total.+See+which+networks+hold+the+most+DeFi+liquidity&p=%2Fchains"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Blockchain TVL by Chain · three.ws" />+ <meta+ name="twitter:description"+ content="Live total value locked by blockchain — every chain ranked by TVL with its dominance share of the cross-chain total."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Blockchain+TVL+by+Chain&d=Live+total+value+locked+by+blockchain%3A+every+chain+ranked+by+TVL+with+its+dominance+share+of+the+cross-chain+total.+See+which+networks+hold+the+most+DeFi+liquidity&p=%2Fchains"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/chains.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/chains" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Blockchain TVL by Chain — three.ws" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Blockchain TVL by Chain",+ "description": "Live total value locked by blockchain: every chain ranked by TVL with its dominance share of the cross-chain total. See which networks hold the most DeFi liquidity at a glance, sourced from DeFiLlama.",+ "url": "https://three.ws/chains",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=Blockchain+TVL+by+Chain&d=Live+total+value+locked+by+blockchain%3A+every+chain+ranked+by+TVL+with+its+dominance+share+of+the+cross-chain+total.+See+which+networks+hold+the+most+DeFi+liquidity&p=%2Fchains"+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/coins">Markets</a><span class="sep">/</span+ ><span class="here">Chains</span>+ </nav>+ <h1 class="cv-h1">Blockchain TVL by Chain</h1>+ <p class="cv-sub">+ Total value locked across every blockchain — each network ranked by TVL with its+ dominance share of the cross-chain total. See where DeFi liquidity concentrates.+ </p>++ <!-- Header stat cards. Hydrated by src/chains.js. -->+ <section+ id="chains-stats"+ class="cv-section"+ aria-label="Cross-chain statistics"+ ></section>++ <div class="cv-toolbar">+ <h2 class="cv-h2" style="margin: 0">Chains by TVL</h2>+ <a class="cv-pill" href="/defi">DeFi protocols →</a>+ </div>++ <!-- Chain table. Hydrated by src/chains.js. -->+ <section+ id="chains-table"+ aria-label="Blockchains ranked by total value locked"+ ></section>+ <p class="cv-updated" id="chains-updated"></p>+ </main>++ <script type="module" src="/src/chains.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/coins.html b/pages/coins.htmlindex f6e80a07c..24149c75b 100644--- a/pages/coins.html+++ b/pages/coins.html@@ -55,6 +55,22 @@digital assets.</p>+ <!-- Market tools hub: every sibling surface, discoverable from the index. -->+ <nav class="cv-tools" aria-label="Market tools">+ <a class="cv-pill" href="/heatmap">Heatmap</a>+ <a class="cv-pill" href="/screener">Screener</a>+ <a class="cv-pill" href="/categories">Categories</a>+ <a class="cv-pill" href="/exchanges">Exchanges</a>+ <a class="cv-pill" href="/derivatives">Derivatives</a>+ <a class="cv-pill" href="/converter">Converter</a>+ <a class="cv-pill" href="/compare">Compare</a>+ <a class="cv-pill" href="/fear-greed">Fear & Greed</a>+ <a class="cv-pill" href="/gas">Gas</a>+ <a class="cv-pill" href="/defi">DeFi TVL</a>+ <a class="cv-pill" href="/chains">Chains</a>+ <a class="cv-pill" href="/stablecoins">Stablecoins</a>+ </nav>+<!-- Global stats bar. Hydrated by src/coins-index.js. --><section id="cv-stats" class="cv-section" aria-label="Market statistics"></section>diff --git a/pages/converter.html b/pages/converter.htmlnew file mode 100644index 000000000..bc80b2e7d--- /dev/null+++ b/pages/converter.html@@ -0,0 +1,135 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Crypto Converter · three.ws</title>+ <meta+ name="description"+ content="Convert between any cryptocurrency and major world currencies at live market rates. Crypto to crypto, crypto to fiat, fiat to crypto — instant, accurate, always up to date."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/converter" />+ <meta property="og:title" content="Crypto Converter · three.ws" />+ <meta+ property="og:description"+ content="Convert between any cryptocurrency and major world currencies at live market rates — crypto to crypto, crypto to fiat, and back."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Crypto+Converter&d=Convert+between+any+cryptocurrency+and+major+world+currencies+at+live+market+rates%3A+crypto%E2%86%94crypto%2C+crypto%E2%86%94fiat%2C+fiat%E2%86%94crypto.+Instant%2C+accurate%2C+always+up+to+date&p=%2Fconverter"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Crypto Converter · three.ws" />+ <meta+ name="twitter:description"+ content="Convert between any cryptocurrency and major world currencies at live market rates."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Crypto+Converter&d=Convert+between+any+cryptocurrency+and+major+world+currencies+at+live+market+rates%3A+crypto%E2%86%94crypto%2C+crypto%E2%86%94fiat%2C+fiat%E2%86%94crypto.+Instant%2C+accurate%2C+always+up+to+date&p=%2Fconverter"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/converter.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/converter" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Crypto Converter — three.ws" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Crypto Converter",+ "description": "Convert between any cryptocurrency and major world currencies at live market rates: crypto to crypto, crypto to fiat, and fiat to crypto. Prices come straight from the live market and update continuously.",+ "url": "https://three.ws/converter",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=Crypto+Converter&d=Convert+between+any+cryptocurrency+and+major+world+currencies+at+live+market+rates%3A+crypto%E2%86%94crypto%2C+crypto%E2%86%94fiat%2C+fiat%E2%86%94crypto.+Instant%2C+accurate%2C+always+up+to+date&p=%2Fconverter"+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/coins">Markets</a><span class="sep">/</span+ ><span class="here">Converter</span>+ </nav>+ <h1 class="cv-h1">Crypto Converter</h1>+ <p class="cv-sub">+ Convert between any cryptocurrency and major world currencies at live market rates.+ Crypto to crypto, crypto to fiat, or fiat to crypto — every price comes straight+ from the live market.+ </p>++ <!-- Quick presets. Hydrated by src/converter.js. -->+ <div+ class="cvt-presets"+ id="cvt-presets"+ role="group"+ aria-label="Quick conversions"+ ></div>++ <!-- Converter widget. Hydrated by src/converter.js. -->+ <section id="cvt-app" class="cvt-app" aria-label="Currency converter">+ <div class="cvt-card cv-card">+ <div class="cv-skel" style="height: 5.5rem; margin-bottom: 1rem"></div>+ <div class="cv-skel" style="height: 5.5rem"></div>+ </div>+ </section>++ <!-- Shared asset picker popover (fiat + crypto). Positioned by src/converter.js. -->+ <div id="cvt-picker" class="cvt-picker" hidden></div>++ <div class="cvt-links">+ <div class="cv-pills">+ <a class="cv-pill" href="/coins">Browse all coins →</a>+ <a class="cv-pill" href="/compare">Compare coins →</a>+ <a class="cv-pill" href="/heatmap">Market heatmap →</a>+ </div>+ </div>+ </main>++ <script type="module" src="/src/converter.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/defi.html b/pages/defi.htmlnew file mode 100644index 000000000..883bb8d08--- /dev/null+++ b/pages/defi.html@@ -0,0 +1,136 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>DeFi TVL & Protocols · three.ws</title>+ <meta+ name="description"+ content="Live DeFi total value locked — the top protocols ranked by TVL, with category, chains, and 1d/7d moves. See where liquidity sits across decentralized finance at a glance."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/defi" />+ <meta property="og:title" content="DeFi TVL & Protocols · three.ws" />+ <meta+ property="og:description"+ content="Live DeFi total value locked — the top protocols ranked by TVL, with category, chains, and 1d/7d moves. See where liquidity sits across decentralized finance."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=DeFi+TVL+%26+Protocols&d=Live+DeFi+total+value+locked%3A+the+top+protocols+ranked+by+TVL%2C+with+category%2C+chains%2C+and+1d%2F7d+moves.+See+where+liquidity+sits+across+decentralized+finance&p=%2Fdefi"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="DeFi TVL & Protocols · three.ws" />+ <meta+ name="twitter:description"+ content="Live DeFi total value locked — the top protocols ranked by TVL, with category, chains, and 1d/7d moves."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=DeFi+TVL+%26+Protocols&d=Live+DeFi+total+value+locked%3A+the+top+protocols+ranked+by+TVL%2C+with+category%2C+chains%2C+and+1d%2F7d+moves.+See+where+liquidity+sits+across+decentralized+finance&p=%2Fdefi"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/defi.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/defi" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="DeFi TVL & Protocols — three.ws" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "DeFi TVL & Protocols",+ "description": "Live DeFi total value locked: the top protocols ranked by TVL, with category, the chains they run on, and 1d/7d moves. See where liquidity sits across decentralized finance at a glance, sourced from DeFiLlama.",+ "url": "https://three.ws/defi",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=DeFi+TVL+%26+Protocols&d=Live+DeFi+total+value+locked%3A+the+top+protocols+ranked+by+TVL%2C+with+category%2C+chains%2C+and+1d%2F7d+moves.+See+where+liquidity+sits+across+decentralized+finance&p=%2Fdefi"+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/coins">Markets</a><span class="sep">/</span><span class="here">DeFi</span>+ </nav>+ <h1 class="cv-h1">DeFi TVL & Protocols</h1>+ <p class="cv-sub">+ Total value locked across decentralized finance — the top protocols ranked by TVL,+ with category, the chains they run on, and how each moved over the last day and+ week.+ </p>++ <!-- Header stat cards. Hydrated by src/defi.js. -->+ <section+ id="defi-stats"+ class="cv-section"+ aria-label="DeFi market statistics"+ ></section>++ <div class="cv-toolbar">+ <h2 class="cv-h2" style="margin: 0">Top Protocols by TVL</h2>+ <div class="defi-filter">+ <label class="defi-filter-label" for="defi-category">Category</label>+ <select+ id="defi-category"+ class="defi-select"+ aria-label="Filter protocols by category"+ >+ <option value="__all">All categories</option>+ </select>+ <a class="cv-pill" href="/chains">Chains →</a>+ </div>+ </div>++ <!-- Protocol table. Hydrated by src/defi.js. -->+ <section+ id="defi-table"+ aria-label="Top DeFi protocols by total value locked"+ ></section>+ <p class="cv-updated" id="defi-updated"></p>+ </main>++ <script type="module" src="/src/defi.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/derivatives.html b/pages/derivatives.htmlnew file mode 100644index 000000000..9f0579d46--- /dev/null+++ b/pages/derivatives.html@@ -0,0 +1,128 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Crypto Derivatives · three.ws</title>+ <meta+ name="description"+ content="Live perpetual futures markets across the major crypto exchanges — price, 24h move, funding rate, open interest, and 24h volume. Filter by index. Real CoinGecko data."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/derivatives" />+ <meta property="og:title" content="Crypto Derivatives · three.ws" />+ <meta+ property="og:description"+ content="Live perpetual futures markets — price, 24h move, funding rate, open interest, and 24h volume across the major exchanges."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Crypto+Derivatives&d=Live+perpetual+futures+markets+across+the+major+crypto+exchanges+%E2%80%94+price%2C+24h+move%2C+funding+rate%2C+open+interest%2C+and+24h+volume.+Filter+by+index&p=%2Fderivatives"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Crypto Derivatives · three.ws" />+ <meta+ name="twitter:description"+ content="Live perpetual futures markets — price, 24h move, funding rate, open interest, and 24h volume."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Crypto+Derivatives&d=Live+perpetual+futures+markets+across+the+major+crypto+exchanges+%E2%80%94+price%2C+24h+move%2C+funding+rate%2C+open+interest%2C+and+24h+volume.+Filter+by+index&p=%2Fderivatives"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/derivatives.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/derivatives" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Crypto Derivatives — three.ws" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Crypto Derivatives",+ "description": "Live perpetual futures markets across the major crypto exchanges — price, 24h move, funding rate, open interest, and 24h volume, filterable by underlying index. Real CoinGecko data, refreshed automatically, no API key required.",+ "url": "https://three.ws/derivatives",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=Crypto+Derivatives&d=Live+perpetual+futures+markets+across+the+major+crypto+exchanges+%E2%80%94+price%2C+24h+move%2C+funding+rate%2C+open+interest%2C+and+24h+volume.+Filter+by+index&p=%2Fderivatives"+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/coins">Markets</a><span class="sep">/</span+ ><span class="here">Derivatives</span>+ </nav>+ <h1 class="cv-h1">Crypto Derivatives</h1>+ <p class="cv-sub">+ Live perpetual futures markets across the major exchanges — funding rate, open+ interest, and 24h volume for every contract. Positive funding means longs pay+ shorts; negative means shorts pay longs.+ </p>++ <!-- Header stat cards. Hydrated by src/derivatives.js. -->+ <section+ id="dv-stats"+ class="cv-section"+ aria-label="Derivatives market summary"+ ></section>++ <!-- Index filter chips. Hydrated by src/derivatives.js. -->+ <div+ class="hm-seg"+ role="group"+ aria-label="Filter by index"+ id="dv-filters"+ hidden+ ></div>++ <!-- Sortable perpetuals table. Hydrated by src/derivatives.js. -->+ <section id="dv-market" aria-label="Perpetual futures markets"></section>+ <p class="cv-updated" id="dv-updated"></p>+ </main>++ <script type="module" src="/src/derivatives.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/exchanges.html b/pages/exchanges.htmlnew file mode 100644index 000000000..0e877a9d2--- /dev/null+++ b/pages/exchanges.html@@ -0,0 +1,119 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Crypto Exchanges · three.ws</title>+ <meta+ name="description"+ content="The top crypto exchanges ranked by trust score and 24h trading volume — with country, launch year, and a direct link to each venue. Real CoinGecko data, no API key."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/exchanges" />+ <meta property="og:title" content="Crypto Exchanges · three.ws" />+ <meta+ property="og:description"+ content="The top crypto exchanges ranked by trust score and 24h trading volume, with country, launch year, and a direct link to each venue."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Crypto+Exchanges&d=The+top+crypto+exchanges+ranked+by+trust+score+and+24h+trading+volume%2C+with+country%2C+launch+year%2C+and+a+direct+link+to+each+venue.+Real+CoinGecko+data&p=%2Fexchanges"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Crypto Exchanges · three.ws" />+ <meta+ name="twitter:description"+ content="The top crypto exchanges ranked by trust score and 24h trading volume."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Crypto+Exchanges&d=The+top+crypto+exchanges+ranked+by+trust+score+and+24h+trading+volume%2C+with+country%2C+launch+year%2C+and+a+direct+link+to+each+venue.+Real+CoinGecko+data&p=%2Fexchanges"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/exchanges.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/exchanges" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Crypto Exchanges — three.ws" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Crypto Exchanges",+ "description": "The top crypto exchanges ranked by trust score and 24h trading volume, with country, launch year, and a direct link to each venue. Real CoinGecko data, refreshed automatically, no API key required.",+ "url": "https://three.ws/exchanges",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=Crypto+Exchanges&d=The+top+crypto+exchanges+ranked+by+trust+score+and+24h+trading+volume%2C+with+country%2C+launch+year%2C+and+a+direct+link+to+each+venue.+Real+CoinGecko+data&p=%2Fexchanges"+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/coins">Markets</a><span class="sep">/</span+ ><span class="here">Exchanges</span>+ </nav>+ <h1 class="cv-h1">Crypto Exchanges</h1>+ <p class="cv-sub">+ The top crypto exchanges ranked by trust score and trading volume. Trust score is+ CoinGecko's 0–10 measure of a venue's liquidity, scale, and data integrity. Click+ any row to open the exchange.+ </p>++ <!-- Header stat cards. Hydrated by src/exchanges.js. -->+ <section+ id="ex-stats"+ class="cv-section"+ aria-label="Exchange market summary"+ ></section>++ <!-- Sortable exchanges table. Hydrated by src/exchanges.js. -->+ <section id="ex-market" aria-label="Crypto exchanges"></section>+ <p class="cv-updated" id="ex-updated"></p>+ </main>++ <script type="module" src="/src/exchanges.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/screener.html b/pages/screener.htmlnew file mode 100644index 000000000..25bb9c9db--- /dev/null+++ b/pages/screener.html@@ -0,0 +1,179 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Token Screener · three.ws</title>+ <meta+ name="description"+ content="Filter the top 250 cryptocurrencies live — search by name, isolate gainers or losers, set minimum market cap and volume, and sort every column. Find your next coin fast."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/screener" />+ <meta property="og:title" content="Token Screener · three.ws" />+ <meta+ property="og:description"+ content="Filter the top 250 cryptocurrencies live — search, isolate gainers or losers, set minimum market cap and volume, and sort every column."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Token+Screener&d=Filter+the+top+250+cryptocurrencies+live%3A+search+by+name%2C+isolate+gainers+or+losers%2C+set+minimum+market+cap+and+volume%2C+and+sort+every+column.+Find+your+next+coin+fast&p=%2Fscreener"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Token Screener · three.ws" />+ <meta+ name="twitter:description"+ content="Filter the top 250 cryptocurrencies live — search, isolate gainers or losers, set minimum market cap and volume, and sort every column."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Token+Screener&d=Filter+the+top+250+cryptocurrencies+live%3A+search+by+name%2C+isolate+gainers+or+losers%2C+set+minimum+market+cap+and+volume%2C+and+sort+every+column.+Find+your+next+coin+fast&p=%2Fscreener"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/screener.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/screener" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Token Screener — three.ws" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Token Screener",+ "description": "Filter the top 250 cryptocurrencies live: search by name or symbol, isolate gainers or losers, set a minimum market cap and 24h volume, and sort every column. Every match links to a rich /coin/:id detail page with an interactive chart, market stats, and news.",+ "url": "https://three.ws/screener",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=Token+Screener&d=Filter+the+top+250+cryptocurrencies+live%3A+search+by+name%2C+isolate+gainers+or+losers%2C+set+minimum+market+cap+and+volume%2C+and+sort+every+column.+Find+your+next+coin+fast&p=%2Fscreener"+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/coins">Markets</a><span class="sep">/</span+ ><span class="here">Screener</span>+ </nav>+ <h1 class="cv-h1">Token Screener</h1>+ <p class="cv-sub">+ Filter the top 250 coins by market cap in real time — search by name, isolate+ gainers or losers, set floors on market cap and volume, then sort any column. Every+ row opens the full coin profile.+ </p>++ <!-- Filter controls. Wired by src/screener.js. -->+ <div class="scr-controls">+ <div class="cv-search" id="scr-search" style="max-width: 20rem">+ <span class="mag" aria-hidden="true">+ <svg+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ >+ <circle cx="11" cy="11" r="8" />+ <path d="m21 21-4.3-4.3" />+ </svg>+ </span>+ <input+ id="scr-search-input"+ type="search"+ placeholder="Filter by name or symbol…"+ autocomplete="off"+ spellcheck="false"+ aria-label="Filter coins by name or symbol"+ />+ </div>++ <div class="hm-seg" role="group" aria-label="Direction filter" id="scr-dir">+ <button type="button" data-dir="all" aria-pressed="true">All</button>+ <button type="button" data-dir="gainers" aria-pressed="false">Gainers</button>+ <button type="button" data-dir="losers" aria-pressed="false">Losers</button>+ </div>++ <label class="scr-field">+ <span>Min market cap</span>+ <select id="scr-mcap" aria-label="Minimum market cap">+ <option value="0">Any</option>+ <option value="10000000">$10M+</option>+ <option value="100000000">$100M+</option>+ <option value="1000000000">$1B+</option>+ <option value="10000000000">$10B+</option>+ <option value="100000000000">$100B+</option>+ </select>+ </label>++ <label class="scr-field">+ <span>Min 24h volume</span>+ <select id="scr-vol" aria-label="Minimum 24h volume">+ <option value="0">Any</option>+ <option value="1000000">$1M+</option>+ <option value="10000000">$10M+</option>+ <option value="100000000">$100M+</option>+ <option value="1000000000">$1B+</option>+ </select>+ </label>++ <button type="button" class="scr-reset" id="scr-reset">Reset</button>+ </div>++ <div class="scr-meta">+ <span id="scr-count" class="scr-count" aria-live="polite"></span>+ <div class="cv-pills">+ <a class="cv-pill" href="/coins">All Coins</a>+ <a class="cv-pill" href="/categories">Categories</a>+ <a class="cv-pill" href="/heatmap">Heatmap</a>+ </div>+ </div>++ <!-- Results table. Hydrated by src/screener.js. -->+ <section id="scr-table" aria-label="Screened cryptocurrencies"></section>+ <p class="cv-updated" id="scr-updated"></p>+ </main>++ <script type="module" src="/src/screener.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/stablecoins.html b/pages/stablecoins.htmlnew file mode 100644index 000000000..d7c1c0ca4--- /dev/null+++ b/pages/stablecoins.html@@ -0,0 +1,124 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Stablecoins Market Cap · three.ws</title>+ <meta+ name="description"+ content="Track the top stablecoins by market cap — peg health, dominance share, backing mechanism, and the chains each one lives on. Live data from DeFiLlama."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/stablecoins" />+ <meta property="og:title" content="Stablecoins Market Cap · three.ws" />+ <meta+ property="og:description"+ content="The top stablecoins ranked by market cap — with live peg health, dominance share, backing mechanism, and chains. Data from DeFiLlama."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Stablecoins+Market+Cap&d=The+top+stablecoins+ranked+by+market+cap%2C+with+live+peg+health%2C+dominance+share%2C+backing+mechanism%2C+and+the+chains+each+one+lives+on&p=%2Fstablecoins"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Stablecoins Market Cap · three.ws" />+ <meta+ name="twitter:description"+ content="The top stablecoins ranked by market cap — with live peg health, dominance, mechanism, and chains."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Stablecoins+Market+Cap&d=The+top+stablecoins+ranked+by+market+cap%2C+with+live+peg+health%2C+dominance+share%2C+backing+mechanism%2C+and+the+chains+each+one+lives+on&p=%2Fstablecoins"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/stablecoins.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/stablecoins" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Stablecoins Market Cap — three.ws" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Stablecoins Market Cap",+ "description": "The top stablecoins ranked by market cap, with live peg health, dominance share, backing mechanism, and the chains each one lives on. Data from DeFiLlama.",+ "url": "https://three.ws/stablecoins",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=Stablecoins+Market+Cap&d=The+top+stablecoins+ranked+by+market+cap%2C+with+live+peg+health%2C+dominance+share%2C+backing+mechanism%2C+and+the+chains+each+one+lives+on&p=%2Fstablecoins"+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/coins">Markets</a><span class="sep">/</span+ ><span class="here">Stablecoins</span>+ </nav>+ <h1 class="cv-h1">Stablecoins Market Cap</h1>+ <p class="cv-sub">+ The stablecoin market at a glance — ranked by circulating supply, with live peg+ health, dominance share, backing mechanism, and the chains each one lives on. A+ price drifting from $1.00 shows red; on-peg shows green.+ </p>++ <!-- Stat cards. Hydrated by src/stablecoins.js. -->+ <section id="sc-stats" aria-label="Stablecoin market summary"></section>++ <div class="cv-toolbar">+ <div+ class="hm-seg"+ role="group"+ aria-label="Filter by peg mechanism"+ id="sc-filter"+ ></div>+ </div>++ <!-- Sortable table. Hydrated by src/stablecoins.js. -->+ <section id="sc-table" aria-label="Stablecoins ranked by market cap"></section>+ <p class="cv-updated" id="sc-updated">Data: DeFiLlama</p>+ </main>++ <script type="module" src="/src/stablecoins.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/prompts/roadmap/_generated/01/gate-inventory.md b/prompts/roadmap/_generated/01/gate-inventory.mdindex 46b8e3e0e..646f5c61a 100644--- a/prompts/roadmap/_generated/01/gate-inventory.md+++ b/prompts/roadmap/_generated/01/gate-inventory.md@@ -103,6 +103,39 @@ drift outside this prompt's remit (introduced by unrelated work between the2026-07-04 baseline and this pass) and was resolved by a concurrent agent'scommit, not by scope creep in this pass.+## 2026-07-08 pass B — extend golden coverage to published packages + guard `title`++The prior passes snapshotted only the **hosted** MCP servers (`api/_mcp*`, 76+contracts / 16 files). The **32 published `packages/*-mcp`** — the tools other+people install from the registry — had **zero** contract protection: a refactor+could silently change any published tool's name, title, input schema, or safety+annotations and nothing would fail. This pass closes that gap.++1. **Coverage extended to `packages/*-mcp/src/tools/*.js`.** `scripts/audit-mcp-golden.mjs`+ now discovers every `packages/<name>-mcp/src/tools/*.js` (skipping `index.js`+ barrels) via a new `packageToolSources()` helper and folds them into `SOURCES`.+ Fixture grew **76/16 → 223 tool contracts / 163 files** (+147 package files+ across 32 packages). Same static-AST mechanism (acorn, no import, no network) —+ fully consistent with the "never import catalogs" offline doctrine.+2. **`title` now snapshotted *and* compared.** The extractor captured+ name/description/annotations/schema but not `title`, and the diff loop only+ checked `descHash`/`schemaHash`/`annotations` — so a tool's public title could+ drift undetected (and prompt 01's own tripwire is a title change). Added `title`+ to both the extracted contract and the compared-field list. All 223 contracts+ now carry a snapshotted title.+3. **Tripwire re-proven for the new surface + field.** Mutated+ `three_price.title` in `packages/three-token-mcp/src/tools/three-price.js`;+ `audit:mcp-golden` exited non-zero with+ `three_price.title changed`; reverted → green. See `tripwire-proof.md`.++Net: a published MCP package tool's contract can no longer change silently.+Regenerate after an intentional change with `node scripts/audit-mcp-golden.mjs --update`.++Concurrency note: this worktree is shared with other agents (CLAUDE.md "Known+traps"). Only these paths were touched here — `scripts/audit-mcp-golden.mjs`,+`tests/fixtures/mcp-golden-tools.json`, and this `_generated/01/` doc — staged+explicitly, never `git add -A`.+## Pre-existing advisories (not fixed here, per prompt 01 hand-off rules)1. `TRAILSLASH /payments/` lands on the designed 404 (route audit advisory).diff --git a/prompts/roadmap/_generated/01/tripwire-proof.md b/prompts/roadmap/_generated/01/tripwire-proof.mdnew file mode 100644index 000000000..26d9dc221--- /dev/null+++ b/prompts/roadmap/_generated/01/tripwire-proof.md@@ -0,0 +1,38 @@+# Golden-snapshot tripwire proof — package tool + `title` field (2026-07-08 pass B)++Proves `audit:mcp-golden` catches a public-contract change on a **published+package tool** and on the **`title`** field — the two things pass B added.+(The 2026-07-04 proof for a *hosted* tool rename is in `tripwire-proof.txt`.)++## Procedure++Target: `packages/three-token-mcp/src/tools/three-price.js`, tool `three_price`.++```+1. Clean tree → audit green:+ $ node scripts/audit-mcp-golden.mjs+ [audit:mcp-golden] 223 hosted MCP tool contracts match the golden fixture++2. Mutate the tool title:+ title: 'Live $THREE price (Jupiter) + USD→$THREE quote'+ → title: 'MUTATED TITLE (tripwire test)'++3. Audit re-run → FAILS with exact diagnosis (exit 1):+ [audit:mcp-golden] packages/three-token-mcp/src/tools/three-price.js: three_price.title changed (was "Return the live USD price of $THREE (Jupiter primary, Birdeye fallback).")+ [audit:mcp-golden] 1 contract change(s) vs golden fixture.++4. Revert (git checkout -- <file>) → audit green again:+ [audit:mcp-golden] 223 hosted MCP tool contracts match the golden fixture+```++## Result++- The change was to a `packages/*-mcp` tool — a surface that had **no** golden+ protection before pass B. It is now caught. ✅+- The changed field was `title` — previously neither snapshotted nor compared.+ It is now caught. ✅+- Diagnosis names the exact file, tool, and field. Reverting restores green with+ no fixture edit needed (proving the fixture and live source agree on a clean tree).++Regenerate the fixture only for an *intentional* contract change:+`node scripts/audit-mcp-golden.mjs --update`.diff --git a/prompts/roadmap/_generated/02/gate-before.txt b/prompts/roadmap/_generated/02/gate-before.txtindex b4f688663..790598a86 100644--- a/prompts/roadmap/_generated/02/gate-before.txt+++ b/prompts/roadmap/_generated/02/gate-before.txt@@ -1,425 +1,49 @@-> [email protected] typecheck-> tsc -p jsconfig.json+> [email protected] gate+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens-> [email protected] test-> vitest run && playwright test+> [email protected] test:gate+> node scripts/test-gate.mjs+[test-gate] running 7 critical-path test files…- RUN v4.1.7 /workspaces/three.ws+ RUN v4.1.9 /workspaces/three.ws- ❯ tests/api/x402-spec.test.js (23 tests | 2 failed) 2012ms- × advertises only USDC on Solana by default (no THREE accept) 12ms- × adds a THREE Solana accept after USDC when X402_ACCEPT_THREE_SOLANA is on 4ms- ❯ tests/refine-lineage.test.js (20 tests | 1 failed) 20ms- × is deterministic — same inputs give the same prompt 7ms- ❯ tests/remix-royalty.test.js (15 tests | 1 failed) 18ms- × drops a sub-dust royalty rather than paying it 9ms- ❯ tests/api/forge-lane-routing.test.js (16 tests | 1 failed) 21ms- × treats unknown/degraded health as usable (never blocks on missing telemetry) 8ms-stderr | tests/auto-rig-completion.test.js > 6a — cron recovers an open job from its stored result_glb_url > finalizes via the stored URL and never re-polls the provider-[auto-rig-sweep] job error { jobId: 'job-a', error: 'Invalid IP address: undefined' }- ❯ tests/auto-rig-completion.test.js (5 tests | 3 failed) 119ms- × finalizes via the stored URL and never re-polls the provider 103ms- × lets exactly one of two concurrent finalizes materialize the avatar 4ms- × a thrown winner releases the claim to a cron-selectable status (not done, not wedged) 8ms- ❯ tests/api/agent-memory.test.js (22 tests | 1 failed) 30ms- × truncates content longer than 10,000 characters 7ms- ❯ tests/metering.test.js (11 tests | 1 failed) 55ms- × issues a MeterUsage command with the product code, dimension, and idempotency allocation 42ms- ❯ tests/build-asset-paths.test.js (5 tests | 1 failed) 15ms- × serves /style.css from dist root 12ms- ❯ tests/branding.test.js (4 tests | 4 failed) 8398ms- × no "Avaturn" in user-facing files 7728ms- × no "Character Studio" in user-facing files 308ms- × no "Ready Player Me" in user-facing files 191ms- × no "RPM" referring to Ready Player Me (heuristic: near avatar/selfie) 169ms-stderr | tests/api/x402-discovery-green.test.js > x402 discovery catalog is fully green > every resource carries a real output.example for result cards-[wk/x402-discovery] agent services unavailable Missing required env var: DATABASE_URL+ Test Files 7 passed (7)+ Tests 83 passed (83)+ Start at 00:50:45+ Duration 2.74s (transform 1.53s, setup 0ms, import 3.21s, tests 2.80s, environment 1ms)-stderr | tests/api/x402-discovery-green.test.js > x402 discovery catalog is fully green-[wk/x402-discovery] agent services unavailable Missing required env var: DATABASE_URL+[test-gate] ✓ all critical-path tests passed- ❯ tests/api/x402-discovery-green.test.js (4 tests | 2 failed) 1957ms- × has no listing-quality warnings (every resource ranks and renders fully) 9ms- × every resource carries a real output.example for result cards 5ms- ❯ tests/mcp-forge-free.test.js (7 tests | 3 failed) 30ms- × surfaces a not-configured deployment as a designed error 11ms- × surfaces a busy lane as a rate_limited error with retry hint 5ms- × reports a terminal generation failure from the poll loop 2ms- ❯ tests/pose-presets.test.js (9 tests | 1 failed) 153ms- × no preset drives a hand or the head below the floor 103ms+> [email protected] test:gate-3d+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js-⎯⎯⎯⎯⎯⎯ Failed Tests 21 ⎯⎯⎯⎯⎯⎯⎯- FAIL tests/auto-rig-completion.test.js > 6a — cron recovers an open job from its stored result_glb_url > finalizes via the stored URL and never re-polls the provider-AssertionError: expected +0 to be 1 // Object.is equality+ RUN v4.1.9 /workspaces/three.ws-- Expected-+ Received-- 1-+ 0+ Test Files 4 passed (4)+ Tests 244 passed (244)+ Start at 00:50:49+ Duration 525ms (transform 184ms, setup 0ms, import 560ms, tests 319ms, environment 1ms)- ❯ tests/auto-rig-completion.test.js:206:26- 204| expect(body.ok).toBe(true);- 205| expect(body.scanned).toBe(1);- 206| expect(body.finalized).toBe(1);- | ^- 207|- 208| // Req 4: the stored URL was reused — the provider's status() was NO…-⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/21]⎯+> [email protected] audit:mcp+> node scripts/audit-mcp-manifests.mjs- FAIL tests/auto-rig-completion.test.js > 6c — finalizeAutoRigStage is concurrency-safe > lets exactly one of two concurrent finalizes materialize the avatar-TypeError: Invalid IP address: undefined- ❯ lookup api/_lib/ssrf-guard.js:172:5- 170| const agent = new AgentClass({- 171| lookup(_hostname, _options, cb) {- 172| cb(null, pinnedIp, net.isIPv6(pinnedIp) ? 6 : 4);- | ^- 173| },- 174| });+[audit:mcp] 16 MCP manifests consistent-⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/21]⎯+> [email protected] audit:mcp-golden+> node scripts/audit-mcp-golden.mjs- FAIL tests/auto-rig-completion.test.js > 6c — finalizeAutoRigStage is concurrency-safe > a thrown winner releases the claim to a cron-selectable status (not done, not wedged)-AssertionError: expected [Function] to throw error including 'r2 down' but got 'Invalid IP address: undefined'--Expected: "r2 down"-Received: "Invalid IP address: undefined"-- ❯ tests/auto-rig-completion.test.js:329:4- 327| await expect(- 328| finalizeAutoRigStage({ userId: 'u1', jobId: 'job-d', job, glbUrl: '…- 329| ).rejects.toThrow('r2 down');- | ^- 330|- 331| // The claim was released back to 'running' — cron-selectable, never…--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[3/21]⎯-- FAIL tests/branding.test.js > three.ws branding lock > no "Avaturn" in user-facing files-Error: Forbidden brand "Avaturn" found in 5 user-facing location(s):- docs/launch/go-no-go-2026-06-24.md:150- brands **"Avaturn" (×4), "Ready Player Me" (×7), "Character Studio" (×2), "RPM"** in user-facing- docs/tutorials/animate-your-avatar.md:170- **Facial expression** ([src/runtime/arkit52.js](../../src/runtime/arkit52.js)) — independent of the skeleton. If your avatar carries ARKit-52 blendshapes (most modern exports do — RPM, Avaturn, VRoid), the runtime resolves those morph targets and drives expression and lip-sync directly on the face. A skeletal clip plays the body; the blendshape layer plays the eyes, brows, and mouth on top.- docs/tutorials/animate-your-avatar.md:180- - **"This rig can't be retargeted — only N recognizable humanoid bones."** The model exposes fewer than 8 canonical bones. It's likely non-humanoid, a static prop, or a rig whose bone names the canonicalizer doesn't recognize. Re-export it as a standard humanoid (Mixamo, RPM, Avaturn, VRM all work), or auto-rig a rig-less mesh first.- docs/ux-flows/01-onboarding-creation.md:43- - **External calls / dependencies:** `GET /api/config`; `GET /api/avatars`; `GET /api/usage/summary`; `POST /api/avatars/fork`; `GET /api/avatars/:id` + raw GLB fetch (guest fork). Avaturn / Ready Player Me iframes loaded by `AvatarCreator`.- src/viewer/framing.js:50- * default, every Avaturn/RPM rig) are returned unchanged and never re-framed.--Replace with three.ws-branded language, or add a documented exemption to tests/branding-allowlist.json.- ❯ tests/branding.test.js:370:11---⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[4/21]⎯-- FAIL tests/branding.test.js > three.ws branding lock > no "Character Studio" in user-facing files-Error: Forbidden brand "Character Studio" found in 3 user-facing location(s):- public/docs/index.html:131- ['character-studio', 'Character studio', 'Author and pose characters.'],- docs/internal/ISSUES-ARCHIVE-2026-06.md:11- vendored CharacterStudio fork that all predated the upgrade.- docs/launch/go-no-go-2026-06-24.md:150- brands **"Avaturn" (×4), "Ready Player Me" (×7), "Character Studio" (×2), "RPM"** in user-facing--Replace with three.ws-branded language, or add a documented exemption to tests/branding-allowlist.json.- ❯ tests/branding.test.js:370:11---⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[5/21]⎯-- FAIL tests/branding.test.js > three.ws branding lock > no "Ready Player Me" in user-facing files-Error: Forbidden brand "Ready Player Me" found in 8 user-facing location(s):- public/demos/audio2face.html:95- (ARKit, Ready Player Me, VRM, Oculus visemes). If Audio2Face is unavailable, the- docs/launch/go-no-go-2026-06-24.md:150- brands **"Avaturn" (×4), "Ready Player Me" (×7), "Character Studio" (×2), "RPM"** in user-facing- docs/tutorials/import-avatar-url.md:3- You already have an avatar living somewhere else — a Ready Player Me model on a CloudFront link, a GLB on Arweave, an export sitting in your own storage. You don't need to download it, convert it, or re-host it. Paste the URL into [three.ws/import/rpm](/import/rpm) and the platform fetches it server-side, normalizes its skeleton, auto-rigs it so it can move, and saves it to your account as an avatar an agent can wear.- docs/tutorials/import-avatar-url.md:14- You: paste https://models.readyplayer.me/64c3….glb into /import/rpm- docs/tutorials/import-avatar-url.md:31- Most avatar hosts (Ready Player Me's CloudFront CDN, Arweave gateways, arbitrary object storage) serve their GLBs **without CORS headers**. A browser `fetch()` to those URLs is blocked before a single byte arrives. So the importer doesn't rely on your browser reaching the file at all:- docs/tutorials/import-avatar-url.md:50- **Ready Player Me.** RPM gives you a model URL of the form `https://models.readyplayer.me/<id>.glb`. If you only have the avatar's web page, append `.glb` to the avatar ID, or open the page, then DevTools → **Network**, filter by `.glb`, and copy the request URL. RPM serves these from a CloudFront CDN with no CORS headers — exactly the case the server-side fetch is built for.- docs/tutorials/import-avatar-url.md:148- - **Paste a `.glb` URL** at [/import/rpm](/import/rpm) — Ready Player Me, any CDN, Arweave, or your own storage all work.- docs/ux-flows/01-onboarding-creation.md:43- - **External calls / dependencies:** `GET /api/config`; `GET /api/avatars`; `GET /api/usage/summary`; `POST /api/avatars/fork`; `GET /api/avatars/:id` + raw GLB fetch (guest fork). Avaturn / Ready Player Me iframes loaded by `AvatarCreator`.--Replace with three.ws-branded language, or add a documented exemption to tests/branding-allowlist.json.- ❯ tests/branding.test.js:370:11---⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[6/21]⎯-- FAIL tests/branding.test.js > three.ws branding lock > no "RPM" referring to Ready Player Me (heuristic: near avatar/selfie)-Error: Found "RPM" near avatar/selfie context in 4 location(s) — assume Ready Player Me:- prompts/roadmap/REUSE-MAP.md:36- | Turnkey talking-avatar | met4citizen/TalkingHead (+HeadTTS) | ✅ MIT | Full Oculus OVR + ARKit viseme pipeline on RPM/Mixamo GLB. |- docs/tutorials/animate-your-avatar.md:170- **Facial expression** ([src/runtime/arkit52.js](../../src/runtime/arkit52.js)) — independent of the skeleton. If your avatar carries ARKit-52 blendshapes (most modern exports do — RPM, Avaturn, VRoid), the runtime resolves those morph targets and drives expression and lip-sync directly on the face. A skeletal clip plays the body; the blendshape layer plays the eyes, brows, and mouth on top.- docs/tutorials/import-avatar-url.md:50- **Ready Player Me.** RPM gives you a model URL of the form `https://models.readyplayer.me/<id>.glb`. If you only have the avatar's web page, append `.glb` to the avatar ID, or open the page, then DevTools → **Network**, filter by `.glb`, and copy the request URL. RPM serves these from a CloudFront CDN with no CORS headers — exactly the case the server-side fetch is built for.- docs/ux-flows/04-embed-widget-studio.md:167- - **avatar-embed runtime** (`src/avatar-embed.js`) backs `/embed/avatar/<handle>`, `/a-embed.html`, and the agent embed; exposes the `v1.avatar.*` postMessage bridge (speak, emote, morphs, lookAt, mocap, idle, hotkeys, mic, state) plus RPM-compatible event aliases and a same-origin BroadcastChannel control surface.- ❯ tests/branding.test.js:407:10- 405| .map((h) => ` ${h.file}:${h.line}\n ${h.text}`)- 406| .join('\n');- 407| throw new Error(- | ^- 408| `Found "RPM" near avatar/selfie context in ${hits.length} location…- 409| );--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[7/21]⎯-- FAIL tests/build-asset-paths.test.js > build asset paths > serves /style.css from dist root-AssertionError: expected false to be true // Object.is equality--- Expected-+ Received--- true-+ false-- ❯ tests/build-asset-paths.test.js:19:50- 17|- 18| it('serves /style.css from dist root', () => {- 19| expect(existsSync(resolve(dist, 'style.css'))).toBe(true);- | ^- 20| });- 21|--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[8/21]⎯-- FAIL tests/mcp-forge-free.test.js > forge_free — handler > surfaces a not-configured deployment as a designed error-AssertionError: expected 'provider_error' to be 'not_configured' // Object.is equality--Expected: "not_configured"-Received: "provider_error"-- ❯ tests/mcp-forge-free.test.js:158:21- 156| const out = structured(envelope);- 157| expect(out.ok).toBe(false);- 158| expect(out.error).toBe('not_configured');- | ^- 159| });- 160|--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[9/21]⎯-- FAIL tests/mcp-forge-free.test.js > forge_free — handler > surfaces a busy lane as a rate_limited error with retry hint-AssertionError: expected 'provider_error' to be 'rate_limited' // Object.is equality--Expected: "rate_limited"-Received: "provider_error"-- ❯ tests/mcp-forge-free.test.js:165:21- 163| const out = structured(await tool.handler({ prompt: 'a ceramic teapo…- 164| expect(out.ok).toBe(false);- 165| expect(out.error).toBe('rate_limited');- | ^- 166| expect(out.retryAfter).toBe(8);- 167| });--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[10/21]⎯-- FAIL tests/mcp-forge-free.test.js > forge_free — handler > reports a terminal generation failure from the poll loop-AssertionError: expected 'provider_error' to be 'generation_failed' // Object.is equality--Expected: "generation_failed"-Received: "provider_error"-- ❯ tests/mcp-forge-free.test.js:175:21- 173| const out = structured(await tool.handler({ prompt: 'a marble bust' …- 174| expect(out.ok).toBe(false);- 175| expect(out.error).toBe('generation_failed');- | ^- 176| });- 177| });--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[11/21]⎯-- FAIL tests/metering.test.js > AWS Marketplace — MeterUsage call shape (SDK boundary mocked) > issues a MeterUsage command with the product code, dimension, and idempotency allocation-TypeError: vi.dontMock is not a function- ❯ tests/metering.test.js:194:6- 192| // Idempotency allocation carries the dedupe key AWS bills against.- 193| expect(input.UsageAllocations[0].Tags[0].Value).toBe('alloc-1');- 194| vi.dontMock('@aws-sdk/client-marketplace-metering');- | ^- 195| vi.dontMock('@aws-sdk/client-marketplace-entitlement-service');- 196| vi.dontMock('../api/_lib/env.js');--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[12/21]⎯-- FAIL tests/pose-presets.test.js > pose geometry (real mannequin forward kinematics) > no preset drives a hand or the head below the floor-AssertionError: sit-floor L hand: expected -0.19006247768508422 to be greater than -0.15- ❯ tests/pose-presets.test.js:106:48- 104| // A small negative tolerance: floor-contact poses (push-up-style) …- 105| // graze y=0, but nothing should sink a hand far underground.- 106| expect(handTip(m, 'L').y, `${p.id} L hand`).toBeGreaterThan(-0.15);- | ^- 107| expect(handTip(m, 'R').y, `${p.id} R hand`).toBeGreaterThan(-0.15);- 108| expect(head.y, `${p.id} head`).toBeGreaterThan(0.2);--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[13/21]⎯-- FAIL tests/refine-lineage.test.js > composeRefinement > is deterministic — same inputs give the same prompt-AssertionError: expected 'a knight helmet, bigger helmet' to be 'a knight helmet, helmet bigger' // Object.is equality--Expected: "a knight helmet, helmet bigger"-Received: "a knight helmet, bigger helmet"-- ❯ tests/refine-lineage.test.js:52:13- 50| const b = composeRefinement('a knight helmet', 'bigger helmet');- 51| expect(a).toBe(b);- 52| expect(a).toBe('a knight helmet, helmet bigger');- | ^- 53| });- 54|--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[14/21]⎯-- FAIL tests/remix-royalty.test.js > computeRemixSplit — split math > drops a sub-dust royalty rather than paying it-AssertionError: expected true to be false // Object.is equality--- Expected-+ Received--- false-+ true-- ❯ tests/remix-royalty.test.js:70:55- 68| // Tiny price where 10% rounds below the dust floor.- 69| const s = computeRemixSplit({ priceAtomics: 50_000n, royaltyBps: 100…- 70| expect(s.creatorAtomics < REMIX_MIN_PAYOUT_ATOMICS).toBe(false); // …- | ^- 71| expect(s.creatorAtomics).toBe(0n);- 72| expect(s.dust).toBe(true);--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[15/21]⎯-- FAIL tests/api/agent-memory.test.js > POST /api/agent-memory > truncates content longer than 10,000 characters-AssertionError: expected undefined to be defined- ❯ tests/api/agent-memory.test.js:405:27- 403|- 404| expect(status).toBe(201);- 405| expect(capturedContent).toBeDefined();- | ^- 406| expect(capturedContent.length).toBe(10_000);- 407| });--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[16/21]⎯-- FAIL tests/api/forge-lane-routing.test.js > resolveBackendIdWithHealth — prefer healthy self-host → other free → paid > treats unknown/degraded health as usable (never blocks on missing telemetry)-AssertionError: expected 'huggingface' to be 'trellis_selfhost' // Object.is equality--Expected: "trellis_selfhost"-Received: "huggingface"-- ❯ tests/api/forge-lane-routing.test.js:123:101- 121| // trellis_selfhost has no entry (unknown) → still picked, ahead of …- 122| const health = { huggingface: 'ok' };- 123| expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard',…- | ^- 124| 'trellis_selfhost',- 125| );--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[17/21]⎯-- FAIL tests/api/x402-discovery-green.test.js > x402 discovery catalog is fully green > has no listing-quality warnings (every resource ranks and renders fully)-AssertionError: Resources with listing-quality warnings:- ▲ /api/x402/token-intel: no output.example: expected [ { …(3) } ] to deeply equal []--- Expected-+ Received--- []-+ [-+ {-+ "errors": [],-+ "label": "/api/x402/token-intel",-+ "warnings": [-+ "no output.example",-+ ],-+ },-+ ]-- ❯ tests/api/x402-discovery-green.test.js:158:5- 156| .map((r) => ` ▲ ${r.label}: ${r.warnings.join('; ')}`)- 157| .join('\n')}`,- 158| ).toEqual([]);- | ^- 159| });- 160|--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[18/21]⎯-- FAIL tests/api/x402-discovery-green.test.js > x402 discovery catalog is fully green > every resource carries a real output.example for result cards-AssertionError: /api/x402/token-intel is missing bazaar.info.output.example: expected undefined to be truthy--- Expected:-true--+ Received:-undefined-- ❯ tests/api/x402-discovery-green.test.js:165:68- 163| for (const r of doc.resources || []) {- 164| const ex = (r.extensions?.bazaar || r.bazaar)?.info?.output?.exampl…- 165| expect(ex, `${label(r)} is missing bazaar.info.output.example`).toB…- | ^- 166| }- 167| });--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[19/21]⎯-- FAIL tests/api/x402-spec.test.js > paymentRequirements > advertises only USDC on Solana by default (no THREE accept)-AssertionError: expected 2 to be 1 // Object.is equality--- Expected-+ Received--- 1-+ 2-- ❯ tests/api/x402-spec.test.js:243:25- 241| r.network.startsWith('solana:'),- 242| );- 243| expect(solana.length).toBe(1);- | ^- 244| expect(solana[0].extra.name).toBe('USDC');- 245| });--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[20/21]⎯-- FAIL tests/api/x402-spec.test.js > paymentRequirements > adds a THREE Solana accept after USDC when X402_ACCEPT_THREE_SOLANA is on-AssertionError: expected '10000000' to be '1000' // Object.is equality--Expected: "1000"-Received: "10000000"-- ❯ tests/api/x402-spec.test.js:261:28- 259| expect(solana[1].extra.feePayer).toBe(solana[0].extra.feePayer);- 260| // Default: reuses the USDC atomic price.- 261| expect(solana[1].amount).toBe(solana[0].amount);- | ^- 262| });- 263|--⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[21/21]⎯--- Test Files 12 failed | 580 passed | 3 skipped (595)- Tests 21 failed | 8504 passed | 18 skipped (8543)- Start at 22:43:37- Duration 182.83s (transform 21.96s, setup 0ms, import 187.03s, tests 155.75s, environment 25.75s)+[audit:mcp-golden] api/_mcp3d/tools/spatial.js: tool ADDED: validate_spatial_response+[audit:mcp-golden] 1 contract change(s) vs golden fixture.+ If every change above is INTENTIONAL (reviewed as a public-contract change),+ refresh the fixture: node scripts/audit-mcp-golden.mjs --updateEXIT_CODE=1+--- Note ---+Baseline failure is PRE-EXISTING, caused by a concurrent agent's untracked work (api/_lib/spatial-mcp.js adds an MCP tool 'validate_spatial_response' not yet reflected in tests/fixtures/mcp-golden-tools.json). Unrelated to prompt 02 (forge generation quality). Captured as-is per gate doctrine; gate-after must be no worse.diff --git a/prompts/roadmap/_generated/03/gate-before.txt b/prompts/roadmap/_generated/03/gate-before.txtindex f1f46b566..54aed484e 100644--- a/prompts/roadmap/_generated/03/gate-before.txt+++ b/prompts/roadmap/_generated/03/gate-before.txt@@ -1,36 +1,108 @@-> [email protected] typecheck-> tsc -p jsconfig.json---> [email protected] test-> vitest run && playwright test--- RUN v4.1.7 /workspaces/three.ws-- ❯ tests/api/x402-spec.test.js (23 tests | 23 skipped) 78772ms- ❯ tests/forge-humanoid.test.js (31 tests | 1 failed) 610ms- × returns a non-humanoid verdict for empty input, never throws 86ms-stderr | tests/auto-rig-completion.test.js > 6a — cron recovers an open job from its stored result_glb_url > finalizes via the stored URL and never re-polls the provider-[auto-rig-sweep] job error { jobId: 'job-a', error: 'Invalid IP address: undefined' }-- ❯ tests/auto-rig-completion.test.js (5 tests | 3 failed) 693ms- × finalizes via the stored URL and never re-polls the provider 466ms- × lets exactly one of two concurrent finalizes materialize the avatar 72ms- × a thrown winner releases the claim to a cron-selectable status (not done, not wedged) 106ms- ❯ tests/branding.test.js (4 tests | 4 failed) 99729ms- × no "Avaturn" in user-facing files 97652ms- × no "Character Studio" in user-facing files 564ms- × no "Ready Player Me" in user-facing files 1097ms- × no "RPM" referring to Ready Player Me (heuristic: near avatar/selfie) 414ms- ❯ tests/metering.test.js (11 tests | 1 failed) 2595ms- × issues a MeterUsage command with the product code, dimension, and idempotency allocation 2515ms- ❯ tests/build-asset-paths.test.js (5 tests | 1 failed) 71ms- × serves /style.css from dist root 49ms- ❯ tests/api/agent-memory.test.js (22 tests | 1 failed) 201ms- × truncates content longer than 10,000 characters 52ms- ❯ tests/api/x402-discovery-parity.test.js (4 tests | 3 failed) 616332ms- × lists every paid /api/x402/* endpoint (no silent drift) 257172ms- × catalogs both hosted MCP servers with their own identities 199214ms- × every cataloged x402 resource carries a price and at least one accept 159682ms+> [email protected] gate+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens+++> [email protected] test:gate+> node scripts/test-gate.mjs++[test-gate] running 7 critical-path test files…++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 7 passed (7)+ Tests 83 passed (83)+ Start at 00:54:22+ Duration 3.66s (transform 3.57s, setup 0ms, import 10.11s, tests 3.76s, environment 1ms)++[test-gate] ✓ all critical-path tests passed++> [email protected] test:gate-3d+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js+++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 4 passed (4)+ Tests 244 passed (244)+ Start at 00:54:29+ Duration 2.03s (transform 682ms, setup 0ms, import 2.26s, tests 1.24s, environment 1ms)+++> [email protected] audit:mcp+> node scripts/audit-mcp-manifests.mjs++[audit:mcp] 16 MCP manifests consistent++> [email protected] audit:mcp-golden+> node scripts/audit-mcp-golden.mjs++[audit:mcp-golden] api/_mcp3d/tools/spatial.js: tool ADDED: validate_spatial_response++[audit:mcp-golden] 1 contract change(s) vs golden fixture.+ If every change above is INTENTIONAL (reviewed as a public-contract change),+ refresh the fixture: node scripts/audit-mcp-golden.mjs --update+=== npm run audit:routes ===++> [email protected] audit:routes+> node scripts/verify-routes.mjs++Route verify — 294 catalog pages, 1058 main routes, 1 post-filesystem routes.+ modeled dist files: 1510 · canonical-covered: 294 · literal page routes checked for shadows: 443+ filesystem boundary (handle:filesystem) present: yes++ℹ 1 advisory note(s):+ TRAILSLASH /payments/ → notfound (lands on designed 404)++✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.++=== npm run audit:handlers ===++> [email protected] audit:handlers+> node scripts/audit-empty-handlers.mjs++✓ audit-empty-handlers: all API handlers export a body (1579 checked)++=== npm run audit:pages ===++> [email protected] audit:pages+> node scripts/audit-page-index.mjs++Route audit: 140 auditable page routes, 294 documented in pages.json.+✓ Every auditable page route is documented.++ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.++=== npm run audit:hidden-guard ===++> [email protected] audit:hidden-guard+> node scripts/audit-hidden-guard.mjs++✓ audit-hidden-guard: all 259 pages resolve the [hidden] guard++=== npm run audit:x402-catalog ===++> [email protected] audit:x402-catalog+> node scripts/audit-x402-catalog.mjs++✓ audit-x402-catalog: all 65 x402 endpoints are documented++=== npm run audit:tokens ===+> [email protected] audit:tokens+> node scripts/audit-token-drift.mjs+++✗ design-token drift increased: 5 hardcoded token-hexes (baseline 0).++ pages/bnb.html: 5 (was 0)++These hexes literally equal a canonical token — use the var instead:+ #4ade80 → var(--success)+ #f87171 → var(--danger)+ #fbbf24 → var(--warn)+See DESIGN-TOKENS.md. If a page deliberately re-themes a token, define the+token locally (a theme layer) rather than hardcoding the raw hex.++diff --git a/prompts/roadmap/_generated/06/gate-before.txt b/prompts/roadmap/_generated/06/gate-before.txtnew file mode 100644index 000000000..42f9d554b--- /dev/null+++ b/prompts/roadmap/_generated/06/gate-before.txt@@ -0,0 +1,84 @@++> [email protected] gate+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens+++> [email protected] test:gate+> node scripts/test-gate.mjs++[test-gate] running 7 critical-path test files…++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 7 passed (7)+ Tests 83 passed (83)+ Start at 00:47:29+ Duration 2.99s (transform 2.12s, setup 0ms, import 4.11s, tests 2.85s, environment 2ms)++[test-gate] ✓ all critical-path tests passed++> [email protected] test:gate-3d+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js+++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 4 passed (4)+ Tests 244 passed (244)+ Start at 00:47:33+ Duration 665ms (transform 286ms, setup 0ms, import 805ms, tests 370ms, environment 3ms)+++> [email protected] audit:mcp+> node scripts/audit-mcp-manifests.mjs++[audit:mcp] 16 MCP manifests consistent++> [email protected] audit:mcp-golden+> node scripts/audit-mcp-golden.mjs++[audit:mcp-golden] 223 hosted MCP tool contracts match the golden fixture++> [email protected] audit:routes+> node scripts/verify-routes.mjs++Route verify — 293 catalog pages, 1058 main routes, 1 post-filesystem routes.+ modeled dist files: 1505 · canonical-covered: 293 · literal page routes checked for shadows: 443+ filesystem boundary (handle:filesystem) present: yes++ℹ 1 advisory note(s):+ TRAILSLASH /payments/ → notfound (lands on designed 404)++✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.++> [email protected] audit:handlers+> node scripts/audit-empty-handlers.mjs++✓ audit-empty-handlers: all API handlers export a body (1571 checked)++> [email protected] audit:pages+> node scripts/audit-page-index.mjs++Route audit: 140 auditable page routes, 293 documented in pages.json.+✓ Every auditable page route is documented.++ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.++> [email protected] audit:hidden-guard+> node scripts/audit-hidden-guard.mjs++✓ audit-hidden-guard: all 258 pages resolve the [hidden] guard++> [email protected] audit:x402-catalog+> node scripts/audit-x402-catalog.mjs+++✗ 1 x402 endpoint(s) missing from docs/x402-endpoints.md:++ /api/x402/embody++Every api/x402/*.js endpoint must be listed in the catalog (docs/x402-endpoints.md).+Add a row with its slug, default price, and what it returns — see the existing tables.+diff --git a/prompts/store-submissions/_generated/spatial-mcp/README.md b/prompts/store-submissions/_generated/spatial-mcp/README.mdnew file mode 100644index 000000000..626014d97--- /dev/null+++ b/prompts/store-submissions/_generated/spatial-mcp/README.md@@ -0,0 +1,34 @@+# Prompt 20 — Spatial MCP standard · evidence++Open spec + reference renderer + conformance validator + adopting tools. Coin-clean, reusable across both stores.++## Deliverables++| Piece | Path |+|---|---|+| Spec (v0.1, CC0) | `specs/SPATIAL_MCP.md` |+| Validator + builder (pure core) | `api/_lib/spatial-mcp.js` |+| Validator MCP tool | `validate_spatial_response` — `api/_mcp3d/tools/spatial.js` (free, read-only), registered in `api/_mcp3d/catalog.js` |+| Reference renderer | `public/spatial-mcp/spatial-renderer.js` + demo `public/spatial-mcp/index.html` → `/spatial-mcp` |+| Adoption doc | `docs/spatial-mcp.md` |+| Tests | `tests/spatial-mcp.test.js` (22 cases) |++## Tools emitting conformant artifacts++Under `structuredContent.spatial`:+- Free 3D Studio (`/api/mcp-studio`): `forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`, `refine_model`.+- Paid 3D Studio (`/api/mcp-3d`): `preview_3d`.++## Verification (all run)++- **All 3D tools emit conformant artifacts** — `tests/spatial-mcp.test.js` drives the real free-studio dispatcher (mocked `/api/forge`) for all six tools and validates the emitted `structuredContent.spatial`. 22/22 green.+- **Portability** — `artifact-foreign-transformed.json` is a foreign `{ model_url, thumbnail, name }` result run through a 6-line adapter; it validates `true` and the reference renderer renders it beside a native artifact at `/spatial-mcp`.+- **Rejects malformed payloads with actionable messages** — `validate-rejected.json`: a payload missing `spatialMcpVersion` with an `http` glbUrl returns `valid:false` and 2 errors naming `spatialMcpVersion` and `scene.glbUrl` + the fix.+- **Coin-clean** — the spec, renderer, and validator contain no payment/coin surface (test `carries no payment/coin surface`; grep of `api/_lib/spatial-mcp.js`, `public/spatial-mcp/*`, `specs/SPATIAL_MCP.md` for `x402|wallet|usdc|token|coin|price|mint` is clean).++## Files here++- `artifact-native.json` — a conformant artifact as three.ws emits it.+- `artifact-foreign-transformed.json` — a foreign result transformed to conformant (portability proof).+- `validate-conformant.json` — validator output for a good artifact (`valid:true`).+- `validate-rejected.json` — validator output for a broken artifact (`valid:false` + actionable errors).diff --git a/prompts/store-submissions/_generated/spatial-mcp/artifact-foreign-transformed.json b/prompts/store-submissions/_generated/spatial-mcp/artifact-foreign-transformed.jsonnew file mode 100644index 000000000..1fa2c4c9f--- /dev/null+++ b/prompts/store-submissions/_generated/spatial-mcp/artifact-foreign-transformed.json@@ -0,0 +1,18 @@+{+ "spatialMcpVersion": "0.1",+ "kind": "model",+ "scene": {+ "glbUrl": "https://cdn.jsdelivr.net/npm/[email protected]/examples/models/gltf/DamagedHelmet/glTF-Binary/DamagedHelmet.glb",+ "format": "glb"+ },+ "camera": {+ "autoRotate": true+ },+ "affordances": {+ "orbit": true,+ "zoom": true+ },+ "meta": {+ "title": "A helmet from another server"+ }+}\ No newline at end of filediff --git a/prompts/store-submissions/_generated/spatial-mcp/artifact-native.json b/prompts/store-submissions/_generated/spatial-mcp/artifact-native.jsonnew file mode 100644index 000000000..df48867bd--- /dev/null+++ b/prompts/store-submissions/_generated/spatial-mcp/artifact-native.json@@ -0,0 +1,27 @@+{+ "spatialMcpVersion": "0.1",+ "kind": "model",+ "scene": {+ "glbUrl": "https://three.ws/cdn/creations/demo.glb",+ "format": "glb"+ },+ "camera": {+ "autoRotate": true+ },+ "environment": {+ "image": "neutral",+ "exposure": 1,+ "shadowIntensity": 1+ },+ "affordances": {+ "orbit": true,+ "zoom": true,+ "fullscreen": true,+ "download": true+ },+ "meta": {+ "prompt": "a battle-worn sci-fi helmet",+ "title": "Damaged helmet",+ "viewerUrl": "https://three.ws/viewer?src=https%3A%2F%2Fthree.ws%2Fcdn%2Fcreations%2Fdemo.glb"+ }+}\ No newline at end of filediff --git a/prompts/store-submissions/_generated/spatial-mcp/validate-conformant.json b/prompts/store-submissions/_generated/spatial-mcp/validate-conformant.jsonnew file mode 100644index 000000000..11484a422--- /dev/null+++ b/prompts/store-submissions/_generated/spatial-mcp/validate-conformant.json@@ -0,0 +1,6 @@+{+ "valid": true,+ "version": "0.1",+ "errors": [],+ "warnings": []+}\ No newline at end of filediff --git a/prompts/store-submissions/_generated/spatial-mcp/validate-rejected.json b/prompts/store-submissions/_generated/spatial-mcp/validate-rejected.jsonnew file mode 100644index 000000000..5005eee24--- /dev/null+++ b/prompts/store-submissions/_generated/spatial-mcp/validate-rejected.json@@ -0,0 +1,24 @@+{+ "valid": false,+ "version": null,+ "errors": [+ {+ "path": "spatialMcpVersion",+ "message": "required — set it to \"0.1\""+ },+ {+ "path": "scene.glbUrl",+ "message": "required — must be an https URL to a .glb asset"+ }+ ],+ "warnings": [+ {+ "path": "scene.format",+ "message": "recommended — set to \"glb\""+ },+ {+ "path": "camera",+ "message": "recommended — include `{ autoRotate: true }` so hosts frame the model"+ }+ ]+}\ No newline at end of filediff --git a/public/changelog.json b/public/changelog.jsonindex a4ea531d9..d09332f78 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,153 @@{- "generated_at": "2026-07-08T00:08:53.648Z",+ "generated_at": "2026-07-08T00:51:31.607Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "Blockchain TVL by Chain",+ "summary": "A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.",+ "link": "/chains",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "Crypto Categories by Market Cap",+ "summary": "Every crypto sector ranked by market cap — smart contract platforms, AI agents, memecoins, DeFi, gaming, and more — with 24h change, volume, and the top coins in each. See which narratives are leading the market right now.",+ "link": "/categories",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "Crypto Currency Converter",+ "summary": "Convert between any cryptocurrency and major world fiat currencies at live market rates — crypto to crypto, crypto to fiat, and back. Type an amount, pick both sides, and share the result via URL.",+ "link": "/converter",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "Crypto Derivatives & Perpetual Futures",+ "summary": "Live perpetual-futures markets across exchanges — price, 24h change, funding rate, open interest, and volume for every major contract. Filter by underlying index (BTC, ETH, SOL) and sort by any column.",+ "link": "/derivatives",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "Crypto Token Screener",+ "summary": "Screen the top 250 cryptocurrencies with live filters — search by name or symbol, isolate gainers or losers, and set minimum market cap and 24h volume thresholds. Every column sorts and every row links to a full coin detail page.",+ "link": "/screener",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "DeFi TVL & Top Protocols",+ "summary": "Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.",+ "link": "/defi",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "glTF / GLB Viewer",+ "summary": "Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.",+ "link": "/viewer",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "Stablecoins Market Cap & Peg Health",+ "summary": "Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.",+ "link": "/stablecoins",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "Top Crypto Exchanges",+ "summary": "The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.",+ "link": "/exchanges",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "<agent-3d> talks out of the box with brain=\"free\"",+ "summary": "Any embedded avatar can now hold a real conversation with zero setup: add brain=\"free\" to an <agent-3d> tag and it routes through three.ws's host-paid free-tier proxy (OpenRouter, Groq, or NVIDIA NIM, whichever is healthy) — no API key, no backend code, no per-token cost to the embedder. Previously the brain attribute required an exact model id and defaulted to a silent avatar; brain=\"free\" is now a supported alias, and it's honored on both the src= (bare GLB) and body= (ad-hoc agent) embed paths, which is where this fell through before.",+ "link": "/docs/embedding",+ "tags": [+ "feature",+ "sdk"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "Markets goes deep — Screener, Categories, Exchanges, Derivatives, Converter, DeFi, Chains, Stablecoins",+ "summary": "Eight new tools join the Markets suite, all live data and all free. Screener filters the top 250 coins by market cap, volume, and 24h move. Categories ranks every crypto sector so you can see which narrative leads. Exchanges ranks venues by trust score and volume. Derivatives shows perpetual-futures funding, open interest, and volume. Converter turns any crypto into any major fiat at live rates. And a DeFi trio — DeFi TVL by protocol, Chains by total value locked, and Stablecoins with peg health — brings on-chain liquidity into view via DeFiLlama. Every one is cross-linked from the markets table.",+ "link": "/screener",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "New shared DeFi utility library: one source of truth for chain and token constants across EVM and Solana",+ "summary": "Added @three-ws/defi-utils, a zero-dependency internal package with chain IDs, native-token symbols, common token addresses (including SPA and USDs on Arbitrum), and minimal ERC-20 ABI fragments for nine EVM chains, plus a Solana extension (SOL/USDC/$THREE mint resolution and base58 address validation). Also ships address and amount validators and USD/percent/token-amount formatters. It replaces ad hoc constant duplication across the codebase's API handlers and frontend modules going forward.",+ "link": null,+ "tags": [+ "sdk"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "Paid API endpoints now stay up through a cache-provider outage",+ "summary": "Hardened the pay-per-call x402 API surface — every /api/x402/* and /api/okx/3d/* endpoint — so it degrades gracefully instead of failing when the shared Redis cache is unreachable. Previously a missing cache configuration could take these paid endpoints offline; they now serve normally on a safe per-instance fallback, with on-chain payment safety unchanged (each payment authorization is still single-use, so no double-charge is possible).",+ "link": null,+ "tags": [+ "fix",+ "infra"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "The three.ws crypto API now has a real free tier",+ "summary": "Any unauthenticated call to the unified /api/v1/x API (CoinGecko, DefiLlama, Jupiter Solana prices/quotes/search) now gets real data with zero setup, up to a per-endpoint quota — no wallet, no key, no signup. curl https://three.ws/api/v1/x/coingecko/price?ids=solana just works. Every response carries rate-limit headers so an agent can see exactly how much free budget is left; once it's used up, the same URL falls through to pay-per-call USDC (x402) or a three.ws API key instead of dead-ending.",+ "link": "/docs/api-reference",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-07","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex a885e5ebe..e233ea6c9 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,118 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Blockchain TVL by Chain</title>+ <link>https://three.ws/chains</link>+ <guid isPermaLink="false">2026-07-08:Blockchain TVL by Chain</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.</description>+ </item>+ <item>+ <title>Crypto Categories by Market Cap</title>+ <link>https://three.ws/categories</link>+ <guid isPermaLink="false">2026-07-08:Crypto Categories by Market Cap</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Every crypto sector ranked by market cap — smart contract platforms, AI agents, memecoins, DeFi, gaming, and more — with 24h change, volume, and the top coins in each. See which narratives are leading the market right now.</description>+ </item>+ <item>+ <title>Crypto Currency Converter</title>+ <link>https://three.ws/converter</link>+ <guid isPermaLink="false">2026-07-08:Crypto Currency Converter</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Convert between any cryptocurrency and major world fiat currencies at live market rates — crypto to crypto, crypto to fiat, and back. Type an amount, pick both sides, and share the result via URL.</description>+ </item>+ <item>+ <title>Crypto Derivatives & Perpetual Futures</title>+ <link>https://three.ws/derivatives</link>+ <guid isPermaLink="false">2026-07-08:Crypto Derivatives & Perpetual Futures</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Live perpetual-futures markets across exchanges — price, 24h change, funding rate, open interest, and volume for every major contract. Filter by underlying index (BTC, ETH, SOL) and sort by any column.</description>+ </item>+ <item>+ <title>Crypto Token Screener</title>+ <link>https://three.ws/screener</link>+ <guid isPermaLink="false">2026-07-08:Crypto Token Screener</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Screen the top 250 cryptocurrencies with live filters — search by name or symbol, isolate gainers or losers, and set minimum market cap and 24h volume thresholds. Every column sorts and every row links to a full coin detail page.</description>+ </item>+ <item>+ <title>DeFi TVL & Top Protocols</title>+ <link>https://three.ws/defi</link>+ <guid isPermaLink="false">2026-07-08:DeFi TVL & Top Protocols</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.</description>+ </item>+ <item>+ <title>glTF / GLB Viewer</title>+ <link>https://three.ws/viewer</link>+ <guid isPermaLink="false">2026-07-08:glTF / GLB Viewer</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.</description>+ </item>+ <item>+ <title>Stablecoins Market Cap & Peg Health</title>+ <link>https://three.ws/stablecoins</link>+ <guid isPermaLink="false">2026-07-08:Stablecoins Market Cap & Peg Health</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.</description>+ </item>+ <item>+ <title>Top Crypto Exchanges</title>+ <link>https://three.ws/exchanges</link>+ <guid isPermaLink="false">2026-07-08:Top Crypto Exchanges</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.</description>+ </item>+ <item>+ <title><agent-3d> talks out of the box with brain="free"</title>+ <link>https://three.ws/docs/embedding</link>+ <guid isPermaLink="false">2026-07-08:<agent-3d> talks out of the box with brain="free"</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Any embedded avatar can now hold a real conversation with zero setup: add brain="free" to an <agent-3d> tag and it routes through three.ws's host-paid free-tier proxy (OpenRouter, Groq, or NVIDIA NIM, whichever is healthy) — no API key, no backend code, no per-token cost to the embedder. Previously the brain attribute required an exact model id and defaulted to a silent avatar; brain="free" is now a supported alias, and it's honored on both the src= (bare GLB) and body= (ad-hoc agent) embed paths, which is where this fell through before.</description>+ </item>+ <item>+ <title>Markets goes deep — Screener, Categories, Exchanges, Derivatives, Converter, DeFi, Chains, Stablecoins</title>+ <link>https://three.ws/screener</link>+ <guid isPermaLink="false">2026-07-08:Markets goes deep — Screener, Categories, Exchanges, Derivatives, Converter, DeFi, Chains, Stablecoins</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Eight new tools join the Markets suite, all live data and all free. Screener filters the top 250 coins by market cap, volume, and 24h move. Categories ranks every crypto sector so you can see which narrative leads. Exchanges ranks venues by trust score and volume. Derivatives shows perpetual-futures funding, open interest, and volume. Converter turns any crypto into any major fiat at live rates. And a DeFi trio — DeFi TVL by protocol, Chains by total value locked, and Stablecoins with peg health — brings on-chain liquidity into view via DeFiLlama. Every one is cross-linked from the markets table.</description>+ </item>+ <item>+ <title>New shared DeFi utility library: one source of truth for chain and token constants across EVM and Solana</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-08:New shared DeFi utility library: one source of truth for chain and token constants across EVM and Solana</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>sdk</category>+ <description>Added @three-ws/defi-utils, a zero-dependency internal package with chain IDs, native-token symbols, common token addresses (including SPA and USDs on Arbitrum), and minimal ERC-20 ABI fragments for nine EVM chains, plus a Solana extension (SOL/USDC/$THREE mint resolution and base58 address validation). Also ships address and amount validators and USD/percent/token-amount formatters. It replaces ad hoc constant duplication across the codebase's API handlers and frontend modules going forward.</description>+ </item>+ <item>+ <title>Paid API endpoints now stay up through a cache-provider outage</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-08:Paid API endpoints now stay up through a cache-provider outage</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Hardened the pay-per-call x402 API surface — every /api/x402/* and /api/okx/3d/* endpoint — so it degrades gracefully instead of failing when the shared Redis cache is unreachable. Previously a missing cache configuration could take these paid endpoints offline; they now serve normally on a safe per-instance fallback, with on-chain payment safety unchanged (each payment authorization is still single-use, so no double-charge is possible).</description>+ </item>+ <item>+ <title>The three.ws crypto API now has a real free tier</title>+ <link>https://three.ws/docs/api-reference</link>+ <guid isPermaLink="false">2026-07-08:The three.ws crypto API now has a real free tier</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Any unauthenticated call to the unified /api/v1/x API (CoinGecko, DefiLlama, Jupiter Solana prices/quotes/search) now gets real data with zero setup, up to a per-endpoint quota — no wallet, no key, no signup. curl https://three.ws/api/v1/x/coingecko/price?ids=solana just works. Every response carries rate-limit headers so an agent can see exactly how much free budget is left; once it's used up, the same URL falls through to pay-per-call USDC (x402) or a three.ws API key instead of dead-ending.</description>+ </item><item><title>3D API</title><link>https://three.ws/3d</link>diff --git a/public/features.json b/public/features.jsonindex c1f8b3bc3..9bd689253 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T00:08:53.636Z",+ "generated_at": "2026-07-08T00:51:31.590Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -819,6 +819,16 @@"tags": [],"showcase": false},+ {+ "path": "/viewer",+ "title": "glTF / GLB Viewer",+ "description": "Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/playground","title": "Playground",@@ -1426,6 +1436,86 @@"tags": [],"showcase": false},+ {+ "path": "/screener",+ "title": "Crypto Token Screener",+ "description": "Screen the top 250 cryptocurrencies with live filters — search by name or symbol, isolate gainers or losers, and set minimum market cap and 24h volume thresholds. Every column sorts and every row links to a full coin detail page.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/categories",+ "title": "Crypto Categories by Market Cap",+ "description": "Every crypto sector ranked by market cap — smart contract platforms, AI agents, memecoins, DeFi, gaming, and more — with 24h change, volume, and the top coins in each. See which narratives are leading the market right now.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/exchanges",+ "title": "Top Crypto Exchanges",+ "description": "The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/derivatives",+ "title": "Crypto Derivatives & Perpetual Futures",+ "description": "Live perpetual-futures markets across exchanges — price, 24h change, funding rate, open interest, and volume for every major contract. Filter by underlying index (BTC, ETH, SOL) and sort by any column.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/converter",+ "title": "Crypto Currency Converter",+ "description": "Convert between any cryptocurrency and major world fiat currencies at live market rates — crypto to crypto, crypto to fiat, and back. Type an amount, pick both sides, and share the result via URL.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/defi",+ "title": "DeFi TVL & Top Protocols",+ "description": "Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/chains",+ "title": "Blockchain TVL by Chain",+ "description": "A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/stablecoins",+ "title": "Stablecoins Market Cap & Peg Health",+ "description": "Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/constellation","title": "watsonx Constellation",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 7465e4f93..3a8dabbd9 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -500,6 +500,12 @@ URL: https://three.ws/avatar-artifactStandalone Three.js viewer for avatar artifacts — embeddable and shareable without any wrapper page.+### glTF / GLB Viewer++URL: https://three.ws/viewer++Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.+### PlaygroundURL: https://three.ws/playground@@ -867,6 +873,54 @@ URL: https://three.ws/compareCompare cryptocurrencies head to head — overlay normalized price performance and line up market cap, volume, FDV, supply, and all-time-high stats for up to four coins at once. The selection is saved to the URL so any matchup is shareable.+### Crypto Token Screener++URL: https://three.ws/screener++Screen the top 250 cryptocurrencies with live filters — search by name or symbol, isolate gainers or losers, and set minimum market cap and 24h volume thresholds. Every column sorts and every row links to a full coin detail page.++### Crypto Categories by Market Cap++URL: https://three.ws/categories++Every crypto sector ranked by market cap — smart contract platforms, AI agents, memecoins, DeFi, gaming, and more — with 24h change, volume, and the top coins in each. See which narratives are leading the market right now.++### Top Crypto Exchanges++URL: https://three.ws/exchanges++The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.++### Crypto Derivatives & Perpetual Futures++URL: https://three.ws/derivatives++Live perpetual-futures markets across exchanges — price, 24h change, funding rate, open interest, and volume for every major contract. Filter by underlying index (BTC, ETH, SOL) and sort by any column.++### Crypto Currency Converter++URL: https://three.ws/converter++Convert between any cryptocurrency and major world fiat currencies at live market rates — crypto to crypto, crypto to fiat, and back. Type an amount, pick both sides, and share the result via URL.++### DeFi TVL & Top Protocols++URL: https://three.ws/defi++Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.++### Blockchain TVL by Chain++URL: https://three.ws/chains++A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.++### Stablecoins Market Cap & Peg Health++URL: https://three.ws/stablecoins++Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.+### watsonx ConstellationURL: https://three.ws/constellationdiff --git a/public/llms.txt b/public/llms.txtindex 74fbbf2d7..755ed801b 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -97,6 +97,7 @@ Experimental features actively shipping. Expect fast iteration.- [Lipsync (TTS)](https://three.ws/lipsync): Type text, stream it through the avatar's voice, and the mouth animates in real time via wawa-lipsync viseme detection.- [Lipsync (Mic)](https://three.ws/lipsync/mic): Feed live mic audio through the viseme analyser and watch the avatar's mouth track your voice in real time.- [Avatar Artifact](https://three.ws/avatar-artifact): Standalone Three.js viewer for avatar artifacts — embeddable and shareable without any wrapper page.+- [glTF / GLB Viewer](https://three.ws/viewer): Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.- [Playground](https://three.ws/playground): Sandbox for experimenting with agents, prompts, and 3D scenes.- [Labs Showcase](https://three.ws/labs): A curated gallery of three.ws's most powerful — and most hidden — features. Find and try things you didn't know existed.- [Walk Leaderboard](https://three.ws/walk-leaderboard): Global leaderboard for the walking avatar — distance walked, sites visited, and time, ranked daily, weekly, and all-time.@@ -160,6 +161,14 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Crypto Fear & Greed Index](https://three.ws/fear-greed): The Crypto Fear & Greed Index — live market sentiment from 0 (Extreme Fear) to 100 (Extreme Greed), shown on a gauge with a week-over-week delta, a full interactive history chart, and a labelled scale explaining what each reading means.- [Ethereum Gas Tracker](https://three.ws/gas): Live Ethereum gas fees straight from the chain — slow, standard, and fast tiers in gwei with USD cost estimates for transfers, token sends, DEX swaps, and NFT mints. Real on-chain fee history, refreshed automatically, no API key required.- [Compare Crypto Side by Side](https://three.ws/compare): Compare cryptocurrencies head to head — overlay normalized price performance and line up market cap, volume, FDV, supply, and all-time-high stats for up to four coins at once. The selection is saved to the URL so any matchup is shareable.+- [Crypto Token Screener](https://three.ws/screener): Screen the top 250 cryptocurrencies with live filters — search by name or symbol, isolate gainers or losers, and set minimum market cap and 24h volume thresholds. Every column sorts and every row links to a full coin detail page.+- [Crypto Categories by Market Cap](https://three.ws/categories): Every crypto sector ranked by market cap — smart contract platforms, AI agents, memecoins, DeFi, gaming, and more — with 24h change, volume, and the top coins in each. See which narratives are leading the market right now.+- [Top Crypto Exchanges](https://three.ws/exchanges): The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.+- [Crypto Derivatives & Perpetual Futures](https://three.ws/derivatives): Live perpetual-futures markets across exchanges — price, 24h change, funding rate, open interest, and volume for every major contract. Filter by underlying index (BTC, ETH, SOL) and sort by any column.+- [Crypto Currency Converter](https://three.ws/converter): Convert between any cryptocurrency and major world fiat currencies at live market rates — crypto to crypto, crypto to fiat, and back. Type an amount, pick both sides, and share the result via URL.+- [DeFi TVL & Top Protocols](https://three.ws/defi): Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.+- [Blockchain TVL by Chain](https://three.ws/chains): A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.+- [Stablecoins Market Cap & Peg Health](https://three.ws/stablecoins): Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.- [watsonx Constellation](https://three.ws/constellation): Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.- [x402 Bazaar](https://three.ws/bazaar): Search and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click.- [x402 Live Demo (IBM × three.ws)](https://three.ws/ibm/x402-demo): A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.diff --git a/public/nav-data.js b/public/nav-data.jsindex 7fd99713c..457430fb2 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -332,6 +332,46 @@ export const NAV_GROUPS = [href: '/compare',desc: 'Put up to four coins head to head — overlay performance and line up the stats',},+ {+ title: 'Screener',+ href: '/screener',+ desc: 'Filter the top 250 coins by market cap, volume, and 24h move — find movers fast',+ },+ {+ title: 'Categories',+ href: '/categories',+ desc: 'Every crypto sector ranked by market cap — smart contracts, AI, memes, and more',+ },+ {+ title: 'Exchanges',+ href: '/exchanges',+ desc: 'Top crypto exchanges ranked by trust score and 24h volume',+ },+ {+ title: 'Derivatives',+ href: '/derivatives',+ desc: 'Live perpetual futures — funding rates, open interest, and volume by market',+ },+ {+ title: 'Converter',+ href: '/converter',+ desc: 'Convert between any crypto and major fiat currencies at live rates',+ },+ {+ title: 'DeFi TVL',+ href: '/defi',+ desc: 'Total value locked across DeFi — top protocols by TVL, live from DeFiLlama',+ },+ {+ title: 'Chains',+ href: '/chains',+ desc: 'Blockchain TVL leaderboard — value locked per chain with dominance share',+ },+ {+ title: 'Stablecoins',+ href: '/stablecoins',+ desc: 'Stablecoin market caps and peg health across every major issuer',+ },{title: 'Coin Intelligence',href: '/coin-intel',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 369a92b2b..b5d7d854f 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 392 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 401 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 392 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 401 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -632,7 +632,7 @@<section class="sm-section" id="labs"><header>- <h2>Labs<span class="sm-count" data-count>8</span></h2>+ <h2>Labs<span class="sm-count" data-count>9</span></h2><p class="sm-section-desc">Experimental features actively shipping. Expect fast iteration.</p></header><ul class="sm-list">@@ -671,6 +671,13 @@<span class="sm-desc">Standalone Three.js viewer for avatar artifacts — embeddable and shareable without any wrapper page.</span></a></li>+ <li>+ <a href="/viewer">+ <span class="sm-title">glTF / GLB Viewer</span>+ <span class="sm-path">/viewer</span>+ <span class="sm-desc">Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.</span>+ </a>+ </li><li><a href="/playground"><span class="sm-title">Playground</span>@@ -697,7 +704,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>86</span></h2>+ <h2>Crypto<span class="sm-count" data-count>94</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -1100,6 +1107,62 @@<span class="sm-desc">Compare cryptocurrencies head to head — overlay normalized price performance and line up market cap, volume, FDV, supply, and all-time-high stats for up to four coins at once. The selection is saved to the URL so any matchup is shareable.</span></a></li>+ <li>+ <a href="/screener">+ <span class="sm-title">Crypto Token Screener</span>+ <span class="sm-path">/screener</span>+ <span class="sm-desc">Screen the top 250 cryptocurrencies with live filters — search by name or symbol, isolate gainers or losers, and set minimum market cap and 24h volume thresholds. Every column sorts and every row links to a full coin detail page.</span>+ </a>+ </li>+ <li>+ <a href="/categories">+ <span class="sm-title">Crypto Categories by Market Cap</span>+ <span class="sm-path">/categories</span>+ <span class="sm-desc">Every crypto sector ranked by market cap — smart contract platforms, AI agents, memecoins, DeFi, gaming, and more — with 24h change, volume, and the top coins in each. See which narratives are leading the market right now.</span>+ </a>+ </li>+ <li>+ <a href="/exchanges">+ <span class="sm-title">Top Crypto Exchanges</span>+ <span class="sm-path">/exchanges</span>+ <span class="sm-desc">The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.</span>+ </a>+ </li>+ <li>+ <a href="/derivatives">+ <span class="sm-title">Crypto Derivatives & Perpetual Futures</span>+ <span class="sm-path">/derivatives</span>+ <span class="sm-desc">Live perpetual-futures markets across exchanges — price, 24h change, funding rate, open interest, and volume for every major contract. Filter by underlying index (BTC, ETH, SOL) and sort by any column.</span>+ </a>+ </li>+ <li>+ <a href="/converter">+ <span class="sm-title">Crypto Currency Converter</span>+ <span class="sm-path">/converter</span>+ <span class="sm-desc">Convert between any cryptocurrency and major world fiat currencies at live market rates — crypto to crypto, crypto to fiat, and back. Type an amount, pick both sides, and share the result via URL.</span>+ </a>+ </li>+ <li>+ <a href="/defi">+ <span class="sm-title">DeFi TVL & Top Protocols</span>+ <span class="sm-path">/defi</span>+ <span class="sm-desc">Total value locked across decentralized finance, with the top protocols ranked by TVL, their category, chains, and 1-day and 7-day change. Live from DeFiLlama, sortable and filterable by category.</span>+ </a>+ </li>+ <li>+ <a href="/chains">+ <span class="sm-title">Blockchain TVL by Chain</span>+ <span class="sm-path">/chains</span>+ <span class="sm-desc">A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.</span>+ </a>+ </li>+ <li>+ <a href="/stablecoins">+ <span class="sm-title">Stablecoins Market Cap & Peg Health</span>+ <span class="sm-path">/stablecoins</span>+ <span class="sm-desc">Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.</span>+ </a>+ </li><li><a href="/constellation"><span class="sm-title">watsonx Constellation</span>diff --git a/public/spatial-mcp/index.html b/public/spatial-mcp/index.htmlnew file mode 100644index 000000000..eccf6cfd5--- /dev/null+++ b/public/spatial-mcp/index.html@@ -0,0 +1,100 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+<title>Spatial MCP — reference renderer</title>+<meta name="description" content="Reference renderer for the open Spatial MCP artifact shape — 3D as a native conversational MCP response type." />+<script src="/model-viewer-meshopt.js"></script>+<script type="module" src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"></script>+<style>+ :root { color-scheme: dark; --accent:#6ea8fe; }+ * { box-sizing:border-box; }+ html,body { margin:0; min-height:100%; }+ body { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background: radial-gradient(130% 130% at 50% 0%, #14161c 0%, #0b0c10 60%, #08090c 100%); color:#e8eaf0; }+ .page { max-width: 1000px; margin: 0 auto; padding: 32px 20px 64px; }+ h1 { font-size: 22px; margin: 0 0 6px; }+ .lede { color:#9aa3b2; font-size:14px; line-height:1.55; max-width: 62ch; }+ .lede a { color: var(--accent); }+ .grid { display:grid; grid-template-columns: 1fr; gap: 20px; margin-top: 26px; }+ @media (min-width: 760px){ .grid { grid-template-columns: 1fr 1fr; } }+ .card { border:1px solid rgba(255,255,255,0.08); border-radius:14px; overflow:hidden; background: rgba(12,14,19,0.6); }+ .card h2 { font-size:13px; letter-spacing:.02em; text-transform:uppercase; color:#aeb6c4; margin:0; padding:12px 14px; border-bottom:1px solid rgba(255,255,255,0.07); }+ .stage { height: 340px; background: transparent; }+ .spatial-empty { display:flex; align-items:center; justify-content:center; height:100%; color:#9aa3b2; font-size:13px; text-align:center; padding:20px; }+ pre { margin:0; padding:14px; font-size:12px; line-height:1.5; overflow:auto; max-height:340px; color:#cbd3e1; }+ .note { margin-top:24px; font-size:13px; color:#9aa3b2; line-height:1.6; }+ code { color:#dbe9ff; }+</style>+</head>+<body>+<div class="page">+ <h1>Spatial MCP — reference renderer</h1>+ <p class="lede">+ <strong>Spatial MCP</strong> makes a live, interactive 3D scene a first-class MCP tool result, not a URL in text.+ This page is the reference renderer for the open artifact shape. It renders the conformant payload below —+ including one <em>transformed from a different (foreign) tool's output</em> — proving the shape is portable.+ Spec: <a href="/specs/spatial-mcp">SPATIAL_MCP.md</a>.+ </p>++ <div class="grid">+ <div class="card">+ <h2>three.ws forge_free → artifact</h2>+ <div id="stage-native" class="stage"></div>+ </div>+ <div class="card">+ <h2>Foreign tool result → conformant artifact</h2>+ <div id="stage-foreign" class="stage"></div>+ </div>+ </div>++ <div class="card" style="margin-top:20px;">+ <h2>The foreign result, transformed (what the renderer consumes)</h2>+ <pre id="artifact-json"></pre>+ </div>++ <p class="note">+ A third-party MCP server that returns <code>{ url, previewImage }</code> becomes conformant with a tiny adapter —+ see <a href="/docs/spatial-mcp">docs/spatial-mcp</a>. Any renderer that speaks this shape (this one included) then+ displays it. No payment, wallet, or coin surface anywhere in the shape or the renderer.+ </p>+</div>++<script type="module">+ import { renderSpatialArtifact } from './spatial-renderer.js';++ // A real, public demo GLB (three.js sample, https).+ const DEMO_GLB = 'https://cdn.jsdelivr.net/npm/[email protected]/examples/models/gltf/DamagedHelmet/glTF-Binary/DamagedHelmet.glb';++ // 1) A native three.ws artifact (what forge_free's structuredContent.spatial looks like).+ const native = {+ spatialMcpVersion: '0.1',+ kind: 'model',+ scene: { glbUrl: DEMO_GLB, format: 'glb' },+ camera: { autoRotate: true },+ environment: { image: 'neutral', exposure: 1, shadowIntensity: 1 },+ affordances: { orbit: true, zoom: true, fullscreen: true, download: true },+ meta: { title: 'Damaged helmet', prompt: 'a battle-worn sci-fi helmet' },+ };+ renderSpatialArtifact(document.getElementById('stage-native'), native);++ // 2) A FOREIGN tool result in some other server's shape…+ const foreignResult = { model_url: DEMO_GLB, thumbnail: null, name: 'A helmet from another server' };++ // …transformed into a conformant artifact by a 6-line adapter (the portability proof).+ function toSpatialArtifact(foreign) {+ return {+ spatialMcpVersion: '0.1',+ kind: 'model',+ scene: { glbUrl: foreign.model_url, format: 'glb', ...(foreign.thumbnail ? { poster: foreign.thumbnail } : {}) },+ camera: { autoRotate: true },+ affordances: { orbit: true, zoom: true },+ meta: { title: foreign.name },+ };+ }+ const transformed = toSpatialArtifact(foreignResult);+ renderSpatialArtifact(document.getElementById('stage-foreign'), transformed);+ document.getElementById('artifact-json').textContent = JSON.stringify(transformed, null, 2);+</script>+</body>+</html>diff --git a/public/spatial-mcp/spatial-renderer.js b/public/spatial-mcp/spatial-renderer.jsnew file mode 100644index 000000000..e719f5cb4--- /dev/null+++ b/public/spatial-mcp/spatial-renderer.js@@ -0,0 +1,104 @@+// Spatial MCP reference renderer — renders any conformant Spatial MCP artifact.+//+// A small, dependency-light, framework-free renderer that turns a Spatial MCP+// artifact (specs/SPATIAL_MCP.md) into an interactive <model-viewer> scene:+// orbit/zoom, animation playback, an AR button, and graceful fallback for every+// missing optional field. It is the REFERENCE IMPLEMENTATION of the spec — any+// MCP host or third-party app can adopt this shape and use (or reimplement) this+// renderer. Zero payment/wallet/coin surface, so it drops into the free OpenAI+// track unchanged.+//+// Usage:+// import { renderSpatialArtifact } from './spatial-renderer.js';+// renderSpatialArtifact(document.getElementById('mount'), artifact);+//+// It expects the <model-viewer> custom element to be available on the page (load+// @google/model-viewer). It never fetches anything itself beyond the GLB the+// artifact points at, and only ever loads https assets.++function isHttps(u) {+ try {+ return typeof u === 'string' && new URL(u).protocol === 'https:';+ } catch {+ return false;+ }+}++// Minimal structural check mirroring api/_lib/spatial-mcp.js validateSpatialArtifact+// — enough to render safely. The full validator is the authority; this keeps the+// renderer standalone (no build-time import) while refusing an unusable payload.+export function canRenderSpatialArtifact(artifact) {+ return (+ artifact &&+ typeof artifact === 'object' &&+ typeof artifact.spatialMcpVersion === 'string' &&+ artifact.scene &&+ isHttps(artifact.scene.glbUrl)+ );+}++/**+ * Render a Spatial MCP artifact into `mount`. Returns the created <model-viewer>+ * element (or null when the artifact can't be rendered — the mount then shows a+ * designed fallback message instead of a blank frame).+ */+export function renderSpatialArtifact(mount, artifact) {+ if (!mount) return null;+ mount.textContent = '';++ if (!canRenderSpatialArtifact(artifact)) {+ const msg = document.createElement('div');+ msg.className = 'spatial-empty';+ msg.textContent = 'No renderable 3D scene in this payload.';+ mount.appendChild(msg);+ return null;+ }++ const scene = artifact.scene;+ const camera = artifact.camera || {};+ const env = artifact.environment || {};+ const affordances = artifact.affordances || {};+ const ar = artifact.ar || {};++ const mv = document.createElement('model-viewer');+ mv.setAttribute('src', scene.glbUrl);+ mv.setAttribute('alt', scene.alt || (artifact.meta && artifact.meta.title) || 'Interactive 3D model');+ if (isHttps(scene.poster)) mv.setAttribute('poster', scene.poster);++ // Camera / interaction — honor affordances, default to a framed, orbitable view.+ if (affordances.orbit !== false) mv.setAttribute('camera-controls', '');+ if (camera.autoRotate !== false) mv.setAttribute('auto-rotate', '');+ if (typeof camera.orbit === 'string') mv.setAttribute('camera-orbit', camera.orbit);+ if (typeof camera.fieldOfView === 'string') mv.setAttribute('field-of-view', camera.fieldOfView);+ if (affordances.zoom === false) mv.setAttribute('disable-zoom', '');+ mv.setAttribute('touch-action', 'pan-y');+ mv.setAttribute('interaction-prompt', 'none');++ // Environment / lighting.+ mv.setAttribute('environment-image', typeof env.image === 'string' ? env.image : 'neutral');+ if (typeof env.exposure === 'number') mv.setAttribute('exposure', String(env.exposure));+ if (typeof env.shadowIntensity === 'number') mv.setAttribute('shadow-intensity', String(env.shadowIntensity));+ mv.setAttribute('tone-mapping', 'aces');++ // Animation — autoplay when the artifact declares an animation block.+ if (artifact.animation) {+ if (artifact.animation.autoplay !== false) mv.setAttribute('autoplay', '');+ if (Array.isArray(artifact.animation.clips) && artifact.animation.clips.length) {+ mv.setAttribute('animation-name', String(artifact.animation.clips[0]));+ }+ }++ // AR handoff — enable AR when the artifact declares an AR asset/link, or always+ // offer WebXR/Scene-Viewer/Quick-Look from the GLB itself as a graceful default.+ mv.setAttribute('ar', '');+ mv.setAttribute('ar-modes', 'webxr scene-viewer quick-look');+ mv.setAttribute('ar-scale', 'auto');+ if (isHttps(ar.usdzUrl)) mv.setAttribute('ios-src', ar.usdzUrl);++ mv.style.width = '100%';+ mv.style.height = '100%';+ mv.style.background = 'transparent';+ mount.appendChild(mv);++ return mv;+}diff --git a/public/viewer.html b/public/viewer.htmlnew file mode 100644index 000000000..75dc7c316--- /dev/null+++ b/public/viewer.html@@ -0,0 +1,162 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+<title>3D Viewer · three.ws</title>+<meta name="description" content="View and download an interactive 3D model (GLB) generated with three.ws." />+<meta name="robots" content="noindex" />+<meta property="og:title" content="3D Viewer · three.ws" />+<meta property="og:description" content="An interactive 3D model, generated with three.ws." />+<meta property="og:type" content="website" />+<!-- Meshopt decoder must register before <model-viewer> starts loading (Forge GLBs are meshopt-compressed). Classic script → runs during parse, before the model-viewer module. -->+<script src="/model-viewer-meshopt.js"></script>+<script type="module" src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"></script>+<style>+ :root { color-scheme: dark; --accent: #6ea8fe; }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; }+ body {+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;+ background: radial-gradient(130% 130% at 50% 0%, #14161c 0%, #0b0c10 60%, #08090c 100%);+ color: #e8eaf0;+ overflow: hidden;+ }+ .wrap { display: flex; flex-direction: column; height: 100dvh; }+ header.bar {+ display: flex; align-items: center; gap: 12px;+ padding: 12px 16px; border-bottom: 1px solid rgba(255,255,255,0.07);+ background: rgba(10,11,14,0.55); backdrop-filter: blur(8px);+ }+ .brand { display: flex; align-items: center; gap: 9px; text-decoration: none; color: #e8eaf0; font-weight: 700; letter-spacing: .01em; }+ .brand .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }+ .brand:hover { color: #fff; }+ .title { flex: 1 1 auto; min-width: 0; font-size: 13.5px; color: #aeb6c4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .stage { position: relative; flex: 1 1 auto; min-height: 0; }+ model-viewer {+ width: 100%; height: 100%;+ --poster-color: transparent; --progress-bar-color: var(--accent);+ background: transparent;+ }+ .overlay {+ position: absolute; inset: 0; display: flex; flex-direction: column;+ align-items: center; justify-content: center; gap: 14px; text-align: center; padding: 28px;+ }+ .spinner { width: 38px; height: 38px; border-radius: 50%; border: 3px solid rgba(255,255,255,0.14); border-top-color: var(--accent); animation: spin .9s linear infinite; }+ @keyframes spin { to { transform: rotate(360deg); } }+ @media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 2.4s; } }+ .h { font-size: 15px; font-weight: 600; }+ .muted { color: #9aa3b2; font-size: 13px; line-height: 1.5; max-width: 40ch; }+ footer.bar {+ display: flex; align-items: center; gap: 8px; flex-wrap: wrap;+ padding: 11px 16px; border-top: 1px solid rgba(255,255,255,0.07);+ background: rgba(10,11,14,0.55); backdrop-filter: blur(8px);+ }+ .spacer { flex: 1 1 auto; }+ a.btn, button.btn {+ appearance: none; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 7px;+ font-size: 13px; font-weight: 600; color: #e8eaf0;+ background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.14);+ border-radius: 10px; padding: 8px 13px; transition: background .15s, border-color .15s, transform .05s;+ }+ a.btn.primary { background: rgba(110,168,254,0.16); border-color: rgba(110,168,254,0.42); color: #dbe9ff; }+ a.btn:hover, button.btn:hover { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.28); }+ a.btn.primary:hover { background: rgba(110,168,254,0.26); }+ a.btn:active, button.btn:active { transform: translateY(1px); }+ a.btn:focus-visible, button.btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .hidden { display: none !important; }+ #ar-btn { display: none; }+</style>+</head>+<body>+<div class="wrap">+ <header class="bar">+ <a class="brand" href="https://three.ws"><span class="dot" aria-hidden="true"></span>three.ws</a>+ <span id="title" class="title"></span>+ </header>++ <div class="stage">+ <model-viewer id="mv" class="hidden" camera-controls auto-rotate touch-action="pan-y"+ rotation-per-second="14deg" interaction-prompt="none"+ shadow-intensity="1" shadow-softness="0.85" exposure="1.05" environment-image="neutral" tone-mapping="aces"+ ar ar-modes="webxr scene-viewer quick-look" ar-scale="auto" reveal="auto" alt="Generated 3D model">+ </model-viewer>++ <div id="loading" class="overlay">+ <div class="spinner" aria-hidden="true"></div>+ <div class="h">Loading model…</div>+ <div class="muted">Fetching and rendering the GLB. Large or high-detail models take a few seconds.</div>+ </div>++ <div id="empty" class="overlay hidden">+ <div class="h">No model to show</div>+ <div class="muted">This viewer opens a 3D model from a <code>?src=</code> link. Generate one for free at three.ws.</div>+ <a class="btn primary" href="https://three.ws">Create a 3D model</a>+ </div>++ <div id="error" class="overlay hidden">+ <div class="h">Couldn't display this model</div>+ <div id="errmsg" class="muted">The 3D model failed to load. You can still download the GLB file below.</div>+ </div>+ </div>++ <footer id="foot" class="bar hidden">+ <button id="ar-btn" class="btn" type="button" aria-label="View this model in augmented reality">View in AR</button>+ <div class="spacer"></div>+ <a id="download" class="btn" download aria-label="Download the GLB file">Download GLB</a>+ <a class="btn primary" href="https://three.ws" aria-label="Create your own 3D model at three.ws">Make your own →</a>+ </footer>+</div>++<script>+(function () {+ var mv = document.getElementById('mv');+ var loading = document.getElementById('loading');+ var empty = document.getElementById('empty');+ var errEl = document.getElementById('error');+ var errMsg = document.getElementById('errmsg');+ var foot = document.getElementById('foot');+ var titleEl = document.getElementById('title');+ var downloadEl = document.getElementById('download');+ var arBtn = document.getElementById('ar-btn');++ function show(el) { [loading, empty, errEl].forEach(function (n) { n.classList.add('hidden'); }); if (el) el.classList.remove('hidden'); }+ function fail(msg) { mv.classList.add('hidden'); errMsg.textContent = msg || 'The 3D model failed to load.'; show(errEl); }++ var params = new URLSearchParams(location.search);+ var src = params.get('src') || '';+ var title = params.get('title') || '';++ // Only ever load an https GLB — never data:/http:/blob: from an untrusted link.+ function isHttps(u) { try { return new URL(u).protocol === 'https:'; } catch (e) { return false; } }++ if (!src) { mv.classList.add('hidden'); foot.classList.add('hidden'); show(empty); return; }+ if (!isHttps(src)) { fail('That model link is not a valid https URL.'); foot.classList.remove('hidden'); return; }++ if (title) { titleEl.textContent = title; document.title = title + ' · 3D Viewer · three.ws'; }+ downloadEl.href = src;+ foot.classList.remove('hidden');+ show(loading);+ mv.setAttribute('src', src);++ mv.addEventListener('load', function () {+ show(null);+ mv.classList.remove('hidden');+ // Expose the AR button only when the device/model can actually enter AR.+ if (mv.canActivateAR) { arBtn.style.display = 'inline-flex'; }+ });+ mv.addEventListener('error', function () {+ fail('The 3D model could not be displayed. You can still download the GLB file.');+ });+ arBtn.addEventListener('click', function () { try { mv.activateAR(); } catch (e) {} });++ // If model-viewer itself never upgrades (script blocked), don't spin forever.+ setTimeout(function () {+ if (loading && !loading.classList.contains('hidden') && !customElements.get('model-viewer')) {+ fail('The 3D viewer could not load in this browser. Download the GLB and open it in any 3D viewer.');+ }+ }, 12000);+})();+</script>+</body>+</html>diff --git a/public/x402-stripe.html b/public/x402-stripe.htmlindex dd848e4c1..9068071bc 100644--- a/public/x402-stripe.html+++ b/public/x402-stripe.html@@ -562,7 +562,7 @@const CATS = [{ key: 'Crypto', icon: '◎', test: /pump|token|mint|vanity|symbol|intel|crypto|cross-chain|three-intel|reputation|bouncer|identity|did/i },{ key: '3D', icon: '◈', test: /mesh|forge|model|avatar|animation|cosmetic|club|dance|glb/i },- { key: 'AI', icon: '✦', test: /fact-check|tutor|vision|insight|revenue-vision/i },+ { key: 'AI', icon: '✦', test: /fact-check|tutor|vision|insight/i },{ key: 'Discovery', icon: '⌘', test: /marketplace|bazaar|catalog|skill/i },];const categorize = (path, ...text) => {diff --git a/scripts/audit-mcp-golden.mjs b/scripts/audit-mcp-golden.mjsindex df1ea4e56..d90628d90 100644--- a/scripts/audit-mcp-golden.mjs+++ b/scripts/audit-mcp-golden.mjs@@ -22,7 +22,7 @@//// Run: node scripts/audit-mcp-golden.mjs → compare, exit 1 on drift// node scripts/audit-mcp-golden.mjs --update → regenerate the fixture-import { readFileSync, writeFileSync, readdirSync } from 'node:fs';+import { readFileSync, writeFileSync, readdirSync, existsSync } from 'node:fs';import { createHash } from 'node:crypto';import { resolve, dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';@@ -40,8 +40,31 @@ const SOURCES = ['api/_mcpagent/tools.js','api/_mcpbazaar/tools.js','api/_mcpibm/tools.js',+ // Published MCP packages expose each tool as packages/<name>-mcp/src/tools/*.js.+ // Snapshot them too — a package tool's public contract (name, description,+ // input schema, safety annotations) is a promise to every MCP client that+ // installed it, and a silent refactor must not be allowed to change it.+ ...packageToolSources(),].filter((f) => f.endsWith('.js')).sort();+// Discover every `packages/*-mcp/src/tools/*.js` tool-definition file. Returns+// repo-relative, forward-slash paths (matching the hosted entries above) so the+// same static AST extractor and fixture keying work unchanged. `index.js`+// barrels are skipped — they re-export, they don't define contracts.+function packageToolSources() {+ const pkgRoot = join(ROOT, 'packages');+ if (!existsSync(pkgRoot)) return [];+ return readdirSync(pkgRoot, { withFileTypes: true })+ .filter((d) => d.isDirectory() && d.name.endsWith('-mcp'))+ .flatMap((d) => {+ const rel = `packages/${d.name}/src/tools`;+ if (!existsSync(join(ROOT, rel))) return [];+ return readdirSync(join(ROOT, rel))+ .filter((f) => f.endsWith('.js') && f !== 'index.js')+ .map((f) => `${rel}/${f}`);+ });+}+const sha12 = (text) => createHash('sha256').update(text).digest('hex').slice(0, 12);function templateText(node) {@@ -89,8 +112,10 @@ function extractTools(file) {if (name && hasContract) {const desc = stringValue(props.get('description'));const schemaNode = props.get('inputSchema');+ const title = stringValue(props.get('title'));tools.push({name,+ ...(title ? { title } : {}),descHead: desc ? desc.split('\n')[0].slice(0, 72) : 'dynamic',descHash: desc ? sha12(desc) : 'dynamic',annotations: annotationsValue(props.get('annotations')),@@ -145,7 +170,7 @@ for (const file of new Set([...Object.keys(golden), ...Object.keys(current)])) {for (const [name, tool] of after) {const prev = before.get(name);if (!prev) { complain(`${file}: tool ADDED: ${name}`); continue; }- for (const field of ['descHash', 'schemaHash']) {+ for (const field of ['title', 'descHash', 'schemaHash']) {if (JSON.stringify(prev[field]) !== JSON.stringify(tool[field])) {complain(`${file}: ${name}.${field.replace('Hash', '')} changed (was "${prev.descHead}")`);}diff --git a/server/index.mjs b/server/index.mjsindex ccdd988e5..be6480250 100644--- a/server/index.mjs+++ b/server/index.mjs@@ -324,8 +324,19 @@ app.use((req, res, next) => {// Vercel-parity body parsing. Types not listed (multipart, image/*, …) are// left unparsed so handlers can consume the raw request stream.-app.use(express.json({ limit: BODY_LIMIT }));-app.use(express.urlencoded({ extended: true, limit: BODY_LIMIT }));+//+// `verify` stashes the exact raw bytes on req.rawBody before they're parsed —+// a handful of handlers (webhook signature verification: api/webhooks/*.js)+// need the byte-for-byte body, which a re-serialized req.body can't+// reconstruct (whitespace/key-order differ). Every other handler reads the+// body via api/_lib/http.js readJson()/readBody(), which prefers req.rawBody+// (falling back to reconstructing from req.body) instead of re-reading the+// stream — reading the stream here already fully drains it, so a second read+// downstream would hang forever waiting for 'data'/'end' events that already+// fired.+const captureRawBody = (req, _res, buf) => { req.rawBody = buf; };+app.use(express.json({ limit: BODY_LIMIT, verify: captureRawBody }));+app.use(express.urlencoded({ extended: true, limit: BODY_LIMIT, verify: captureRawBody }));app.use(express.text({ type: 'text/*', limit: BODY_LIMIT }));app.use(express.raw({ type: 'application/octet-stream', limit: BODY_LIMIT }));diff --git a/solana-agent-sdk/src/index.ts b/solana-agent-sdk/src/index.tsindex 2a283472b..00075d125 100644--- a/solana-agent-sdk/src/index.ts+++ b/solana-agent-sdk/src/index.ts@@ -48,6 +48,10 @@ export type { BuildAndSendOptions } from "./tx/build.js";// Memoexport { memoInstruction, MEMO_PROGRAM_ID } from "./utils/memo.js";+// Token-2022 detection — resolve whether a mint is classic SPL Token or Token-2022+// so consumers building their own instructions target the correct program.+export { resolveTokenProgramId } from "./utils/token-program.js";+// Format utilitiesexport { toUiAmount } from "./utils/format.js";diff --git a/solana-agent-sdk/src/utils/token-program.ts b/solana-agent-sdk/src/utils/token-program.tsindex e546ffa65..e691f20c5 100644--- a/solana-agent-sdk/src/utils/token-program.ts+++ b/solana-agent-sdk/src/utils/token-program.ts@@ -1,6 +1,10 @@import { PublicKey, type Connection } from "@solana/web3.js";import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";+// A mint's owning program is fixed for the life of the mint, so caching by mint+// pubkey is always safe and turns a per-transfer RPC into a one-time lookup.+const programCache = new Map<string, PublicKey>();+/*** Resolve which SPL token program owns a mint — classic SPL Token vs Token-2022.*@@ -8,7 +12,8 @@ import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";* address and builds against the wrong program for a Token-2022 mint, so the* transfer fails (or a balance lookup misses) for tokens that genuinely exist in* the wallet — including $THREE, which is a Token-2022 mint. The mint account's- * owner is the canonical, on-chain way to tell the two programs apart.+ * owner is the canonical, on-chain way to tell the two programs apart. The result+ * is memoized for the process, so repeated transfers of the same mint hit RPC once.** @throws if the mint account doesn't exist or isn't owned by either SPL program.*/@@ -16,11 +21,21 @@ export async function resolveTokenProgramId(connection: Connection,mint: PublicKey,): Promise<PublicKey> {+ const key = mint.toBase58();+ const cached = programCache.get(key);+ if (cached) return cached;+const info = await connection.getAccountInfo(mint);- if (!info) throw new Error(`Mint not found: ${mint.toBase58()}`);- if (info.owner.equals(TOKEN_2022_PROGRAM_ID)) return TOKEN_2022_PROGRAM_ID;- if (info.owner.equals(TOKEN_PROGRAM_ID)) return TOKEN_PROGRAM_ID;- throw new Error(- `Not an SPL token mint (owner ${info.owner.toBase58()}): ${mint.toBase58()}`,- );+ if (!info) throw new Error(`Mint not found: ${key}`);++ let programId: PublicKey;+ if (info.owner.equals(TOKEN_2022_PROGRAM_ID)) programId = TOKEN_2022_PROGRAM_ID;+ else if (info.owner.equals(TOKEN_PROGRAM_ID)) programId = TOKEN_PROGRAM_ID;+ else+ throw new Error(+ `Not an SPL token mint (owner ${info.owner.toBase58()}): ${key}`,+ );++ programCache.set(key, programId);+ return programId;}diff --git a/solana-agent-sdk/tests/actions/transfer-spl.test.ts b/solana-agent-sdk/tests/actions/transfer-spl.test.tsindex 2ac8960dc..0d4b8d6d0 100644--- a/solana-agent-sdk/tests/actions/transfer-spl.test.ts+++ b/solana-agent-sdk/tests/actions/transfer-spl.test.ts@@ -23,6 +23,10 @@ const { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID,const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;const RECIPIENT_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(2)).publicKey;const MINT_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(3)).publicKey;+// A distinct mint for the Token-2022 case. resolveTokenProgramId memoizes a+// mint's owning program (immutable on-chain), so the 2022 test must use its own+// mint rather than reuse MINT_PUBKEY, which the classic-program tests already cached.+const MINT_2022_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(4)).publicKey;const SENDER_ATA = getAssociatedTokenAddressSync(MINT_PUBKEY, WALLET_PUBKEY, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,@@ -41,15 +45,16 @@ function makeConnection(senderExists: boolean,receiverExists: boolean,mintProgram: PublicKey = TOKEN_PROGRAM_ID,+ mint: PublicKey = MINT_PUBKEY,) {// ATAs are derived with whichever program owns the mint, so a Token-2022 test// must look its accounts up under the Token-2022 program.- const senderAta = getAssociatedTokenAddressSync(MINT_PUBKEY, WALLET_PUBKEY, false, mintProgram, ASSOCIATED_TOKEN_PROGRAM_ID);- const receiverAta = getAssociatedTokenAddressSync(MINT_PUBKEY, RECIPIENT_PUBKEY, false, mintProgram, ASSOCIATED_TOKEN_PROGRAM_ID);+ const senderAta = getAssociatedTokenAddressSync(mint, WALLET_PUBKEY, false, mintProgram, ASSOCIATED_TOKEN_PROGRAM_ID);+ const receiverAta = getAssociatedTokenAddressSync(mint, RECIPIENT_PUBKEY, false, mintProgram, ASSOCIATED_TOKEN_PROGRAM_ID);const getAccountInfo = jest.fn<(pubkey: PublicKey) => Promise<AccountInfo<Buffer> | null>>();getAccountInfo.mockImplementation(async (pubkey) => {// resolveTokenProgramId reads the mint account's owner to pick the program.- if (pubkey.equals(MINT_PUBKEY)) return ({ ...FAKE_ACCOUNT, owner: mintProgram } as unknown as AccountInfo<Buffer>);+ if (pubkey.equals(mint)) return ({ ...FAKE_ACCOUNT, owner: mintProgram } as unknown as AccountInfo<Buffer>);if (pubkey.equals(senderAta)) return senderExists ? (FAKE_ACCOUNT as unknown as AccountInfo<Buffer>) : null;if (pubkey.equals(receiverAta)) return receiverExists ? (FAKE_ACCOUNT as unknown as AccountInfo<Buffer>) : null;return null;@@ -135,8 +140,8 @@ describe("transferSpl", () => {it("uses the Token-2022 program for a Token-2022 mint (e.g. $THREE)", async () => {// Mint account owned by Token-2022 → ATAs and the transfer must build against// Token-2022, not the classic program (which would derive the wrong ATA).- await transferSpl(makeWallet(), makeConnection(true, true, TOKEN_2022_PROGRAM_ID), {- mint: MINT_PUBKEY, to: RECIPIENT_PUBKEY, amount: 1_000_000n,+ await transferSpl(makeWallet(), makeConnection(true, true, TOKEN_2022_PROGRAM_ID, MINT_2022_PUBKEY), {+ mint: MINT_2022_PUBKEY, to: RECIPIENT_PUBKEY, amount: 1_000_000n,});const [, , instructions] = mockBuildAndSendFn.mock.calls[0]!;@@ -144,7 +149,7 @@ describe("transferSpl", () => {expect(transferIx.programId.equals(TOKEN_2022_PROGRAM_ID)).toBe(true);// And the source ATA is the Token-2022-derived address, not the classic one.const expectedSenderAta = getAssociatedTokenAddressSync(- MINT_PUBKEY, WALLET_PUBKEY, false, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ MINT_2022_PUBKEY, WALLET_PUBKEY, false, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,);expect(transferIx.keys[0]!.pubkey.equals(expectedSenderAta)).toBe(true);});diff --git a/specs/EMBED_SPEC.md b/specs/EMBED_SPEC.mdindex 26018cf34..c40c6073d 100644--- a/specs/EMBED_SPEC.md+++ b/specs/EMBED_SPEC.md@@ -77,7 +77,7 @@ name-plate) is **opt-in**:| Attribute | Type | Default | Notes || -------------- | ------------------------- | ------------- | ----------------------------------------- |-| `brain` | model id | from manifest | `claude-opus-4-6`, `none`, etc. |+| `brain` | model id | from manifest | `claude-opus-4-6`, `free` (host-paid free tier, no key needed), `none`, etc. || `api-key` | string | none | **dev use only** — prefer `key-proxy` || `key-proxy` | URL | none | your backend that injects API keys safely || `instructions` | URL or inline | from manifest | overrides manifest's instructions.md |diff --git a/specs/SPATIAL_MCP.md b/specs/SPATIAL_MCP.mdnew file mode 100644index 000000000..aad44a327--- /dev/null+++ b/specs/SPATIAL_MCP.md@@ -0,0 +1,109 @@+# Spatial MCP — 3D as a native conversational response type++**Version 0.1** · Open specification · License: CC0 / public domain (adopt freely)++> Reference implementation: [three.ws](https://three.ws). Validator: `api/_lib/spatial-mcp.js`. Reference renderer: [`/spatial-mcp`](https://three.ws/spatial-mcp). Adoption guide: [`docs/spatial-mcp.md`](../docs/spatial-mcp.md).++## The problem++MCP tool results are text or JSON today. A tool that produces a 3D model can only hand back a URL and hope the host does something useful with it. There is no shared shape that says "this result **is** an interactive 3D scene — render it, let the user orbit it, animate it, place it in AR."++**Spatial MCP** defines that shape: a structured-content artifact a tool returns so any conformant host can render a live scene inline instead of printing a link. It aligns with the MCP Apps / Apps SDK component-embedding model — a tool emits the artifact in `structuredContent`, and a host renders it with an embedded component (three.ws ships one; the shape is renderer-agnostic).++The shape carries **zero** payment, wallet, coin, or token fields, so it is safe to adopt in any context, including crypto-free app stores.++## The artifact++A Spatial MCP artifact is a JSON object placed in a tool result's `structuredContent` (three.ws nests it under the key `spatial`, but the object stands alone). Only `spatialMcpVersion`, `kind`, and `scene.glbUrl` are required; every other field is optional and a renderer applies sensible defaults for anything absent.++```jsonc+{+ "spatialMcpVersion": "0.1", // required — the shape version a host reads to pick a renderer+ "kind": "model", // required — model | mesh | avatar | rigged-model | scene+ "scene": { // required+ "glbUrl": "https://…/model.glb", // required — an https URL to a .glb asset+ "format": "glb", // recommended — only "glb" in v0.1+ "poster": "https://…/prev.jpg", // optional — a preview image shown while loading+ "alt": "a battle-worn helmet" // optional — accessibility text+ },+ "camera": { // optional+ "autoRotate": true, // default true+ "orbit": "0deg 80deg 2m", // optional — model-viewer camera-orbit string+ "fieldOfView": "30deg" // optional+ },+ "environment": { // optional+ "image": "neutral", // "neutral" or an https .hdr URL+ "exposure": 1.0, // default 1.0+ "shadowIntensity": 1.0 // default 1.0+ },+ "animation": { // optional — present when the asset is animated+ "autoplay": true, // default true+ "clips": ["idle", "wave"] // optional — named clips; renderer plays the first+ },+ "persona": { // optional — an embodied, speakable body (see three.ws prompt 07)+ "id": "psn_…",+ "speakable": true+ },+ "ar": { // optional — AR handoff (see prompt 21)+ "supported": true, // true requires at least one asset/link below+ "usdzUrl": "https://…/m.usdz", // iOS Quick Look+ "glbUrl": "https://…/m.glb", // Android Scene Viewer source+ "launchUrl": "https://…/ar?…" // a device-aware AR launch page+ },+ "affordances": { // optional — what the host should allow+ "orbit": true, "zoom": true, "fullscreen": true, "download": true+ },+ "meta": { // optional — human-facing, NO internal identifiers+ "title": "Damaged helmet",+ "prompt": "a battle-worn sci-fi helmet",+ "viewerUrl": "https://…/viewer?src=…"+ }+}+```++### Field rules++| Field | Required | Rule |+|---|---|---|+| `spatialMcpVersion` | ✅ | string; must be a known version (`0.1`). |+| `kind` | ✅ | one of `model`, `mesh`, `avatar`, `rigged-model`, `scene`. Drives labelling/affordances only — an unknown kind still renders `scene.glbUrl`. |+| `scene` | ✅ | object with a required `glbUrl`. |+| `scene.glbUrl` | ✅ | **https** URL to a `.glb`. Non-https is rejected — a host feeds this to a renderer `src`. |+| `scene.format` | recommended | `"glb"` only in v0.1. |+| `scene.poster` | optional | https URL when present. |+| `camera`,`environment`,`animation`,`persona`,`affordances`,`meta` | optional | objects; validated for type/shape only when present. |+| `ar.*Url` | optional | https URLs; `ar.supported: true` requires at least one of `usdzUrl`/`glbUrl`/`launchUrl`. |++**Data minimization.** `meta` is human-facing only. Never place session ids, job/creation/prediction ids, trace ids, wallet addresses, prices, or any auth/coin field anywhere in the artifact. The reference validator does not police this (it can't know your internal names), but conformant emitters MUST strip them — this is what keeps the shape reusable in crypto-free stores.++**Forward compatibility.** Unknown top-level fields are ignored by conformant renderers (a warning, not an error), so a host may carry extra data without breaking older renderers.++## Conformance++Validate an artifact with `validateSpatialArtifact(payload)` (`api/_lib/spatial-mcp.js`) or the MCP tool `validate_spatial_response({ artifact })` on the three.ws 3D Studio server. Both return actionable diagnostics:++```js+{ valid: false, version: "0.1",+ errors: [{ path: "scene.glbUrl", message: "required — must be an https URL to a .glb asset" }],+ warnings: [{ path: "camera", message: "recommended — include { autoRotate: true } so hosts frame the model" }] }+```++A payload is **conformant** iff `errors` is empty. Emit the artifact from your tool, pass it through the validator in CI, and any Spatial-MCP renderer can display it.++## Rendering++A conformant renderer:+1. Loads `scene.glbUrl` into a WebGL/`<model-viewer>` scene.+2. Applies `camera`/`environment`/`affordances`, defaulting anything absent.+3. Plays `animation` when present; offers AR when `ar` (or the GLB) supports it.+4. Degrades gracefully — a missing optional never breaks the render; an unusable payload shows a designed fallback, not a blank frame.++The reference renderer is `public/spatial-mcp/spatial-renderer.js` (`renderSpatialArtifact(mount, artifact)`), demoed at [`/spatial-mcp`](https://three.ws/spatial-mcp). It is framework-free and reusable independent of the three.ws product.++## Adopters (three.ws)++Tools that emit conformant artifacts today: `forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`, and `refine_model` (free 3D Studio — under `structuredContent.spatial`); `preview_3d` (paid 3D Studio). The validator tool `validate_spatial_response` is the public conformance gate.++## Versioning++`spatialMcpVersion` is the contract. `0.1` is the initial shape. Additive fields ship in a new minor version; a breaking change bumps the major. Renderers read the version to select behavior. This spec is CC0 — reimplement, extend, and ship it anywhere.diff --git a/specs/vault-manifest.md b/specs/vault-manifest.mdnew file mode 100644index 000000000..cb2c8e3ac--- /dev/null+++ b/specs/vault-manifest.md@@ -0,0 +1,191 @@+# Vault Manifest Spec v1 — Encrypted-GLB Envelope++The BNB vault track (prompts 08–11) stores 3D models (GLB) so that even+though the encrypted bytes live on a public-ish Storage Provider (Greenfield+or any object store — see the portability note below), only a paying,+authorized buyer can ever recover the plaintext. This document is the wire+contract other code depends on:++- **08** (this prompt) implements the crypto primitives — `api/_lib/bnb/vault-crypto.js`.+- **09** (upload) produces the manifest below and uploads the ciphertext.+- **10** (contract) is the on-chain source of truth for `sellerAddress` / `priceAtomic` / access grants.+- **11** (unlock) consumes the manifest to deliver a wrapped key to a verified buyer and drive `unwrapKey` + `decryptGlb`.++Implementation: `api/_lib/bnb/vault-crypto.js` (`encryptGlb`, `decryptGlb`,+`wrapKey`, `unwrapKey`, `generateVaultKeypair`, `VAULT_CRYPTO_PARAMS`).++## Design goals++1. **Backend-agnostic.** The envelope and manifest never assume a specific+ storage backend. `glbObjectRef` is a `{bucket, object}` pointer — today+ that resolves against Greenfield buckets/objects, but the same manifest+ shape works unchanged against S3, R2, or any object store, hedging the+ Greenfield platform-risk noted in `00-CONTEXT.md` (contracts repo+ deprioritized, absent from the 2026 roadmap).+2. **Bytes-at-rest are always ciphertext.** The Storage Provider, any relay,+ and any observer of the manifest itself never sees plaintext GLB bytes or+ the raw content key.+3. **Per-object content key, per-buyer key delivery.** Every vault object+ gets its own random AES-256-GCM content key (`encryptGlb`). That content+ key is delivered to an authorized buyer only via `wrapKey`/`unwrapKey`+ (ECIES to the buyer's own secp256k1 public key — the same curve as their+ BSC/EVM address), never embedded in the manifest or transmitted in the+ clear.+4. **Fail loud, never silent garbage.** Tampered ciphertext, a tampered auth+ tag, or the wrong unwrap key must throw a typed error+ (`VaultCryptoError`), not return corrupted bytes.++## Cryptographic parameters (fixed for v1)++| Parameter | Value |+|---|---|+| Content cipher | AES-256-GCM (Node `crypto`, OpenSSL-backed) |+| Content key length | 32 bytes (256-bit), random per object |+| GCM IV (nonce) length | 12 bytes (96-bit, NIST SP 800-38D recommended size), random per encryption |+| GCM auth tag length | 16 bytes (128-bit) |+| Key-wrap scheme | ECIES over secp256k1 (ephemeral ECDH → HKDF-SHA256 → AES-256-GCM) |+| Key-wrap KDF | HKDF-SHA256, `info = "three.ws/bnb-vault/ecies/v1"`, no salt (HKDF default: zero-filled `hashLen` salt per RFC 5869) |+| Key-wrap ephemeral public key | secp256k1, compressed, 33 bytes |+| Recipient key | The buyer's own secp256k1 keypair (same curve as their EVM/BSC address — a buyer can, in principle, prove control of the wrap-recipient key the same way they prove control of their BSC address, though the vault track may use a dedicated vault keypair rather than the chain signing key directly; prompt 11 decides which) |+| Hash for content integrity | SHA-256 of the plaintext GLB bytes |++These are exposed programmatically from `VAULT_CRYPTO_PARAMS` in+`vault-crypto.js` so callers never hardcode a second copy that could drift+from the implementation.++## Byte layout of the envelope++The **encrypted object** uploaded to the Storage Provider is the raw GCM+ciphertext bytes only (`encryptGlb(...).ciphertext`) — no header, no+manifest fields inline. `iv`, `authTag`, and everything needed to interpret+the ciphertext live in the **manifest**, stored as a separate JSON object+alongside it (e.g. `<object>.manifest.json` next to `<object>.glb.enc`, or a+manifest-hub record referencing the object key — prompt 09 picks the exact+naming/pairing convention on top of this spec).++```+Storage Provider bucket/+├── <object>.glb.enc # raw AES-256-GCM ciphertext bytes (opaque)+└── <object>.manifest.json # the manifest below+```++Rationale: keeping ciphertext bytes header-free means the encrypted object+is a plain binary blob any object store can serve as-is (correct+`Content-Length`, resumable range requests, CDN-cacheable) — no custom+parser needed on the read path before the manifest is fetched.++## Manifest JSON schema++```json+{+ "version": 1,+ "glbObjectRef": {+ "bucket": "three-ws-vault-testnet",+ "object": "vaults/0xSellerAddr.../a1b2c3d4.glb.enc"+ },+ "encryption": {+ "alg": "AES-256-GCM",+ "iv": "9f1c... (24 hex chars = 12 bytes)",+ "authTag": "7e3a... (32 hex chars = 16 bytes)"+ },+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",+ "priceAtomic": "100000",+ "sellerAddress": "0x0000000000000000000000000000000000dEaD",+ "contract": {+ "address": "0x0000000000000000000000000000000000dEaD",+ "chainId": 97+ },+ "createdAt": "2026-07-08T00:00:00.000Z"+}+```++### Field reference++| Field | Type | Notes |+|---|---|---|+| `version` | integer | Manifest schema version. `1` for this spec. A future breaking change increments this; readers MUST reject an unknown version rather than guess. |+| `glbObjectRef.bucket` | string | Storage Provider bucket name (Greenfield bucket or equivalent). |+| `glbObjectRef.object` | string | Object key within the bucket. Points at the raw ciphertext blob described above. |+| `encryption.alg` | string | Always `"AES-256-GCM"` for v1 — matches `VAULT_CRYPTO_PARAMS.alg`. |+| `encryption.iv` | hex string | 12-byte GCM nonce, lowercase hex, no `0x` prefix. From `encryptGlb().iv`. |+| `encryption.authTag` | hex string | 16-byte GCM auth tag, lowercase hex, no `0x` prefix. From `encryptGlb().authTag`. |+| `sha256` | hex string | SHA-256 of the **plaintext** GLB bytes (`encryptGlb().sha256OfPlaintext`). The buyer's client MUST verify this after `decryptGlb` — pass it as `decryptGlb(envelope, { expectedSha256 })` to fail loudly on any silent corruption. |+| `priceAtomic` | decimal string | Price in the payment token's smallest unit (atomic), as a string to avoid float precision loss — same convention as `priceFor`/x402 elsewhere in this repo. Default `"100000"` (= $0.10 at 6 decimals) per 00-CONTEXT's "unsure of a price" default, env-overridable by prompt 09/10. |+| `sellerAddress` | `0x`-checksummed EVM address | The seller's BSC address. Validate with `assertBscAddress` from `api/_lib/bnb/chains.js`. |+| `contract.address` | `0x`-checksummed EVM address | The on-chain vault/marketplace contract that gates purchase + access (prompt 10). |+| `contract.chainId` | integer | `56` (BSC mainnet) or `97` (BSC testnet) — see `BNB_CHAINS` in `api/_lib/bnb/chains.js`. |+| `createdAt` | ISO 8601 string | Manifest creation timestamp (UTC). |++The manifest never contains the content key (raw or wrapped) — key delivery+is a separate, buyer-specific, access-gated flow (below), not a static field+anyone with the manifest URL can read.++## Key-delivery flow++The manifest is assumed to be publicly readable (it contains no secrets).+The **content key** is the secret, and it is delivered only after prompt+10's contract confirms the requester is an authorized buyer:++1. **Seller uploads (prompt 09).** Seller calls `encryptGlb(glbBytes)`,+ uploads `ciphertext` to the Storage Provider, and publishes the manifest+ (`iv`, `authTag`, `sha256`, `glbObjectRef`, etc.) alongside it. The+ seller retains `contentKey` only long enough to wrap it per-buyer (or+ re-derives/re-wraps on each sale) — it is never written to the manifest+ or any public location.+2. **Buyer purchases (prompt 10).** Buyer pays `priceAtomic` to `contract`+ on `contract.chainId`. The contract is the source of truth for "is this+ address an authorized buyer of this object" — `vault-crypto.js` has no+ opinion on payment; it only wraps/unwraps keys once authorization is+ established.+3. **Key unlock (prompt 11).** After the contract confirms payment, the+ unlock service calls `wrapKey(contentKey, buyerPubKey)` — a fresh ECIES+ wrap addressed to that specific buyer's public key — and returns the+ wrapped-key bundle (`ephemeralPublicKey`, `iv`, `authTag`, `ciphertext`)+ to the buyer over an authenticated channel. Only that buyer's matching+ private key can `unwrapKey` it; anyone else's key derives a different+ AES key and the GCM auth check fails closed (`VaultCryptoError` with+ `code: 'auth_failed'`).+4. **Buyer decrypts.** Buyer calls `unwrapKey(wrapped, theirPrivKey)` to+ recover the content key, then+ `decryptGlb({ciphertext, contentKey, iv, authTag}, {expectedSha256: manifest.sha256})`+ to recover and verify the original GLB bytes.++Each sale to a new buyer re-runs step 3 with that buyer's own public key —+`wrapKey` is deterministic in output *shape* but random in ephemeral key per+call (see `VAULT_CRYPTO_PARAMS`/tests: two wraps of the same content key to+the same recipient never produce identical ciphertext), so there is no+shared "master wrapped key" to leak across buyers.++## Error surface (typed, from `vault-crypto.js`)++`VaultCryptoError extends Error`, `name: 'VaultCryptoError'`, distinguishing+`code`:++| `code` | Thrown when |+|---|---|+| `bad_input` | Empty plaintext, or a value that isn't a Buffer/Uint8Array/hex string where one is required. |+| `bad_length` | A key/IV/tag is the wrong byte length (e.g. a 16-byte value where a 32-byte AES key is required) — rejected *before* touching the cipher. |+| `bad_public_key` | `recipientPubKey` doesn't decode to a valid secp256k1 curve point. |+| `bad_ecdh_input` | ECDH itself fails on the given private/public key pair. |+| `auth_failed` | GCM auth-tag verification failed — tampered ciphertext/tag, or (for `unwrapKey`) the wrong recipient private key. Never returns partial/garbage plaintext. |+| `sha256_mismatch` | `decryptGlb(..., {expectedSha256})` succeeded at the GCM layer but the plaintext hash doesn't match — signals silent corruption upstream of encryption, or a manifest/ciphertext pairing mistake. |++Prompts 09/11's HTTP layers should map `auth_failed` → 401/403 (wrong+key/tampered data), `bad_*` → 400 (malformed input), never a raw 500.++## Portability note (Greenfield platform-risk hedge)++Nothing in `vault-crypto.js` or this manifest imports a Greenfield SDK,+references a Greenfield-specific address type, or assumes Greenfield's+async cross-chain settlement model. `glbObjectRef.bucket`/`object` are+backend-neutral strings. If Greenfield's 2026 roadmap deprioritization (see+`00-CONTEXT.md`) makes it unsuitable later, prompt 09's upload path is the+only place that needs to change — swap the Storage-Provider client, keep+this manifest shape and every crypto primitive as-is.++## Versioning++This is `version: 1`. Any change to the algorithm, key lengths, HKDF info+string, or manifest field set is a breaking change and MUST bump `version`.+Readers MUST reject a manifest whose `version` they don't recognize rather+than attempt best-effort decryption.diff --git a/src/agent-avatar.js b/src/agent-avatar.jsindex 1e2771771..7ac029175 100644--- a/src/agent-avatar.js+++ b/src/agent-avatar.js@@ -33,6 +33,16 @@ import { log } from './shared/log.js';const DEG2RAD = Math.PI / 180;+// Sustained-mood → gesture-slot bias thresholds (Living Agents · Task 07+// extension). Read against the *applied* (lerped) mood, not the raw target, so+// a gesture only fires once the mood has actually settled there — a momentary+// setMood() spike doesn't yank the body into a slot the same frame it decays.+const MOOD_GESTURE_THRESHOLD = {+ positiveValence: 0.35, // above this = "up"; below its negation = "down"+ energeticArousal: 0.6, // above this = "energetic"+ calmArousal: 0.25, // below this = "subdued"+};+// Emotion decay rates (units per second — larger = fades faster)const DECAY = {concern: 0.08, // half-life ~12s — lingers, builds empathy@@ -774,6 +784,25 @@ export class AgentAvatar {this._playSlot('concern', 2.0);} else if (w.curiosity > 0.6) {this._playSlot('think', 1.5);+ } else if (this._mood.active) {+ // Stage 3.5: sustained-mood gesture bias. Stage 3 above reacts to+ // momentary emotion *spikes* (an error just happened, a task just+ // finished); this reacts to the agent's *resting* mood — the same+ // valence/arousal state that drives the facial mood layer in+ // _applyMoodLayer(). Only engages once nothing else already claims+ // the one-shot slot (the `else` above), so a live event always wins.+ // Routes through the same `_playSlot` → `resolveSlot` path as every+ // other gesture, so `meta.edits.animations` overrides still apply and+ // an unregistered clip name can never be selected.+ const { valence, arousal } = this._moodApplied;+ if (valence > MOOD_GESTURE_THRESHOLD.positiveValence && arousal > MOOD_GESTURE_THRESHOLD.energeticArousal) {+ // Sustained up + energetic mood → lively, energetic body language.+ this._playSlot('celebrate', 2.5);+ } else if (valence < -MOOD_GESTURE_THRESHOLD.positiveValence && arousal < MOOD_GESTURE_THRESHOLD.calmArousal) {+ // Sustained down + subdued mood → concerned stillness — the+ // opposite bias, never the energetic gesture.+ this._playSlot('concern', 2.5);+ }}}diff --git a/src/bnb-hub-helpers.js b/src/bnb-hub-helpers.jsnew file mode 100644index 000000000..4e082247e--- /dev/null+++ b/src/bnb-hub-helpers.js@@ -0,0 +1,68 @@+// Pure helpers for the /bnb hub page (src/bnb.js). Kept dependency-free and+// side-effect-free so they're unit-testable without mocking fetch or the DOM+// — see tests/bnb-hub-helpers.test.js.++/**+ * Format a block-time measurement in milliseconds as a short duration string.+ * Sub-second reads two decimals ("0.45s"), otherwise one ("1.2s"). Returns+ * "—" for missing/invalid input so callers never branch on null before+ * rendering.+ */+export function formatBlockTime(ms) {+ if (ms == null || !Number.isFinite(ms) || ms < 0) return '—';+ const seconds = ms / 1000;+ return seconds < 1 ? `${seconds.toFixed(2)}s` : `${seconds.toFixed(1)}s`;+}++/**+ * Compact integer formatting for block numbers / counts: locale-grouped+ * ("108,693,266"). Returns "—" for missing/invalid input.+ */+export function formatBlockNumber(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ return Math.round(n).toLocaleString('en-US');+}++/**+ * How far off a measured block time is from the marketing target, as a+ * signed percentage ("+2.2%" measured slower, "-4.0%" measured faster).+ * Returns null when either input is missing (no target on testnet).+ */+export function deltaFromTarget(measuredMs, targetMs) {+ if (!Number.isFinite(measuredMs) || !Number.isFinite(targetMs) || targetMs === 0) return null;+ const pct = ((measuredMs - targetMs) / targetMs) * 100;+ return `${pct >= 0 ? '+' : ''}${pct.toFixed(1)}%`;+}++/**+ * Interpret an HTTP probe outcome into a track's liveness state.+ *+ * A track "exists" the moment its route/API resolves — regardless of which+ * status it answers with. A 404 means the file genuinely isn't deployed yet+ * (Vercel/Cloud Run route table has no match). A 405 means the route exists+ * but the probe method isn't what it wants (expected for POST-only APIs+ * probed with GET/HEAD) — that still counts as live. Any 2xx/3xx/4xx other+ * than 404 counts as live; a network failure (status === null) or a 5xx+ * fails closed to "coming-soon" — an unreachable/erroring dependency should+ * never read as a shipped feature.+ *+ * @param {number|null} status - HTTP status code, or null on network error.+ * @returns {'live'|'coming-soon'}+ */+export function trackLiveness(status) {+ if (status == null) return 'coming-soon';+ if (status === 404) return 'coming-soon';+ if (status >= 500) return 'coming-soon';+ return 'live';+}++/**+ * Reduce N per-check results (a card can gate on more than one route) to one+ * card state: live only when every check is live.+ * @param {Array<'live'|'coming-soon'>} states+ * @returns {'live'|'coming-soon'}+ */+export function combineTrackStates(states) {+ if (!Array.isArray(states) || states.length === 0) return 'coming-soon';+ return states.every((s) => s === 'live') ? 'live' : 'coming-soon';+}diff --git a/src/bnb.js b/src/bnb.jsnew file mode 100644index 000000000..31a8a250f--- /dev/null+++ b/src/bnb.js@@ -0,0 +1,233 @@+// /bnb — the BNB Chain campaign's front door. Renders (1) a live block-time+// proof strip backed by /api/bnb/block-time (which wraps probeBlockTime from+// api/_lib/bnb/chains.js — a real RPC measurement, never hardcoded) and (2)+// three feature cards, each auto-detecting whether its track has shipped by+// probing the real route/API on this deployment. No hardcoded live/coming-soon+// flags: a card lights up the moment its check target starts resolving.+//+// See prompts/bnb-chain/19-bnb-hub-page.md and 00-CONTEXT.md (verified/refuted+// claims list — every sentence on this page traces back to that list).++import { escapeHtml as esc, timeAgo } from './shared/coin-format.js';+import {+ formatBlockTime,+ formatBlockNumber,+ deltaFromTarget,+ trackLiveness,+ combineTrackStates,+} from './bnb-hub-helpers.js';++const $ = (id) => document.getElementById(id);++// ── Live block-time proof ────────────────────────────────────────────────++async function loadBlockTime() {+ const el = $('bnb-proof-card');+ el.innerHTML = `+ <div class="bnb-proof-loading" role="status" aria-live="polite">+ <span class="bnb-spinner" aria-hidden="true"></span>+ Measuring live BNB Chain block time from a public RPC…+ </div>`;+ try {+ const res = await fetch('/api/bnb/block-time?network=bscMainnet', {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(8000),+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = await res.json();+ renderBlockTime(data);+ } catch {+ el.innerHTML = `+ <div class="bnb-proof-error" role="alert">+ BNB Chain RPC is unreachable right now — every public endpoint we tried timed out.+ <button class="bnb-retry" id="bnb-proof-retry" type="button">Retry</button>+ </div>`;+ const retry = $('bnb-proof-retry');+ if (retry) retry.addEventListener('click', loadBlockTime);+ }+}++function renderBlockTime(data) {+ const el = $('bnb-proof-card');+ const avg = formatBlockTime(data.avgBlockTimeMs);+ const delta = deltaFromTarget(data.avgBlockTimeMs, data.target);+ const deltaClass = delta && delta.startsWith('-') ? 'delta-fast' : 'delta-slow';+ const deltaHtml = delta+ ? `<span class="${deltaClass}">${esc(delta)} vs the ${data.target}ms Fermi-hardfork target</span>`+ : 'no published target on this network';++ el.innerHTML = `+ <div class="bnb-proof-num">${esc(avg)}<span class="unit">avg block time</span></div>+ <div class="bnb-proof-mid">+ <p class="bnb-proof-title">Measured live, right now — not a marketing claim</p>+ <p class="bnb-proof-sub">${deltaHtml} · sampled ${esc(String(data.sampleBlocks))} real blocks off a public BSC RPC</p>+ </div>+ <div class="bnb-proof-stats">+ <span>latest block <b>${esc(formatBlockNumber(data.latestBlock))}</b></span>+ <span>updated ${esc(timeAgo(data.measuredAt))}</span>+ </div>`;+}++// ── Track cards ───────────────────────────────────────────────────────────++const ICONS = {+ bolt: '<path d="M13 2 3 14h7l-1 8 10-12h-7l1-8Z" fill="currentColor"/>',+ lock: '<path d="M6 10V7a6 6 0 0 1 12 0v3" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/><rect x="4" y="10" width="16" height="11" rx="2" stroke="currentColor" stroke-width="2" fill="none"/>',+ globe: '<circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="2" fill="none"/><path d="M3 12h18M12 3a15 15 0 0 1 0 18M12 3a15 15 0 0 0 0 18" stroke="currentColor" stroke-width="1.6" fill="none"/>',+};++// Each track gates on ONE canonical, independently-probeable HTTP target —+// the concrete artifact the card's headline claim depends on. A card also+// carries an optional secondary link that only renders once its own probe+// (checked separately) resolves, so nothing on the page ever links to a 404.+const TRACKS = [+ {+ id: 'gasless',+ icon: 'bolt',+ kicker: 'BEP-414 + BEP-322 · MegaFuel',+ title: 'Gasless agent onboarding',+ desc: `A brand-new wallet holding zero BNB mints a real on-chain ERC-8004 agent+ identity — no faucet, no funding step, no smart-account setup first. BSC's+ BEP-414 paymaster API pairs a user's own zero-gas-price transaction with a+ sponsor transaction atomically (BEP-322) — a plain private-key EOA, not a+ smart account. That's mechanically impossible on Ethereum L1 or Base today:+ EIP-1559 rejects a zero-fee transaction outright, and ERC-4337/7702 both+ need extra account setup before the first tx. Built on MegaFuel (NodeReal's+ production implementation), with an automatic self-pay fallback.`,+ caveat: 'MegaFuel is one operator (NodeReal); BEP-414 is still Draft status. Sponsorship decline always falls through to self-pay — it never blocks registration.',+ primary: { label: 'Register an agent gaslessly', href: '/create-agent' },+ primaryCheck: '/api/bnb/register-agent',+ secondary: { label: 'Read the payments guide', href: '/docs/bnb-payments' },+ secondaryCheck: '/docs/bnb-payments.md',+ },+ {+ id: 'vault',+ icon: 'lock',+ kicker: 'Greenfield cross-chain hubs · live on BSC(56)',+ title: 'On-chain-gated 3D vault',+ desc: `Buy access to an encrypted 3D model on BSC, and the unlock key is granted+ through a live cross-chain call into Greenfield's programmable storage —+ bucket, object, and group permissions created and revoked directly from a+ BSC smart contract (six hub contracts, bytecode-verified live on BSC+ mainnet, 2026-07-07). No other chain we've built on lets a smart contract+ program object-level storage permissions on a separate data-availability+ chain in one flow.`,+ caveat: 'Object creation from BSC is still pending in the underlying protocol, and cross-chain grants settle asynchronously — the vault shows "granting access…" honestly instead of hiding the wait. Greenfield is live but deprioritized on BNB’s 2026 roadmap; the vault’s crypto format stays portable to another storage backend.',+ primary: { label: 'Browse the vault', href: '/vault' },+ primaryCheck: '/vault',+ },+ {+ id: 'world',+ icon: 'globe',+ kicker: 'Fermi hardfork · ~0.45s blocks, live',+ title: 'Real-time on-chain world',+ desc: `Every step your avatar takes in Explore can be written on-chain and read+ back by every other player in the room, riding BNB's ~0.45s blocks and+ ~1.125s finality (Fermi hardfork BEP-619/590, live since 2026-01-14 —+ measured on a public RPC below, right now). At Base's 2s blocks or+ Ethereum's 12s, a step-by-step on-chain presence layer isn't playable; at+ ~0.45s it's the fastest EVM L1 in production — only Solana's ~400ms slot+ cadence comes close, and it isn't an EVM chain.`,+ caveat: 'The on-chain toggle inside Explore/Platformer is opt-in and off by default — no surprise wallet prompts. BEP-670 targets 250ms blocks next; that isn’t live yet, so this page measures and shows only what’s real today.',+ primary: { label: 'Watch the live block race', href: '/bnb-latency' },+ primaryCheck: '/bnb-latency',+ },+];++function iconSvg(name) {+ return `<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">${ICONS[name] || ''}</svg>`;+}++function ctaHtml(track, state) {+ if (state !== 'live') {+ return `<span class="bnb-cta" aria-disabled="true" title="Ships as part of the BNB Chain campaign — not deployed on this build yet">+ ${esc(track.primary.label)} — coming soon+ </span>`;+ }+ return `<a class="bnb-cta" href="${esc(track.primary.href)}">${esc(track.primary.label)} →</a>`;+}++function cardHtml(track) {+ return `+ <article class="bnb-card" data-track="${esc(track.id)}">+ <div class="bnb-card-head">+ <div class="bnb-card-icon">${iconSvg(track.icon)}</div>+ <span class="bnb-status" data-state="checking" aria-live="polite" aria-label="Status: checking">Checking</span>+ </div>+ <p class="kicker">${esc(track.kicker)}</p>+ <h2>${esc(track.title)}</h2>+ <p class="desc">${esc(track.desc.replace(/\s+/g, ' ').trim())}</p>+ <p class="caveat">${esc(track.caveat)}</p>+ <div class="bnb-card-footer" data-cta-slot></div>+ </article>`;+}++/** Probe a URL and resolve to an HTTP status, or null on network failure/timeout. */+async function probe(url) {+ try {+ const res = await fetch(url, { method: 'HEAD', signal: AbortSignal.timeout(4000) });+ return res.status;+ } catch {+ return null;+ }+}++async function checkTrack(track) {+ const checks = [track.primaryCheck, track.secondaryCheck].filter(Boolean);+ const statuses = await Promise.all(checks.map(probe));+ const states = statuses.map(trackLiveness);+ const primaryState = trackLiveness(statuses[0]);+ const secondaryState = track.secondaryCheck ? trackLiveness(statuses[1]) : 'coming-soon';+ return { cardState: combineTrackStates([primaryState]), primaryState, secondaryState };+}++async function updateCard(track) {+ const card = document.querySelector(`.bnb-card[data-track="${track.id}"]`);+ if (!card) return null;+ const { cardState, secondaryState } = await checkTrack(track);++ const pill = card.querySelector('.bnb-status');+ pill.dataset.state = cardState;+ pill.textContent = cardState === 'live' ? 'Live' : 'Coming soon';+ pill.setAttribute('aria-label', `Status: ${cardState === 'live' ? 'live' : 'coming soon'}`);++ const slot = card.querySelector('[data-cta-slot]');+ const bits = [ctaHtml(track, cardState)];+ if (track.secondary && secondaryState === 'live') {+ bits.push(+ `<a class="bnb-cta-secondary" href="${esc(track.secondary.href)}">${esc(track.secondary.label)} ↗</a>`,+ );+ }+ slot.innerHTML = bits.join('');++ return cardState;+}++function updateProgress(states) {+ const el = $('bnb-progress');+ if (!el) return;+ const liveCount = states.filter((s) => s === 'live').length;+ el.dataset.anyLive = liveCount > 0 ? 'true' : 'false';+ el.textContent =+ liveCount === 0+ ? `0 of ${states.length} demo tracks live yet — block-time proof is live below`+ : `${liveCount} of ${states.length} demo track${states.length === 1 ? '' : 's'} live now`;+}++async function loadTracks() {+ const grid = $('bnb-grid');+ grid.innerHTML = TRACKS.map(cardHtml).join('');+ const states = await Promise.all(TRACKS.map(updateCard));+ updateProgress(states);+}++function init() {+ loadBlockTime();+ loadTracks();+}++if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', init);+} else {+ init();+}diff --git a/src/categories.css b/src/categories.cssnew file mode 100644index 000000000..e42b73bec--- /dev/null+++ b/src/categories.css@@ -0,0 +1,27 @@+/*+ * /categories — sector leaderboard. Reuses the shared cv-table / cv-stat-card+ * system from coin-pages.css; this file adds only the stacked top-3 coin+ * avatars that identify each category in the name cell.+ */++.cat-avatars {+ display: inline-flex;+ align-items: center;+ flex-shrink: 0;+}+.cat-avatars img {+ width: 22px;+ height: 22px;+ border-radius: 50%;+ background: var(--cv-surface-3);+ border: 2px solid var(--cv-surface);+ object-fit: cover;+}+.cat-avatars img + img {+ margin-left: -8px;+}++/* Keep the avatar stack visible even where the table hides the ticker on mobile. */+.cv-table .name-cell .inner {+ gap: 0.625rem;+}diff --git a/src/categories.js b/src/categories.jsnew file mode 100644index 000000000..10bce3b05--- /dev/null+++ b/src/categories.js@@ -0,0 +1,215 @@+// /categories — crypto sector leaderboard, styled after the /coins markets+// index: a couple of summary stat cards up top, then a sortable table of every+// CoinGecko category ranked by market cap with its top-3 coin icons, 24h move,+// and 24h volume. Consumes /api/coin/categories.++import { formatUsd, formatPercent, escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── Summary stat cards ────────────────────────────────────────────────────────++const ICONS = {+ grid: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>',+ trend: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>',+ bars: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/></svg>',+};++function statCard({ label, value, delta, deltaClass, icon }) {+ return `+ <div class="cv-stat-card">+ <div style="min-width:0">+ <p class="label">${esc(label)}</p>+ <p class="value cv-mono">${esc(value)}</p>+ ${delta ? `<p class="delta ${deltaClass || ''}">${esc(delta)}</p>` : ''}+ </div>+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>+ </div>`;+}++function renderStats() {+ const el = $('cat-stats');+ const cats = state.categories;+ if (!cats.length) {+ el.innerHTML = '';+ return;+ }+ // Categories overlap (a coin sits in many), so a summed market cap would+ // double-count. The largest category is the honest headline number instead.+ const top = cats.reduce(+ (best, c) => ((c.market_cap ?? 0) > (best.market_cap ?? 0) ? c : best),+ cats[0],+ );+ const gainers = cats.filter((c) => (c.market_cap_change_24h ?? 0) > 0).length;+ const cards = [+ statCard({+ label: 'Categories Tracked',+ value: cats.length.toLocaleString('en-US'),+ icon: 'grid',+ }),+ statCard({+ label: 'Largest Category',+ value: top.name,+ delta: formatUsd(top.market_cap),+ icon: 'bars',+ }),+ statCard({+ label: 'Advancing (24h)',+ value: `${gainers} / ${cats.length}`,+ delta: `${cats.length - gainers} declining`,+ deltaClass: gainers >= cats.length - gainers ? 'cv-up' : 'cv-down',+ icon: 'trend',+ }),+ ];+ el.innerHTML = `<div style="display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(200px,1fr))">${cards.join('')}</div>`;+}++// ── Category table ────────────────────────────────────────────────────────────++const COLUMNS = [+ { key: 'rank', label: '#', left: true, hide: 'hide-sm', num: true },+ { key: 'name', label: 'Category', left: true },+ { key: 'market_cap', label: 'Market Cap', num: true },+ { key: 'market_cap_change_24h', label: '24h %', num: true },+ { key: 'volume_24h', label: 'Volume (24h)', hide: 'hide-md', num: true },+];++const state = { categories: [], sortKey: 'rank', sortDir: 'asc' };++function pctCell(v) {+ if (v == null) return '<td class="pct dim">—</td>';+ const up = v >= 0;+ return `<td class="pct ${up ? 'cv-up' : 'cv-down'}"><span aria-hidden="true">${up ? '▲' : '▼'}</span>${esc(formatPercent(v))}</td>`;+}++function avatarStack(coins) {+ if (!coins || !coins.length) return '';+ const imgs = coins+ .map(+ (u) =>+ `<img src="${esc(u)}" alt="" loading="lazy" width="22" height="22" data-no-dark-filter />`,+ )+ .join('');+ return `<span class="cat-avatars" aria-hidden="true">${imgs}</span>`;+}++function sortValue(c, key) {+ if (key === 'name') return (c.name || '').toLowerCase();+ if (key === 'rank') return c.rank ?? Infinity;+ return c[key] ?? -Infinity;+}++function sortedCategories() {+ const copy = [...state.categories];+ const { sortKey, sortDir } = state;+ copy.sort((a, b) => {+ const va = sortValue(a, sortKey);+ const vb = sortValue(b, sortKey);+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;+ return sortDir === 'asc' ? cmp : -cmp;+ });+ return copy;+}++function renderTable() {+ const el = $('cat-table');+ if (!state.categories.length) {+ el.innerHTML =+ '<div class="cv-empty">Category data is temporarily unavailable. Please try again shortly.</div>';+ return;+ }++ const head = COLUMNS.map((col) => {+ const active = col.key === state.sortKey;+ const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ }).join('');++ const rows = sortedCategories()+ .map((c) => {+ const href = `/coins?category=${encodeURIComponent(c.id)}`;+ return `+ <tr data-href="${esc(href)}">+ <td class="rank hide-sm cv-mono">${c.rank ?? '—'}</td>+ <td class="left name-cell"><a href="${esc(href)}"><span class="inner">+ ${avatarStack(c.top_3_coins)}+ <span class="nm">${esc(c.name)}</span>+ </span></a></td>+ <td class="dim">${esc(formatUsd(c.market_cap))}</td>+ ${pctCell(c.market_cap_change_24h)}+ <td class="dim hide-md">${esc(formatUsd(c.volume_24h))}</td>+ </tr>`;+ })+ .join('');++ el.innerHTML = `+ <div class="cv-table-wrap">+ <table class="cv-table">+ <thead><tr>${head}</tr></thead>+ <tbody>${rows}</tbody>+ </table>+ </div>`;++ el.querySelectorAll('th[data-key]').forEach((th) => {+ const activate = () => {+ const key = th.dataset.key;+ if (key === state.sortKey) {+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';+ } else {+ state.sortKey = key;+ state.sortDir = key === 'name' || key === 'rank' ? 'asc' : 'desc';+ }+ renderTable();+ };+ th.addEventListener('click', activate);+ th.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ activate();+ }+ });+ });++ el.querySelectorAll('tr[data-href]').forEach((tr) => {+ tr.addEventListener('click', (e) => {+ if (e.target.closest('a')) return;+ location.href = tr.dataset.href;+ });+ });+}++// ── Load ──────────────────────────────────────────────────────────────────────++async function loadCategories() {+ const el = $('cat-table');+ el.innerHTML =+ '<div class="cv-table-wrap" style="padding:0.75rem">' ++ Array.from(+ { length: 12 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('') ++ '</div>';+ try {+ const { categories } = await getJson('/api/coin/categories');+ // The endpoint returns market-cap-desc order; that ordinal is the rank.+ state.categories = (categories || []).map((c, i) => ({ ...c, rank: i + 1 }));+ $('cat-updated').textContent = `Updated ${new Date().toLocaleTimeString('en-US')}`;+ } catch {+ state.categories = [];+ $('cat-updated').textContent = '';+ }+ renderStats();+ renderTable();+}++loadCategories();diff --git a/src/chains.css b/src/chains.cssnew file mode 100644index 000000000..c40f07ee9--- /dev/null+++ b/src/chains.css@@ -0,0 +1,50 @@+/*+ * /chains — cross-chain TVL leaderboard. Layered after coin-pages.css: reuses+ * the cv-* token system, cards, and table; this file only adds the stat grid+ * and the inline dominance bar. Both themes inherit from the shared data-theme+ * tokens.+ */++.chains-stat-grid {+ display: grid;+ gap: 1rem;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+}++/* Rows are informational, not navigable — reset the shared table's pointer+ cursor so nothing signals a click target that doesn't exist. */+#chains-table .cv-table tbody tr {+ cursor: default;+}++/* Inline dominance bar. Fixed-width track so bars read as a shared scale down+ the column; the fill is scaled to the leading chain in chains.js. */+.chains-bar-cell {+ min-width: 160px;+}+.chains-bar {+ display: block;+ width: 100%;+ max-width: 220px;+ height: 8px;+ border-radius: 999px;+ background: var(--cv-surface-3);+ overflow: hidden;+}+.chains-bar-fill {+ display: block;+ height: 100%;+ border-radius: 999px;+ background: linear-gradient(+ 90deg,+ var(--cv-accent),+ color-mix(in srgb, var(--cv-accent) 55%, transparent)+ );+ transition: width 0.4s ease;+}++@media (prefers-reduced-motion: reduce) {+ .chains-bar-fill {+ transition: none;+ }+}diff --git a/src/chains.js b/src/chains.jsnew file mode 100644index 000000000..0ba83cc28--- /dev/null+++ b/src/chains.js@@ -0,0 +1,230 @@+// /chains — cross-chain TVL leaderboard. Header stat cards (total TVL, chain+// count, top-chain dominance), and a sortable table of chains by TVL with an+// inline dominance bar. Data comes from /api/defi/chains (DeFiLlama, keyless),+// normalized server-side. Mirrors the /coins markets-table pattern: stat cards,+// sortable cv-table, designed loading / empty / error states.++import { formatUsd, escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── Stat cards ────────────────────────────────────────────────────────────++const ICONS = {+ lock: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>',+ link: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',+ pie: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.21 15.89A10 10 0 1 1 8 2.83"/><path d="M22 12A10 10 0 0 0 12 2v10z"/></svg>',+};++function statCard({ label, value, delta, icon }) {+ return `+ <div class="cv-stat-card">+ <div style="min-width:0">+ <p class="label">${esc(label)}</p>+ <p class="value cv-mono">${esc(value)}</p>+ ${delta ? `<p class="delta">${esc(delta)}</p>` : ''}+ </div>+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>+ </div>`;+}++function renderStats() {+ const el = $('chains-stats');+ const top = state.chains[0];+ const cards = [+ statCard({+ label: 'Total Cross-Chain TVL',+ value: formatUsd(state.total_tvl),+ icon: 'lock',+ }),+ statCard({+ label: 'Chains Tracked',+ value: state.chain_count.toLocaleString('en-US'),+ icon: 'link',+ }),+ ];+ if (top) {+ cards.push(+ statCard({+ label: `${top.name} Dominance`,+ value: `${top.share_pct.toFixed(1)}%`,+ delta: formatUsd(top.tvl),+ icon: 'pie',+ }),+ );+ }+ el.innerHTML = `<div class="chains-stat-grid">${cards.join('')}</div>`;+}++function statsSkeleton() {+ $('chains-stats').innerHTML =+ '<div class="chains-stat-grid">' ++ Array.from({ length: 3 }, () => '<div class="cv-skel" style="height:6rem"></div>').join(+ '',+ ) ++ '</div>';+}++// ── Table ─────────────────────────────────────────────────────────────────++const COLUMNS = [+ { key: 'rank', label: '#', left: true, hide: 'hide-sm', num: true },+ { key: 'name', label: 'Chain', left: true },+ { key: 'tvl', label: 'TVL', num: true },+ { key: 'share_pct', label: 'Dominance', num: true },+ { key: 'bar', label: 'Share', left: true, hide: 'hide-md', sortless: true },+];++const state = {+ chains: [],+ total_tvl: 0,+ chain_count: 0,+ updated_at: 0,+ sortKey: 'tvl',+ sortDir: 'desc',+ loading: true,+ error: false,+};++function sortValue(c, key) {+ if (key === 'name') return (c.name || '').toLowerCase();+ if (key === 'rank') return c.__rank ?? Infinity;+ return c[key] ?? -Infinity;+}++function sortedChains() {+ const ranked = [...state.chains].sort((a, b) => (b.tvl ?? 0) - (a.tvl ?? 0));+ ranked.forEach((c, i) => (c.__rank = i + 1));+ const { sortKey, sortDir } = state;+ const sorted = [...ranked].sort((a, b) => {+ const va = sortValue(a, sortKey);+ const vb = sortValue(b, sortKey);+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;+ return sortDir === 'asc' ? cmp : -cmp;+ });+ return sorted;+}++function renderTable() {+ const el = $('chains-table');++ if (state.loading) {+ el.innerHTML =+ '<div class="cv-table-wrap" style="padding:0.75rem">' ++ Array.from(+ { length: 12 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('') ++ '</div>';+ return;+ }+ if (state.error) {+ el.innerHTML =+ '<div class="cv-empty">Chain TVL data is temporarily unavailable. <a href="/chains">Try again</a> shortly.</div>';+ return;+ }+ if (!state.chains.length) {+ el.innerHTML =+ '<div class="cv-empty">No chain data to show right now. <a href="/chains">Refresh</a> to retry.</div>';+ return;+ }++ // The dominance bar scales to the leader so the top chain fills the cell and+ // the rest read as a fraction of it — a clearer visual than raw share %.+ const maxShare = Math.max(...state.chains.map((c) => c.share_pct || 0), 0.0001);++ const head = COLUMNS.map((col) => {+ if (col.sortless) {+ return `<th scope="col" class="${col.left ? 'left' : ''} ${col.hide || ''}">${esc(col.label)}</th>`;+ }+ const active = col.key === state.sortKey;+ const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ }).join('');++ const body = sortedChains()+ .map((c) => {+ const barPct = Math.max(2, ((c.share_pct || 0) / maxShare) * 100);+ return `+ <tr>+ <td class="rank hide-sm cv-mono">${c.__rank}</td>+ <td class="left name-cell"><span class="inner">+ <span class="nm">${esc(c.name)}</span>+ ${c.token_symbol ? `<span class="sym">${esc(c.token_symbol)}</span>` : ''}+ </span></td>+ <td class="price">${esc(formatUsd(c.tvl))}</td>+ <td class="pct cv-mono">${(c.share_pct || 0).toFixed(2)}%</td>+ <td class="left hide-md chains-bar-cell">+ <span class="chains-bar" role="img" aria-label="${(c.share_pct || 0).toFixed(2)}% of total value locked">+ <span class="chains-bar-fill" style="width:${barPct.toFixed(1)}%"></span>+ </span>+ </td>+ </tr>`;+ })+ .join('');++ el.innerHTML = `+ <div class="cv-table-wrap">+ <table class="cv-table">+ <thead><tr>${head}</tr></thead>+ <tbody>${body}</tbody>+ </table>+ </div>`;++ el.querySelectorAll('th[data-key]').forEach((th) => {+ const activate = () => {+ const key = th.dataset.key;+ if (key === state.sortKey) {+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';+ } else {+ state.sortKey = key;+ state.sortDir = key === 'name' ? 'asc' : 'desc';+ }+ renderTable();+ };+ th.addEventListener('click', activate);+ th.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ activate();+ }+ });+ });+}++// ── Boot ──────────────────────────────────────────────────────────────────++async function load() {+ statsSkeleton();+ renderTable();+ try {+ const data = await getJson('/api/defi/chains');+ state.chains = Array.isArray(data.chains) ? data.chains : [];+ state.total_tvl = data.total_tvl || 0;+ state.chain_count = data.chain_count || state.chains.length;+ state.updated_at = data.updated_at || Date.now();+ state.loading = false;+ state.error = false;+ renderStats();+ renderTable();+ $('chains-updated').textContent =+ `Top ${state.chains.length} chains by TVL · Data: DeFiLlama · updated ${new Date(state.updated_at).toLocaleTimeString('en-US')}`;+ } catch {+ state.loading = false;+ state.error = true;+ $('chains-stats').innerHTML = '';+ renderTable();+ }+}++load();diff --git a/src/coin-pages.css b/src/coin-pages.cssindex ed85536de..3cae911a2 100644--- a/src/coin-pages.css+++ b/src/coin-pages.css@@ -540,6 +540,13 @@ html.cv-page, .cv-page body {.cv-news-card, .cv-stat-card, .cv-range-btn { transition: none; }}+/* Market-tools hub strip on /coins — every sibling surface, one row. */+.cv-tools {+ display: flex; flex-wrap: wrap; gap: 0.5rem;+ margin: 0 0 2rem;+}+.cv-tools .cv-pill { font-size: 0.8125rem; }+/* ═══════════════════════════════════════════════════════════════════════════Market tools — /fear-greed, /heatmap, /gas, /compareShared with the coin pages above (same tokens, fonts, card system).diff --git a/src/converter.css b/src/converter.cssnew file mode 100644index 000000000..adde2f768--- /dev/null+++ b/src/converter.css@@ -0,0 +1,472 @@+/*+ * /converter — crypto ⇄ crypto ⇄ fiat converter widget.+ * Loaded AFTER /src/coin-pages.css: reuses its design tokens (--cv-*), card+ * system, skeletons, spinner, empty state, and pills. Everything here is+ * specific to the converter's two-sided input + asset picker.+ */++/* ── Presets ─────────────────────────────────────────────────────────────── */++.cvt-presets {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ margin-bottom: 1.25rem;+}+.cvt-preset {+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-size: 0.8125rem;+ font-weight: 500;+ color: var(--cv-text-2);+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: 999px;+ padding: 0.375rem 0.875rem;+ font-variant-numeric: tabular-nums;+ transition:+ background 0.15s,+ color 0.15s,+ border-color 0.15s,+ transform 0.1s;+}+.cvt-preset:hover {+ background: var(--cv-surface-3);+ color: var(--cv-text);+ border-color: var(--cv-border-hover);+}+.cvt-preset:active {+ transform: translateY(1px);+}+.cvt-preset:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++/* ── Widget shell ────────────────────────────────────────────────────────── */++.cvt-app {+ position: relative;+ max-width: 40rem;+}++.cvt-card {+ padding: 1.25rem;+ display: grid;+ grid-template-columns: 1fr;+ gap: 0.75rem;+}+@media (min-width: 560px) {+ .cvt-card {+ padding: 1.75rem;+ }+}++.cvt-side {+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ padding: 1rem 1.125rem;+ transition: border-color 0.15s;+}+.cvt-side:focus-within {+ border-color: var(--cv-border-hover);+}++.cvt-label {+ display: block;+ font-size: 0.6875rem;+ font-weight: 600;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--cv-text-3);+ margin-bottom: 0.5rem;+}++.cvt-row {+ display: flex;+ align-items: center;+ gap: 0.75rem;+}++/* Amount input — big, mono, borderless (the side card is the frame). */+.cvt-amount {+ flex: 1 1 auto;+ min-width: 0;+ appearance: none;+ border: 0;+ background: transparent;+ color: var(--cv-text);+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+ font-size: 1.75rem;+ font-weight: 600;+ line-height: 1.1;+ padding: 0;+}+.cvt-amount:focus {+ outline: none;+}+.cvt-amount::placeholder {+ color: var(--cv-text-3);+}++/* Result — same visual weight as the input, read-only. */+.cvt-result {+ flex: 1 1 auto;+ min-width: 0;+ color: var(--cv-text);+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+ font-size: 1.75rem;+ font-weight: 600;+ line-height: 1.1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.cvt-result-empty {+ color: var(--cv-text-3);+}++.cvt-subline {+ margin: 0.5rem 0 0;+ font-size: 0.8125rem;+ color: var(--cv-text-3);+ min-height: 1.125rem;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* ── Asset button ────────────────────────────────────────────────────────── */++.cvt-asset {+ flex: 0 0 auto;+ display: inline-flex;+ align-items: center;+ gap: 0.4375rem;+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-weight: 600;+ color: var(--cv-text);+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: 999px;+ padding: 0.375rem 0.625rem 0.375rem 0.5rem;+ transition:+ border-color 0.15s,+ background 0.15s;+}+.cvt-asset:hover {+ border-color: var(--cv-border-hover);+ background: var(--cv-surface-3);+}+.cvt-asset:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}+.cvt-asset img {+ width: 22px;+ height: 22px;+ border-radius: 50%;+ background: var(--cv-surface-3);+ flex: 0 0 auto;+}+.cvt-asset svg {+ color: var(--cv-text-3);+ flex: 0 0 auto;+}+.cvt-asset-code {+ font-size: 0.9375rem;+ letter-spacing: 0.01em;+}+.cvt-asset-glyph {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ border-radius: 50%;+ background: var(--cv-surface-3);+ color: var(--cv-text-2);+ font-size: 0.75rem;+ font-weight: 700;+ flex: 0 0 auto;+}+.cvt-asset-glyph.fiat {+ background: color-mix(in srgb, var(--cv-accent) 16%, transparent);+ color: var(--cv-accent);+}+.cvt-asset-load {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+}+.cvt-asset-load .cv-spinner {+ width: 0.875rem;+ height: 0.875rem;+ color: var(--cv-text-3);+}++/* ── Swap button ─────────────────────────────────────────────────────────── */++.cvt-swap-wrap {+ display: flex;+ justify-content: center;+ align-items: center;+ height: 0;+ position: relative;+ z-index: 2;+ margin: -0.25rem 0;+}+.cvt-swap {+ appearance: none;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 2.375rem;+ height: 2.375rem;+ border-radius: 50%;+ background: var(--cv-surface);+ color: var(--cv-text-2);+ border: 1px solid var(--cv-border);+ box-shadow: var(--cv-shadow-card);+ transition:+ color 0.15s,+ border-color 0.15s,+ transform 0.2s,+ background 0.15s;+}+.cvt-swap:hover {+ color: var(--cv-accent);+ border-color: var(--cv-accent);+ background: var(--cv-surface-2);+ transform: rotate(180deg);+}+.cvt-swap:active {+ transform: rotate(180deg) scale(0.94);+}+.cvt-swap:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++/* ── Rate line + retry ───────────────────────────────────────────────────── */++.cvt-rate {+ margin: 0.375rem 0 0;+ font-size: 0.9375rem;+ color: var(--cv-text-2);+ font-variant-numeric: tabular-nums;+ text-align: center;+}+.cvt-rate strong {+ color: var(--cv-text);+ font-weight: 600;+}+.cvt-rate .dim {+ color: var(--cv-text-3);+}++.cvt-card .cv-updated {+ text-align: center;+ margin-top: 0.25rem;+}++.cvt-retry {+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-size: 0.875rem;+ font-weight: 500;+ color: #fff;+ background: var(--cv-accent);+ border: 0;+ border-radius: var(--cv-radius-md);+ padding: 0.5rem 1.25rem;+ transition: background 0.15s;+}+.cvt-retry:hover {+ background: var(--cv-accent-hover);+}+.cvt-retry:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++/* ── Asset picker popover ────────────────────────────────────────────────── */++.cvt-picker {+ position: fixed;+ z-index: 60;+ width: min(22rem, calc(100vw - 2rem));+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ box-shadow: var(--cv-shadow-dropdown);+ overflow: hidden;+ animation: cvtPickIn 0.14s ease-out;+}+@keyframes cvtPickIn {+ from {+ opacity: 0;+ transform: translateY(-4px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}+@media (prefers-reduced-motion: reduce) {+ .cvt-picker {+ animation: none;+ }+}++.cvt-pick-search {+ position: relative;+ padding: 0.625rem;+ border-bottom: 1px solid var(--cv-border);+}+.cvt-pick-search .mag {+ position: absolute;+ left: 1.125rem;+ top: 50%;+ transform: translateY(-50%);+ width: 1rem;+ height: 1rem;+ color: var(--cv-text-3);+ pointer-events: none;+}+.cvt-pick-search input {+ width: 100%;+ appearance: none;+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ color: var(--cv-text);+ font: inherit;+ font-size: 0.875rem;+ padding: 0.5rem 0.75rem 0.5rem 2.125rem;+ transition:+ border-color 0.15s,+ box-shadow 0.15s;+}+.cvt-pick-search input::placeholder {+ color: var(--cv-text-3);+}+.cvt-pick-search input:focus {+ outline: none;+ border-color: var(--cv-accent);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 20%, transparent);+}++.cvt-pick-list {+ max-height: 20rem;+ overflow-y: auto;+ -webkit-overflow-scrolling: touch;+ padding: 0.375rem;+}++.cvt-pick-head {+ margin: 0.375rem 0.5rem 0.25rem;+ font-size: 0.6875rem;+ font-weight: 600;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--cv-text-3);+}+.cvt-pick-group + .cvt-pick-group {+ margin-top: 0.25rem;+}++.cvt-pick-item {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 0.625rem;+ appearance: none;+ cursor: pointer;+ text-align: left;+ font: inherit;+ color: var(--cv-text);+ background: transparent;+ border: 0;+ border-radius: var(--cv-radius-md);+ padding: 0.4375rem 0.5rem;+ transition: background 0.12s;+}+.cvt-pick-item:hover,+.cvt-pick-item:focus-visible {+ background: var(--cv-surface-2);+ outline: none;+}+.cvt-pick-item img {+ width: 22px;+ height: 22px;+ border-radius: 50%;+ background: var(--cv-surface-3);+ flex: 0 0 auto;+}+.cvt-pick-glyph {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ border-radius: 50%;+ background: var(--cv-surface-3);+ color: var(--cv-text-2);+ font-size: 0.75rem;+ font-weight: 700;+ flex: 0 0 auto;+}+.cvt-pick-glyph.fiat {+ background: color-mix(in srgb, var(--cv-accent) 16%, transparent);+ color: var(--cv-accent);+}+.cvt-pick-name {+ flex: 1 1 auto;+ min-width: 0;+ font-size: 0.875rem;+ font-weight: 500;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.cvt-pick-code {+ color: var(--cv-text-3);+ text-transform: uppercase;+ font-size: 0.75rem;+ flex: 0 0 auto;+}+.cvt-pick-rank {+ color: var(--cv-text-3);+ font-size: 0.75rem;+ flex: 0 0 auto;+}++.cvt-pick-note {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.75rem 0.625rem;+ color: var(--cv-text-3);+ font-size: 0.8125rem;+}+.cvt-pick-note .cv-spinner {+ width: 0.875rem;+ height: 0.875rem;+}++/* ── Cross-links ─────────────────────────────────────────────────────────── */++.cvt-links {+ margin-top: 1.75rem;+}diff --git a/src/converter.js b/src/converter.jsnew file mode 100644index 000000000..ed50a0fd7--- /dev/null+++ b/src/converter.js@@ -0,0 +1,678 @@+// /converter — crypto ⇄ crypto ⇄ fiat converter, part of the /coins "Markets"+// surface. Reuses the shared /api/coin proxies:+// · /api/coin/rates → curated fiat currencies (units per 1 BTC)+// · /api/coin/markets?q=<text> → coin search type-ahead (same UX as /coins)+// · /api/coin/detail?id=<id> → a coin's live USD price (market.price)+//+// Conversion is anchored in USD. Every asset knows its USD value:+// · crypto: priceUSD = market.price (USD per 1 coin)+// · fiat: fiatPerUsd(code) = fiat.per_btc / usd.per_btc (units per 1 USD)+// From any FROM asset we compute the USD value of `amount`, then express that+// value in the TO asset — which makes all four directions fall out of one+// formula: crypto→crypto, crypto→fiat, fiat→crypto, fiat→fiat.++import { formatPrice, escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── Formatting ────────────────────────────────────────────────────────────────++// Fiat amount with the currency's own unit symbol + thousands separators.+// Alphabetic units ("Fr.", "R$", "kr") get a space; glyphs ("$", "€", "₹") hug.+function formatFiatAmount(n, unit) {+ if (n == null || !Number.isFinite(n)) return '—';+ const sign = n < 0 ? '-' : '';+ const abs = Math.abs(n);+ let body;+ if (abs !== 0 && abs < 0.01) body = abs.toPrecision(4);+ else body = abs.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });+ const u = unit || '';+ const sep = /[A-Za-z.]$/.test(u) ? ' ' : '';+ return `${sign}${u}${sep}${body}`;+}++// Crypto amount: full precision for whole coins, significant figures for the+// deep-decimal results a fiat→BTC conversion produces (e.g. 0.00001587 BTC).+function formatCryptoAmount(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ if (n === 0) return '0';+ const abs = Math.abs(n);+ if (abs >= 1) return n.toLocaleString('en-US', { maximumFractionDigits: 8 });+ const s = n.toPrecision(6);+ const expanded = s.includes('e') ? Number(s).toFixed(18) : s;+ return expanded.replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');+}++// Format `n` in whatever `asset` is — used for the result field and rate line.+function formatInAsset(n, asset) {+ if (!asset) return '—';+ return asset.kind === 'fiat' ? formatFiatAmount(n, asset.unit) : formatCryptoAmount(n);+}++// Short code shown on the asset button and rate line.+function assetCode(asset) {+ if (!asset) return '';+ return asset.kind === 'fiat' ? asset.code : asset.symbol;+}++// ── State ─────────────────────────────────────────────────────────────────────++// rates: { byCode: Map<CODE, {code,name,unit,per_btc}>, usdPerBtc, list:[], updated_at }+// from / to: { kind:'crypto', id, symbol, name, image, priceUSD }+// or { kind:'fiat', code, name, unit, per_btc }+const state = {+ rates: null,+ from: null,+ to: null,+ amount: 1,+ loading: true,+ error: null,+ pending: { from: false, to: false },+};++const DEFAULT_CRYPTO = 'bitcoin';++// ── Conversion math (USD-anchored) ────────────────────────────────────────────++function fiatPerUsd(fiat) {+ // units of `fiat` per 1 BTC ÷ USD per 1 BTC = units of `fiat` per 1 USD.+ return fiat.per_btc / state.rates.usdPerBtc;+}++// USD value of `amount` units of `asset`.+function toUsd(amount, asset) {+ if (!asset || !Number.isFinite(amount)) return null;+ if (asset.kind === 'crypto') {+ if (!Number.isFinite(asset.priceUSD)) return null;+ return amount * asset.priceUSD;+ }+ // fiat: amount fiat-units ÷ (fiat-units per USD) = USD.+ const perUsd = fiatPerUsd(asset);+ if (!Number.isFinite(perUsd) || perUsd <= 0) return null;+ return amount / perUsd;+}++// Express a USD value in `asset`.+function fromUsd(valueUsd, asset) {+ if (!asset || !Number.isFinite(valueUsd)) return null;+ if (asset.kind === 'crypto') {+ if (!Number.isFinite(asset.priceUSD) || asset.priceUSD <= 0) return null;+ return valueUsd / asset.priceUSD;+ }+ const perUsd = fiatPerUsd(asset);+ if (!Number.isFinite(perUsd)) return null;+ return valueUsd * perUsd;+}++// Convert `amount` of FROM into TO. Null if either leg lacks a price.+function convert(amount, from, to) {+ const usd = toUsd(amount, from);+ if (usd == null) return null;+ return fromUsd(usd, to);+}++// ── Rendering ─────────────────────────────────────────────────────────────────++const CHEVRON =+ '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>';+const SWAP_ICON =+ '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>';++function assetButtonInner(asset, side) {+ if (state.pending[side]) {+ return `<span class="cvt-asset-load"><span class="cv-spinner" aria-hidden="true"></span></span>${CHEVRON}`;+ }+ if (!asset) return `<span class="cvt-asset-code">Select</span>${CHEVRON}`;+ if (asset.kind === 'crypto') {+ const icon = asset.image+ ? `<img src="${esc(asset.image)}" alt="" width="22" height="22" data-no-dark-filter />`+ : `<span class="cvt-asset-glyph">${esc((asset.symbol || '?').slice(0, 1))}</span>`;+ return `${icon}<span class="cvt-asset-code">${esc(asset.symbol)}</span>${CHEVRON}`;+ }+ const glyph = asset.unit || asset.code.slice(0, 1);+ return `<span class="cvt-asset-glyph fiat">${esc(glyph)}</span><span class="cvt-asset-code">${esc(asset.code)}</span>${CHEVRON}`;+}++function assetSubline(asset) {+ if (!asset) return '';+ if (asset.kind === 'crypto') {+ return `${esc(asset.name)} · ${esc(formatPrice(asset.priceUSD))}`;+ }+ return esc(asset.name);+}++function renderRate() {+ const el = $('cvt-rate');+ if (!el) return;+ if (!state.from || !state.to) {+ el.textContent = '';+ return;+ }+ const one = convert(1, state.from, state.to);+ if (one == null) {+ el.innerHTML = `<span class="dim">Live rate unavailable for this pair.</span>`;+ return;+ }+ el.innerHTML = `1 ${esc(assetCode(state.from))} = <strong>${esc(formatInAsset(one, state.to))}</strong> ${esc(assetCode(state.to))}`;+}++function renderResult() {+ const el = $('cvt-result');+ if (!el) return;+ const amt = state.amount;+ if (!Number.isFinite(amt)) {+ el.innerHTML = '<span class="cvt-result-empty">—</span>';+ return;+ }+ const out = convert(amt, state.from, state.to);+ if (out == null) {+ el.innerHTML = '<span class="cvt-result-empty">—</span>';+ return;+ }+ el.textContent = formatInAsset(out, state.to);+}++function renderUpdated() {+ const el = $('cvt-updated');+ if (!el || !state.rates) return;+ const d = new Date(state.rates.updated_at);+ el.textContent = `Rates updated ${d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })} · live market prices`;+}++function renderCard() {+ const app = $('cvt-app');+ if (state.error) {+ app.innerHTML = `+ <div class="cvt-card cv-card">+ <div class="cv-empty">+ <p style="margin:0 0 0.75rem">We couldn't load live rates just now.</p>+ <button type="button" class="cvt-retry" id="cvt-retry">Try again</button>+ </div>+ </div>`;+ $('cvt-retry')?.addEventListener('click', boot);+ return;+ }+ if (state.loading) {+ app.innerHTML = `+ <div class="cvt-card cv-card">+ <div class="cv-skel" style="height:5.5rem;margin-bottom:1rem"></div>+ <div class="cv-skel" style="height:5.5rem"></div>+ </div>`;+ return;+ }++ app.innerHTML = `+ <div class="cvt-card cv-card">+ <div class="cvt-side" data-side="from">+ <span class="cvt-label">Amount</span>+ <div class="cvt-row">+ <input+ class="cvt-amount"+ id="cvt-amount"+ type="text"+ inputmode="decimal"+ autocomplete="off"+ spellcheck="false"+ aria-label="Amount to convert"+ value="${esc(state.amount != null && Number.isFinite(state.amount) ? String(state.amount) : '')}"+ />+ <button type="button" class="cvt-asset" id="cvt-from-btn" aria-haspopup="listbox" aria-expanded="false">+ ${assetButtonInner(state.from, 'from')}+ </button>+ </div>+ <p class="cvt-subline" id="cvt-from-sub">${assetSubline(state.from)}</p>+ </div>++ <div class="cvt-swap-wrap">+ <button type="button" class="cvt-swap" id="cvt-swap" aria-label="Swap currencies" title="Swap">+ ${SWAP_ICON}+ </button>+ </div>++ <div class="cvt-side" data-side="to">+ <span class="cvt-label">Converted to</span>+ <div class="cvt-row">+ <div class="cvt-result" id="cvt-result" aria-live="polite"></div>+ <button type="button" class="cvt-asset" id="cvt-to-btn" aria-haspopup="listbox" aria-expanded="false">+ ${assetButtonInner(state.to, 'to')}+ </button>+ </div>+ <p class="cvt-subline" id="cvt-to-sub">${assetSubline(state.to)}</p>+ </div>++ <p class="cvt-rate" id="cvt-rate"></p>+ <p class="cv-updated" id="cvt-updated"></p>+ </div>`;++ wireCard();+ renderResult();+ renderRate();+ renderUpdated();+}++// Refresh just the dynamic bits without tearing down the input (keeps focus /+// caret while typing). Falls back to a full re-render if the card isn't mounted.+function refresh() {+ if (!$('cvt-result')) {+ renderCard();+ return;+ }+ const fb = $('cvt-from-btn');+ const tb = $('cvt-to-btn');+ if (fb) fb.innerHTML = assetButtonInner(state.from, 'from');+ if (tb) tb.innerHTML = assetButtonInner(state.to, 'to');+ const fs = $('cvt-from-sub');+ const ts = $('cvt-to-sub');+ if (fs) fs.innerHTML = assetSubline(state.from);+ if (ts) ts.innerHTML = assetSubline(state.to);+ renderResult();+ renderRate();+ renderUpdated();+}++function wireCard() {+ const input = $('cvt-amount');+ let debounce = null;+ input?.addEventListener('input', () => {+ const raw = input.value.replace(/,/g, '').trim();+ clearTimeout(debounce);+ debounce = setTimeout(() => {+ const n = raw === '' ? NaN : Number(raw);+ state.amount = Number.isFinite(n) && n >= 0 ? n : NaN;+ renderResult();+ }, 120);+ });+ // Select-all on focus so a tap-and-type replaces the value cleanly.+ input?.addEventListener('focus', () => input.select());++ $('cvt-swap')?.addEventListener('click', swap);+ $('cvt-from-btn')?.addEventListener('click', (e) => {+ e.stopPropagation();+ openPicker('from', e.currentTarget);+ });+ $('cvt-to-btn')?.addEventListener('click', (e) => {+ e.stopPropagation();+ openPicker('to', e.currentTarget);+ });+}++function swap() {+ const f = state.from;+ state.from = state.to;+ state.to = f;+ refresh();+}++// ── Asset resolution ──────────────────────────────────────────────────────────++function fiatAsset(code) {+ const f = state.rates?.byCode.get(code.toUpperCase());+ if (!f) return null;+ return { kind: 'fiat', code: f.code, name: f.name, unit: f.unit, per_btc: f.per_btc };+}++// Fetch a coin's live USD price and metadata → a crypto asset.+async function cryptoAsset(id, seed = {}) {+ const { coin } = await getJson(`/api/coin/detail?id=${encodeURIComponent(id)}`);+ const price = coin?.market?.price;+ return {+ kind: 'crypto',+ id: coin?.id || id,+ symbol: coin?.symbol || (seed.symbol || id).toUpperCase(),+ name: coin?.name || seed.name || id,+ image: coin?.image || seed.thumb || null,+ priceUSD: Number.isFinite(price) ? price : NaN,+ };+}++// Load a crypto into `side`, showing a spinner on that side while the price+// request is in flight. Seed carries the search-result metadata so the button+// shows the symbol/icon immediately.+async function selectCrypto(side, id, seed = {}) {+ state.pending[side] = true;+ // Optimistic placeholder so the button updates instantly.+ state[side] = {+ kind: 'crypto',+ id,+ symbol: (seed.symbol || id).toUpperCase(),+ name: seed.name || id,+ image: seed.thumb || null,+ priceUSD: NaN,+ };+ refresh();+ try {+ state[side] = await cryptoAsset(id, seed);+ } catch {+ // Keep the placeholder but mark price missing — the rate line shows the+ // "unavailable" copy rather than a wrong number.+ state[side] = { ...state[side], priceUSD: NaN };+ }+ state.pending[side] = false;+ refresh();+}++function selectFiat(side, code) {+ const a = fiatAsset(code);+ if (!a) return;+ state[side] = a;+ refresh();+}++// ── Asset picker (fiat + crypto search) ───────────────────────────────────────++const picker = { open: false, side: null, anchor: null, timer: null };++function currencyGlyph(f) {+ return f.unit || f.code.slice(0, 1);+}++function pickerFiatRows(query) {+ const q = query.toLowerCase();+ const rows = state.rates.list.filter(+ (f) => !q || f.code.toLowerCase().includes(q) || f.name.toLowerCase().includes(q),+ );+ if (!rows.length) return '';+ const items = rows+ .map(+ (f) => `+ <button type="button" class="cvt-pick-item" role="option" data-kind="fiat" data-code="${esc(f.code)}">+ <span class="cvt-pick-glyph fiat">${esc(currencyGlyph(f))}</span>+ <span class="cvt-pick-name">${esc(f.name)}</span>+ <span class="cvt-pick-code">${esc(f.code)}</span>+ </button>`,+ )+ .join('');+ return `<div class="cvt-pick-group"><p class="cvt-pick-head">Fiat currencies</p>${items}</div>`;+}++function pickerCryptoRows(coins) {+ if (!coins.length) return '';+ const items = coins+ .map(+ (c) => `+ <button type="button" class="cvt-pick-item" role="option" data-kind="crypto" data-id="${esc(c.id)}" data-symbol="${esc(c.symbol)}" data-name="${esc(c.name)}" data-thumb="${esc(c.thumb || '')}">+ ${c.thumb ? `<img src="${esc(c.thumb)}" alt="" width="22" height="22" data-no-dark-filter />` : `<span class="cvt-pick-glyph">${esc((c.symbol || '?').slice(0, 1))}</span>`}+ <span class="cvt-pick-name">${esc(c.name)}</span>+ <span class="cvt-pick-code">${esc(c.symbol)}</span>+ ${c.rank != null ? `<span class="cvt-pick-rank">#${c.rank}</span>` : ''}+ </button>`,+ )+ .join('');+ return `<div class="cvt-pick-group"><p class="cvt-pick-head">Cryptocurrencies</p>${items}</div>`;+}++function renderPicker({ query = '', coins = null, loading = false } = {}) {+ const el = $('cvt-picker');+ const fiatRows = pickerFiatRows(query);+ let cryptoSection;+ if (loading) {+ cryptoSection =+ '<div class="cvt-pick-note"><span class="cv-spinner" aria-hidden="true"></span>Searching coins…</div>';+ } else if (coins) {+ cryptoSection = coins.length+ ? pickerCryptoRows(coins)+ : `<div class="cvt-pick-note">No coins match “${esc(query)}”.</div>`;+ } else {+ cryptoSection =+ '<div class="cvt-pick-note">Type to search 10,000+ coins by name or symbol.</div>';+ }+ const body =+ !fiatRows && coins && !coins.length+ ? `<div class="cvt-pick-note">Nothing matches “${esc(query)}”.</div>`+ : `${fiatRows}${cryptoSection}`;++ el.innerHTML = `+ <div class="cvt-pick-search">+ <svg class="mag" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>+ <input type="text" id="cvt-pick-input" placeholder="Search currency or coin" autocomplete="off" spellcheck="false" aria-label="Search for a currency or coin" value="${esc(query)}" />+ </div>+ <div class="cvt-pick-list" id="cvt-pick-list" role="listbox">${body}</div>`;++ const input = $('cvt-pick-input');+ input.focus();+ input.addEventListener('input', onPickerInput);+ input.addEventListener('keydown', onPickerKey);+ wirePickerItems();+}++function wirePickerItems() {+ $('cvt-pick-list')+ ?.querySelectorAll('.cvt-pick-item')+ .forEach((btn) => btn.addEventListener('click', () => choosePickItem(btn)));+}++function choosePickItem(btn) {+ const side = picker.side;+ if (btn.dataset.kind === 'fiat') {+ selectFiat(side, btn.dataset.code);+ } else {+ selectCrypto(side, btn.dataset.id, {+ symbol: btn.dataset.symbol,+ name: btn.dataset.name,+ thumb: btn.dataset.thumb || null,+ });+ }+ closePicker();+}++function onPickerInput(e) {+ const q = e.target.value.trim();+ clearTimeout(picker.timer);+ if (!q) {+ renderPickerPreserveFocus({ query: '' });+ return;+ }+ // Show fiat matches + a loading state immediately, then fill crypto results.+ renderPickerPreserveFocus({ query: q, loading: true });+ picker.timer = setTimeout(async () => {+ try {+ const { coins } = await getJson(`/api/coin/markets?q=${encodeURIComponent(q)}`);+ // Guard against a stale response after the input changed again.+ if ($('cvt-pick-input')?.value.trim() === q) {+ renderPickerPreserveFocus({ query: q, coins });+ }+ } catch {+ if ($('cvt-pick-input')?.value.trim() === q) {+ renderPickerPreserveFocus({ query: q, coins: [] });+ }+ }+ }, 250);+}++// Re-render the list only (not the whole popover) so the search input keeps+// focus and caret while results stream in.+function renderPickerPreserveFocus(opts) {+ const list = $('cvt-pick-list');+ if (!list) return renderPicker(opts);+ const { query = '', coins = null, loading = false } = opts;+ const fiatRows = pickerFiatRows(query);+ let cryptoSection;+ if (loading) {+ cryptoSection =+ '<div class="cvt-pick-note"><span class="cv-spinner" aria-hidden="true"></span>Searching coins…</div>';+ } else if (coins) {+ cryptoSection = coins.length+ ? pickerCryptoRows(coins)+ : `<div class="cvt-pick-note">No coins match “${esc(query)}”.</div>`;+ } else {+ cryptoSection =+ '<div class="cvt-pick-note">Type to search 10,000+ coins by name or symbol.</div>';+ }+ list.innerHTML =+ !fiatRows && coins && !coins.length+ ? `<div class="cvt-pick-note">Nothing matches “${esc(query)}”.</div>`+ : `${fiatRows}${cryptoSection}`;+ wirePickerItems();+}++function onPickerKey(e) {+ if (e.key === 'Escape') {+ e.preventDefault();+ closePicker();+ picker.anchor?.focus();+ }+}++function positionPicker(anchor) {+ // Fixed position (viewport coords) so the offset parent is unambiguous — the+ // popover is a sibling of the card, not a child. Right-aligned under the+ // button and clamped to an 8px viewport gutter on both edges.+ const el = $('cvt-picker');+ const rect = anchor.getBoundingClientRect();+ el.style.top = `${rect.bottom + 6}px`;+ const right = Math.max(8, window.innerWidth - rect.right);+ el.style.right = `${right}px`;+ el.style.left = 'auto';+}++function openPicker(side, anchor) {+ picker.open = true;+ picker.side = side;+ picker.anchor = anchor;+ anchor.setAttribute('aria-expanded', 'true');+ const el = $('cvt-picker');+ el.hidden = false;+ positionPicker(anchor);+ renderPicker({ query: '' });+}++function closePicker() {+ if (!picker.open) return;+ picker.open = false;+ picker.anchor?.setAttribute('aria-expanded', 'false');+ const el = $('cvt-picker');+ el.hidden = true;+ el.innerHTML = '';+ picker.side = null;+ picker.anchor = null;+}++document.addEventListener('click', (e) => {+ if (!picker.open) return;+ if (e.target.closest('#cvt-picker') || e.target.closest('.cvt-asset')) return;+ closePicker();+});+window.addEventListener('resize', () => {+ if (picker.open && picker.anchor) positionPicker(picker.anchor);+});+// A fixed popover doesn't follow page scroll — keep it pinned to its anchor.+window.addEventListener(+ 'scroll',+ () => {+ if (picker.open && picker.anchor) positionPicker(picker.anchor);+ },+ { passive: true },+);++// ── Presets ───────────────────────────────────────────────────────────────────++const PRESETS = [+ {+ label: 'BTC → USD',+ from: { kind: 'crypto', id: 'bitcoin', symbol: 'BTC' },+ to: { kind: 'fiat', code: 'USD' },+ },+ {+ label: 'ETH → USD',+ from: { kind: 'crypto', id: 'ethereum', symbol: 'ETH' },+ to: { kind: 'fiat', code: 'USD' },+ },+ {+ label: 'SOL → USD',+ from: { kind: 'crypto', id: 'solana', symbol: 'SOL' },+ to: { kind: 'fiat', code: 'USD' },+ },+ {+ label: 'USD → BTC',+ from: { kind: 'fiat', code: 'USD' },+ to: { kind: 'crypto', id: 'bitcoin', symbol: 'BTC' },+ },+];++function renderPresets() {+ const el = $('cvt-presets');+ el.innerHTML = PRESETS.map(+ (p, i) =>+ `<button type="button" class="cvt-preset" data-preset="${i}">${esc(p.label)}</button>`,+ ).join('');+ el.querySelectorAll('[data-preset]').forEach((btn) =>+ btn.addEventListener('click', () => applyPreset(PRESETS[Number(btn.dataset.preset)])),+ );+}++async function applyPreset(p) {+ if (!state.rates) return;+ closePicker();+ state.amount = 1;+ const input = $('cvt-amount');+ if (input) input.value = '1';+ // Set both sides. Fiat resolves instantly; crypto resolves via detail fetch.+ if (p.from.kind === 'fiat') selectFiat('from', p.from.code);+ else selectCrypto('from', p.from.id, { symbol: p.from.symbol });+ if (p.to.kind === 'fiat') selectFiat('to', p.to.code);+ else selectCrypto('to', p.to.id, { symbol: p.to.symbol });+}++// ── Boot ──────────────────────────────────────────────────────────────────────++async function boot() {+ state.loading = true;+ state.error = null;+ renderCard();++ // Rates + the default coin's price, in parallel — the page needs both to show+ // its default BTC → USD conversion.+ const [ratesRes, btcRes] = await Promise.allSettled([+ getJson('/api/coin/rates'),+ cryptoAsset(DEFAULT_CRYPTO, { symbol: 'BTC', name: 'Bitcoin' }),+ ]);++ if (ratesRes.status !== 'fulfilled') {+ state.loading = false;+ state.error = 'rates';+ renderCard();+ return;+ }++ const { fiats, updated_at } = ratesRes.value;+ const byCode = new Map(fiats.map((f) => [f.code, f]));+ const usd = byCode.get('USD');+ if (!usd) {+ state.loading = false;+ state.error = 'rates';+ renderCard();+ return;+ }+ state.rates = { byCode, list: fiats, usdPerBtc: usd.per_btc, updated_at };++ // Default matchup: 1 BTC → USD. If the coin price failed, still show the+ // widget (the rate line degrades gracefully) so the page is never a dead end.+ state.from =+ btcRes.status === 'fulfilled'+ ? btcRes.value+ : {+ kind: 'crypto',+ id: DEFAULT_CRYPTO,+ symbol: 'BTC',+ name: 'Bitcoin',+ image: null,+ priceUSD: NaN,+ };+ state.to = fiatAsset('USD');+ state.amount = 1;+ state.loading = false;+ renderCard();+}++renderPresets();+boot();diff --git a/src/defi.css b/src/defi.cssnew file mode 100644index 000000000..6699b0824--- /dev/null+++ b/src/defi.css@@ -0,0 +1,92 @@+/*+ * /defi — DeFi TVL & protocols. Layered after coin-pages.css: reuses the cv-*+ * token system, cards, and table; this file only adds the stat grid, category+ * filter, and the small protocol-table affordances (chain chips, logo+ * fallback). Both themes inherit from the shared data-theme tokens.+ */++.defi-stat-grid {+ display: grid;+ gap: 1rem;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+}++/* Rows here are informational, not navigable — reset the shared table's+ pointer cursor so nothing signals a click target that doesn't exist. */+#defi-table .cv-table tbody tr {+ cursor: default;+}++/* Category filter cluster in the toolbar. */+.defi-filter {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ flex-wrap: wrap;+}+.defi-filter-label {+ font-size: 0.75rem;+ font-weight: 500;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--cv-text-3);+}+.defi-select {+ appearance: none;+ background: var(--cv-surface);+ color: var(--cv-text);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ font: inherit;+ font-size: 0.875rem;+ padding: 0.4375rem 2rem 0.4375rem 0.75rem;+ cursor: pointer;+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");+ background-repeat: no-repeat;+ background-position: right 0.5rem center;+ transition:+ border-color 0.15s,+ box-shadow 0.15s;+ max-width: 14rem;+}+.defi-select:hover {+ border-color: var(--cv-border-hover);+}+.defi-select:focus-visible {+ outline: none;+ border-color: var(--cv-accent);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 20%, transparent);+}++/* Chain list cell: keep the "+N" overflow marker subdued. */+.defi-chains .defi-more {+ color: var(--cv-text-3);+ font-size: 0.75rem;+ font-variant-numeric: tabular-nums;+}++/* Placeholder swatch when a protocol has no logo, so the name column stays+ aligned with logo rows. */+.defi-logo-fallback {+ display: inline-block;+ width: 24px;+ height: 24px;+ border-radius: 50%;+ background: var(--cv-surface-3);+ flex-shrink: 0;+}++/* The empty-state reset button reads as a link, matching cv-empty's anchors. */+.defi-reset {+ appearance: none;+ border: 0;+ background: transparent;+ color: var(--cv-accent);+ font: inherit;+ cursor: pointer;+ padding: 0;+}+.defi-reset:hover {+ color: var(--cv-accent-hover);+ text-decoration: underline;+}diff --git a/src/defi.js b/src/defi.jsnew file mode 100644index 000000000..a1f2232d7--- /dev/null+++ b/src/defi.js@@ -0,0 +1,287 @@+// /defi — DeFi TVL & protocols. Header stat cards (total TVL, protocol count,+// top category), a category filter, and a sortable table of the top protocols+// by TVL. Data comes from /api/defi/protocols (DeFiLlama, keyless), normalized+// server-side. Mirrors the /coins markets-table pattern: stat cards, sortable+// cv-table, designed loading / empty / error states.++import { formatUsd, formatPercent, escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── Stat cards ────────────────────────────────────────────────────────────++const ICONS = {+ lock: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>',+ layers: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>',+ tag: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.59 13.41 13.42 20.6a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>',+};++function statCard({ label, value, delta, deltaClass, icon }) {+ return `+ <div class="cv-stat-card">+ <div style="min-width:0">+ <p class="label">${esc(label)}</p>+ <p class="value cv-mono">${esc(value)}</p>+ ${delta ? `<p class="delta ${deltaClass || ''}">${esc(delta)}</p>` : ''}+ </div>+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>+ </div>`;+}++function topCategory(protocols) {+ const byCat = new Map();+ for (const p of protocols) {+ if (!p.category) continue;+ byCat.set(p.category, (byCat.get(p.category) || 0) + (p.tvl || 0));+ }+ let best = null;+ for (const [cat, tvl] of byCat) {+ if (!best || tvl > best.tvl) best = { cat, tvl };+ }+ return best;+}++function renderStats() {+ const el = $('defi-stats');+ const { total_tvl, protocol_count, protocols } = state;+ const top = topCategory(protocols);+ const cards = [+ statCard({ label: 'Total DeFi TVL', value: formatUsd(total_tvl), icon: 'lock' }),+ statCard({+ label: 'Protocols Tracked',+ value: protocol_count.toLocaleString('en-US'),+ icon: 'layers',+ }),+ ];+ if (top) {+ cards.push(+ statCard({+ label: 'Top Category',+ value: top.cat,+ delta: formatUsd(top.tvl),+ icon: 'tag',+ }),+ );+ }+ el.innerHTML = `<div class="defi-stat-grid">${cards.join('')}</div>`;+}++function statsSkeleton() {+ $('defi-stats').innerHTML =+ '<div class="defi-stat-grid">' ++ Array.from({ length: 3 }, () => '<div class="cv-skel" style="height:6rem"></div>').join(+ '',+ ) ++ '</div>';+}++// ── Category filter ───────────────────────────────────────────────────────++function populateCategories() {+ const sel = $('defi-category');+ if (!sel) return;+ const byCat = new Map();+ for (const p of state.protocols) {+ if (!p.category) continue;+ byCat.set(p.category, (byCat.get(p.category) || 0) + (p.tvl || 0));+ }+ const cats = [...byCat.entries()].sort((a, b) => b[1] - a[1]).map(([c]) => c);+ sel.innerHTML =+ '<option value="__all">All categories</option>' ++ cats.map((c) => `<option value="${esc(c)}">${esc(c)}</option>`).join('');+ sel.value = state.category;+ sel.addEventListener('change', () => {+ state.category = sel.value;+ renderTable();+ });+}++// ── Table ─────────────────────────────────────────────────────────────────++const COLUMNS = [+ { key: 'rank', label: '#', left: true, hide: 'hide-sm', num: true },+ { key: 'name', label: 'Protocol', left: true },+ { key: 'category', label: 'Category', left: true, hide: 'hide-md' },+ { key: 'chains', label: 'Chains', left: true, hide: 'hide-lg' },+ { key: 'tvl', label: 'TVL', num: true },+ { key: 'change_1d', label: '1d %', num: true },+ { key: 'change_7d', label: '7d %', hide: 'hide-md', num: true },+];++const state = {+ protocols: [],+ total_tvl: 0,+ protocol_count: 0,+ updated_at: 0,+ sortKey: 'tvl',+ sortDir: 'desc',+ category: '__all',+ loading: true,+ error: false,+};++function pctCell(v, extraClass = '') {+ if (v == null) return `<td class="pct dim ${extraClass}">—</td>`;+ const up = v >= 0;+ return `<td class="pct ${up ? 'cv-up' : 'cv-down'} ${extraClass}"><span aria-hidden="true">${up ? '▲' : '▼'}</span>${esc(formatPercent(v))}</td>`;+}++function chainsCell(chains) {+ if (!chains || !chains.length) return '<td class="left dim hide-lg">—</td>';+ const shown = chains+ .slice(0, 3)+ .map((c) => esc(c))+ .join(', ');+ const extra = chains.length > 3 ? ` <span class="defi-more">+${chains.length - 3}</span>` : '';+ return `<td class="left dim hide-lg defi-chains">${shown}${extra}</td>`;+}++function sortValue(p, key) {+ if (key === 'name') return (p.name || '').toLowerCase();+ if (key === 'category') return (p.category || '').toLowerCase();+ if (key === 'chains') return p.chain_count ?? 0;+ if (key === 'rank') return p.__rank ?? Infinity;+ return p[key] ?? -Infinity;+}++function visibleProtocols() {+ let rows =+ state.category === '__all'+ ? state.protocols+ : state.protocols.filter((p) => p.category === state.category);+ // Rank is by TVL across the filtered set, independent of the active sort.+ rows = [...rows].sort((a, b) => (b.tvl ?? 0) - (a.tvl ?? 0));+ rows.forEach((p, i) => (p.__rank = i + 1));++ const { sortKey, sortDir } = state;+ const sorted = [...rows].sort((a, b) => {+ const va = sortValue(a, sortKey);+ const vb = sortValue(b, sortKey);+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;+ return sortDir === 'asc' ? cmp : -cmp;+ });+ return sorted;+}++function renderTable() {+ const el = $('defi-table');++ if (state.loading) {+ el.innerHTML =+ '<div class="cv-table-wrap" style="padding:0.75rem">' ++ Array.from(+ { length: 12 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('') ++ '</div>';+ return;+ }+ if (state.error) {+ el.innerHTML =+ '<div class="cv-empty">DeFi data is temporarily unavailable. <a href="/defi">Try again</a> shortly.</div>';+ return;+ }++ const rows = visibleProtocols();+ if (!rows.length) {+ el.innerHTML = `<div class="cv-empty">No protocols in “${esc(state.category)}”. <button type="button" class="defi-reset">Show all categories</button></div>`;+ el.querySelector('.defi-reset')?.addEventListener('click', () => {+ state.category = '__all';+ const sel = $('defi-category');+ if (sel) sel.value = '__all';+ renderTable();+ });+ return;+ }++ const head = COLUMNS.map((col) => {+ const active = col.key === state.sortKey;+ const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ }).join('');++ const body = rows+ .map((p) => {+ return `+ <tr>+ <td class="rank hide-sm cv-mono">${p.__rank}</td>+ <td class="left name-cell"><span class="inner">+ ${p.logo ? `<img src="${esc(p.logo)}" alt="" loading="lazy" width="24" height="24" data-no-dark-filter />` : '<span class="defi-logo-fallback" aria-hidden="true"></span>'}+ <span class="nm">${esc(p.name)}</span>+ ${p.symbol ? `<span class="sym">${esc(p.symbol)}</span>` : ''}+ </span></td>+ <td class="left dim hide-md">${p.category ? esc(p.category) : '—'}</td>+ ${chainsCell(p.chains)}+ <td class="price">${esc(formatUsd(p.tvl))}</td>+ ${pctCell(p.change_1d)}+ ${pctCell(p.change_7d, 'hide-md')}+ </tr>`;+ })+ .join('');++ el.innerHTML = `+ <div class="cv-table-wrap">+ <table class="cv-table">+ <thead><tr>${head}</tr></thead>+ <tbody>${body}</tbody>+ </table>+ </div>`;++ el.querySelectorAll('th[data-key]').forEach((th) => {+ const activate = () => {+ const key = th.dataset.key;+ if (key === state.sortKey) {+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';+ } else {+ state.sortKey = key;+ state.sortDir = key === 'name' || key === 'category' ? 'asc' : 'desc';+ }+ renderTable();+ };+ th.addEventListener('click', activate);+ th.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ activate();+ }+ });+ });+}++// ── Boot ──────────────────────────────────────────────────────────────────++async function load() {+ statsSkeleton();+ renderTable();+ try {+ const data = await getJson('/api/defi/protocols');+ state.protocols = Array.isArray(data.protocols) ? data.protocols : [];+ state.total_tvl = data.total_tvl || 0;+ state.protocol_count = data.protocol_count || state.protocols.length;+ state.updated_at = data.updated_at || Date.now();+ state.loading = false;+ state.error = false;+ renderStats();+ populateCategories();+ renderTable();+ $('defi-updated').textContent =+ `Top ${state.protocols.length} protocols by TVL · Data: DeFiLlama · updated ${new Date(state.updated_at).toLocaleTimeString('en-US')}`;+ } catch {+ state.loading = false;+ state.error = true;+ $('defi-stats').innerHTML = '';+ renderTable();+ }+}++load();diff --git a/src/derivatives.css b/src/derivatives.cssnew file mode 100644index 000000000..d8c3fb6ae--- /dev/null+++ b/src/derivatives.css@@ -0,0 +1,44 @@+/*+ * /derivatives — feature styles layered on top of /src/coin-pages.css.+ * Reuses the shared cv-* table, card, state, and hm-seg (segmented filter)+ * system; adds only the index badge unique to this page.+ */++/* Index badge on each perp row (BTC / ETH / SOL / …). */+.dv-index {+ display: inline-flex;+ align-items: center;+ border: 1px solid var(--cv-border);+ background: var(--cv-surface-2);+ color: var(--cv-text-2);+ border-radius: var(--cv-radius-sm);+ padding: 0.0625rem 0.375rem;+ font-family: var(--cv-font-mono);+ font-size: 0.75rem;+ font-weight: 600;+ letter-spacing: 0.02em;+ text-transform: uppercase;+}++/* Filter chips sit just above the table. */+#dv-filters {+ margin-bottom: 1rem;+ flex-wrap: wrap;+}+/* .hm-seg's `display: inline-flex` beats the UA `[hidden]` rule, so an+ author rule is needed to actually hide the chip group before/without data. */+#dv-filters[hidden] {+ display: none;+}++/* Derivatives rows are informational, not links — no pointer cursor. */+.dv-table tbody tr {+ cursor: default;+}+.dv-table .name-cell .nm {+ max-width: 200px;+ overflow: hidden;+ text-overflow: ellipsis;+ display: inline-block;+ vertical-align: middle;+}diff --git a/src/derivatives.js b/src/derivatives.jsnew file mode 100644index 000000000..eae30b8be--- /dev/null+++ b/src/derivatives.js@@ -0,0 +1,274 @@+// /derivatives — perpetual futures markets, part of the three.ws Markets+// surface. A sortable table of live perps across the major exchanges: price,+// 24h move, funding rate, open interest, and 24h volume, filterable by the+// underlying index. Real data via /api/coin/derivatives — never mocked. Mirrors+// the /coins market-table pattern (src/coins-index.js).++import { formatUsd, formatPrice, formatPercent, escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── Header stat cards ─────────────────────────────────────────────────────────++const ICONS = {+ layers: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>',+ vault: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="12" cy="12" r="3"/><path d="M12 9V6"/><path d="m14.5 10.5 2-2"/><path d="M15 12h3"/></svg>',+ bars: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/></svg>',+};++function statCard({ label, value, icon }) {+ return `+ <div class="cv-stat-card">+ <div style="min-width:0">+ <p class="label">${esc(label)}</p>+ <p class="value cv-mono">${esc(value)}</p>+ </div>+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>+ </div>`;+}++function renderStats() {+ const el = $('dv-stats');+ if (!state.tickers.length) {+ el.innerHTML = '';+ return;+ }+ const totalOi = state.tickers.reduce((s, t) => s + (t.open_interest ?? 0), 0);+ const totalVol = state.tickers.reduce((s, t) => s + (t.volume_24h ?? 0), 0);+ const cards = [+ statCard({+ label: 'Perpetual Markets',+ value: state.tickers.length.toLocaleString('en-US'),+ icon: 'layers',+ }),+ statCard({ label: 'Total Open Interest', value: formatUsd(totalOi), icon: 'vault' }),+ statCard({ label: 'Total 24h Volume', value: formatUsd(totalVol), icon: 'bars' }),+ ];+ el.innerHTML = `<div style="display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(200px,1fr))">${cards.join('')}</div>`;+}++// ── Index filter chips ────────────────────────────────────────────────────────++// Well-known indexes float to the front; the rest follow by market count.+const INDEX_PRIORITY = ['BTC', 'ETH', 'SOL'];+const MAX_CHIPS = 9;++function buildFilters() {+ const counts = new Map();+ for (const t of state.tickers) {+ if (!t.index_id) continue;+ counts.set(t.index_id, (counts.get(t.index_id) || 0) + 1);+ }+ const indexes = [...counts.keys()].sort((a, b) => {+ const pa = INDEX_PRIORITY.indexOf(a);+ const pb = INDEX_PRIORITY.indexOf(b);+ if (pa !== -1 || pb !== -1) {+ if (pa === -1) return 1;+ if (pb === -1) return -1;+ return pa - pb;+ }+ return counts.get(b) - counts.get(a);+ });+ state.indexes = indexes.slice(0, MAX_CHIPS);++ const el = $('dv-filters');+ if (state.indexes.length < 2) {+ el.hidden = true;+ return;+ }+ const chips = [{ id: 'all', label: 'All' }, ...state.indexes.map((id) => ({ id, label: id }))];+ el.innerHTML = chips+ .map(+ (c) =>+ `<button type="button" data-index="${esc(c.id)}" aria-pressed="${c.id === state.filter}">${esc(c.label)}</button>`,+ )+ .join('');+ el.hidden = false;+ el.querySelectorAll('button[data-index]').forEach((btn) => {+ btn.addEventListener('click', () => {+ state.filter = btn.dataset.index;+ el.querySelectorAll('button[data-index]').forEach((b) => {+ b.setAttribute('aria-pressed', b.dataset.index === state.filter ? 'true' : 'false');+ });+ renderTable();+ });+ });+}++// ── Table ─────────────────────────────────────────────────────────────────────++const COLUMNS = [+ { key: 'market', label: 'Market', left: true },+ { key: 'symbol', label: 'Symbol', left: true, hide: 'hide-sm' },+ { key: 'index_id', label: 'Index', left: true },+ { key: 'price', label: 'Price', num: true },+ { key: 'change_24h', label: '24h %', num: true },+ { key: 'funding_rate', label: 'Funding', num: true },+ { key: 'open_interest', label: 'Open Interest', hide: 'hide-md', num: true },+ { key: 'volume_24h', label: 'Vol (24h)', num: true },+];++const state = {+ tickers: [],+ indexes: [],+ filter: 'all',+ sortKey: 'volume_24h',+ sortDir: 'desc',+};++function pctCell(v) {+ if (v == null) return '<td class="pct dim">—</td>';+ const up = v >= 0;+ return `<td class="pct ${up ? 'cv-up' : 'cv-down'}"><span aria-hidden="true">${up ? '▲' : '▼'}</span>${esc(formatPercent(v))}</td>`;+}++// Funding rate from CoinGecko is already a percentage value — show 4 decimals.+function fundingCell(v) {+ if (v == null) return '<td class="pct dim">—</td>';+ const up = v >= 0;+ return `<td class="pct ${up ? 'cv-up' : 'cv-down'}">${v >= 0 ? '+' : ''}${esc(v.toFixed(4))}%</td>`;+}++function sortValue(t, key) {+ if (key === 'market' || key === 'symbol' || key === 'index_id') {+ return String(t[key] || '').toLowerCase(); // blanks sort last+ }+ return t[key] ?? -Infinity;+}++function filteredTickers() {+ if (state.filter === 'all') return state.tickers;+ return state.tickers.filter((t) => t.index_id === state.filter);+}++function sortedTickers() {+ const copy = filteredTickers();+ const { sortKey, sortDir } = state;+ const out = [...copy];+ out.sort((a, b) => {+ const va = sortValue(a, sortKey);+ const vb = sortValue(b, sortKey);+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;+ return sortDir === 'asc' ? cmp : -cmp;+ });+ return out;+}++function renderTable() {+ const el = $('dv-market');+ if (!state.tickers.length) {+ el.innerHTML =+ '<div class="cv-empty">Derivatives data is temporarily unavailable. Please try again shortly.</div>';+ return;+ }++ const rows = sortedTickers();+ if (!rows.length) {+ el.innerHTML = `<div class="cv-empty">No perpetual markets for ${esc(state.filter)}. <a href="#" id="dv-clear">Clear filter</a></div>`;+ $('dv-clear')?.addEventListener('click', (e) => {+ e.preventDefault();+ state.filter = 'all';+ buildFilters();+ renderTable();+ });+ return;+ }++ const head = COLUMNS.map((col) => {+ const active = col.key === state.sortKey;+ const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ }).join('');++ const body = rows+ .map(+ (t) => `+ <tr>+ <td class="left name-cell"><span class="nm">${esc(t.market)}</span></td>+ <td class="left dim hide-sm cv-mono">${esc(t.symbol || '—')}</td>+ <td class="left">${t.index_id ? `<span class="dv-index">${esc(t.index_id)}</span>` : '<span class="dim">—</span>'}</td>+ <td class="price">${esc(formatPrice(t.price))}</td>+ ${pctCell(t.change_24h)}+ ${fundingCell(t.funding_rate)}+ <td class="dim hide-md">${esc(formatUsd(t.open_interest))}</td>+ <td class="dim">${esc(formatUsd(t.volume_24h))}</td>+ </tr>`,+ )+ .join('');++ el.innerHTML = `+ <div class="cv-table-wrap">+ <table class="cv-table dv-table">+ <thead><tr>${head}</tr></thead>+ <tbody>${body}</tbody>+ </table>+ </div>`;++ el.querySelectorAll('th[data-key]').forEach((th) => {+ const activate = () => {+ const key = th.dataset.key;+ if (key === state.sortKey) {+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';+ } else {+ state.sortKey = key;+ // Text columns default A→Z; numeric columns default high→low.+ state.sortDir =+ key === 'market' || key === 'symbol' || key === 'index_id' ? 'asc' : 'desc';+ }+ renderTable();+ };+ th.addEventListener('click', activate);+ th.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ activate();+ }+ });+ });+}++// ── Boot ──────────────────────────────────────────────────────────────────────++function renderSkeleton() {+ $('dv-stats').innerHTML =+ '<div style="display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(200px,1fr))">' ++ Array.from({ length: 3 }, () => '<div class="cv-skel" style="height:6rem"></div>').join(+ '',+ ) ++ '</div>';+ $('dv-market').innerHTML =+ '<div class="cv-table-wrap" style="padding:0.75rem">' ++ Array.from(+ { length: 12 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('') ++ '</div>';+}++async function load() {+ renderSkeleton();+ try {+ const data = await getJson('/api/coin/derivatives');+ state.tickers = Array.isArray(data.tickers) ? data.tickers : [];+ $('dv-updated').textContent =+ `Updated ${new Date(data.updated_at || Date.now()).toLocaleTimeString('en-US')} · source: CoinGecko`;+ } catch {+ state.tickers = [];+ $('dv-updated').textContent = '';+ }+ renderStats();+ buildFilters();+ renderTable();+}++load();diff --git a/src/element.js b/src/element.jsindex d2c42b1fe..8b57d0919 100644--- a/src/element.js+++ b/src/element.js@@ -28,6 +28,12 @@ import { log } from './shared/log.js';const MODES = ['inline', 'floating', 'section', 'fullscreen'];+// Zero-config free brain: routed through the we-pay `/api/llm/anthropic` proxy+// (src/runtime/providers.js), which resolves this id to OpenRouter's free tier.+// `brain="free"` gets any ad-hoc embed talking with no API key, no backend code,+// and no per-token cost to the embedder.+const FREE_BRAIN_MODEL = 'meta-llama/llama-3.3-70b-instruct:free';+// ── WebGL context budget ────────────────────────────────────────────────// Browsers cap the number of simultaneous WebGL contexts (~16 in Chrome).// Each booted <agent-3d> holds one (two when axes are shown) for its whole@@ -2057,13 +2063,28 @@ class Agent3DElement extends HTMLElement {}}+ // `brain="free"` resolves to the host-paid free model; any other value is+ // passed through as a literal model id (paid Claude, a specific Groq/+ // OpenRouter id, etc.); no attribute at all keeps the agent silent.+ _brainConfig(instructionsAttr) {+ const brainAttr = this.getAttribute('brain');+ if (!brainAttr) return { provider: 'none' };+ const model = brainAttr.trim().toLowerCase() === 'free' ? FREE_BRAIN_MODEL : brainAttr;+ return {+ provider: 'anthropic',+ model,+ instructions: instructionsAttr || 'You are an embodied three.ws.',+ };+ }+_defaultFallbackManifest() {+ const instructionsAttr = this.getAttribute('instructions');return {spec: 'agent-manifest/0.1',_baseURI: '',name: this.getAttribute('name') || 'Agent',body: { uri: 'https://three.ws/avatars/default.glb', format: 'gltf-binary' },- brain: { provider: 'none' },+ brain: this._brainConfig(instructionsAttr),voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },skills: [],};@@ -2094,12 +2115,13 @@ class Agent3DElement extends HTMLElement {// them as if `body=` had been set so users don't need to know the// distinction.if (/\.(glb|gltf)(\?|$)/i.test(src)) {+ const instructionsAttr = this.getAttribute('instructions');return {spec: 'agent-manifest/0.1',_baseURI: '',name: this.getAttribute('name') || 'Agent',body: { uri: src, format: 'gltf-binary' },- brain: { provider: 'none' },+ brain: this._brainConfig(instructionsAttr),voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },skills: [],};@@ -2156,11 +2178,7 @@ class Agent3DElement extends HTMLElement {_baseURI: '',name: this.getAttribute('name') || 'Agent',body: { uri: body, format: 'gltf-binary' },- brain: {- provider: this.getAttribute('brain') ? 'anthropic' : 'none',- model: this.getAttribute('brain') || undefined,- instructions: instructionsAttr || 'You are an embodied three.ws.',- },+ brain: this._brainConfig(instructionsAttr),instructions: instructionsAttr || 'You are an embodied three.ws.',voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },skills: (this.getAttribute('skills') || '')diff --git a/src/exchanges.css b/src/exchanges.cssnew file mode 100644index 000000000..a2b95dc7a--- /dev/null+++ b/src/exchanges.css@@ -0,0 +1,85 @@+/*+ * /exchanges — feature styles layered on top of /src/coin-pages.css.+ * Reuses the shared cv-* table, card, and state system; adds only the+ * trust-score badge and the link-out affordance unique to this page.+ */++/* Trust-score badge: a compact 0–10 pill, colored by band. */+.ex-trust {+ display: inline-flex;+ align-items: baseline;+ gap: 0.0625rem;+ border-radius: 999px;+ padding: 0.1875rem 0.5rem;+ font-family: var(--cv-font-mono);+ font-size: 0.8125rem;+ font-weight: 600;+ line-height: 1;+ font-variant-numeric: tabular-nums;+ border: 1px solid transparent;+}+.ex-trust .of {+ font-size: 0.625rem;+ font-weight: 500;+ opacity: 0.7;+}+.ex-trust-hi {+ color: var(--cv-green);+ background: var(--cv-green-soft);+ border-color: color-mix(in srgb, var(--cv-green) 30%, transparent);+}+.ex-trust-mid {+ color: var(--cv-text-2);+ background: var(--cv-surface-2);+ border-color: var(--cv-border);+}+.ex-trust-lo {+ color: var(--cv-red);+ background: var(--cv-red-soft);+ border-color: color-mix(in srgb, var(--cv-red) 30%, transparent);+}+.ex-trust-na {+ color: var(--cv-text-3);+ background: var(--cv-surface-2);+ border-color: var(--cv-border);+ font-family: var(--cv-font-sans);+ font-weight: 500;+}++/* Rows open the venue — the whole row is the affordance, so no per-row pointer+ surprise; keep the shared hover but make the intent explicit. */+.ex-table tbody tr[data-href] {+ cursor: pointer;+}+.ex-table tbody tr:not([data-href]) {+ cursor: default;+}++/* Link-out column: a subtle icon that brightens to the accent on hover/focus. */+.ex-table .ex-link-cell {+ width: 1px;+ padding-left: 0.5rem;+ padding-right: 1rem;+}+.ex-link {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ border-radius: var(--cv-radius);+ color: var(--cv-text-3);+ transition:+ color 0.15s,+ background 0.15s;+}+.ex-link:hover,+.ex-link:focus-visible {+ color: var(--cv-accent);+ background: var(--cv-surface-2);+ outline: none;+}+.ex-link:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 1px;+}diff --git a/src/exchanges.js b/src/exchanges.jsnew file mode 100644index 000000000..1a9f9f140--- /dev/null+++ b/src/exchanges.js@@ -0,0 +1,226 @@+// /exchanges — the top crypto exchanges, part of the three.ws Markets surface.+// A sortable table ranked by CoinGecko trust score / 24h volume, with a small+// colored trust-score badge, a USD volume figure (BTC fallback), country, launch+// year, and a link-out to each venue. Real data via /api/coin/exchanges — never+// mocked. Mirrors the /coins market-table pattern (src/coins-index.js).++import { formatUsd, escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── Header stat cards ─────────────────────────────────────────────────────────++const ICONS = {+ building:+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="2" width="16" height="20" rx="2"/><path d="M9 22v-4h6v4"/><path d="M8 6h.01"/><path d="M16 6h.01"/><path d="M12 6h.01"/><path d="M12 10h.01"/><path d="M12 14h.01"/><path d="M16 10h.01"/><path d="M16 14h.01"/><path d="M8 10h.01"/><path d="M8 14h.01"/></svg>',+ bars: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/></svg>',+};++function statCard({ label, value, icon }) {+ return `+ <div class="cv-stat-card">+ <div style="min-width:0">+ <p class="label">${esc(label)}</p>+ <p class="value cv-mono">${esc(value)}</p>+ </div>+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>+ </div>`;+}++function renderStats() {+ const el = $('ex-stats');+ if (!state.exchanges.length) {+ el.innerHTML = '';+ return;+ }+ const totalUsd = state.exchanges.reduce((s, e) => s + (e.volume_24h_usd ?? 0), 0);+ const totalBtc = state.exchanges.reduce((s, e) => s + (e.volume_24h_btc ?? 0), 0);+ const volValue =+ state.btcUsd != null && totalUsd > 0+ ? formatUsd(totalUsd)+ : `${totalBtc.toLocaleString('en-US', { maximumFractionDigits: 0 })} BTC`;+ const cards = [+ statCard({+ label: 'Exchanges Tracked',+ value: state.exchanges.length.toLocaleString('en-US'),+ icon: 'building',+ }),+ statCard({ label: 'Combined 24h Volume', value: volValue, icon: 'bars' }),+ ];+ el.innerHTML = `<div style="display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(200px,1fr))">${cards.join('')}</div>`;+}++// ── Table ─────────────────────────────────────────────────────────────────────++const COLUMNS = [+ { key: 'rank', label: '#', left: true, num: true },+ { key: 'name', label: 'Exchange', left: true },+ { key: 'trust_score', label: 'Trust Score', num: true },+ { key: 'volume', label: '24h Volume', num: true },+ { key: 'country', label: 'Country', hide: 'hide-md', left: true },+ { key: 'year_established', label: 'Year', hide: 'hide-lg', num: true },+];++const state = { exchanges: [], btcUsd: null, sortKey: 'rank', sortDir: 'asc' };++function trustBadge(score) {+ if (score == null) return '<span class="ex-trust ex-trust-na">n/a</span>';+ const cls = score >= 8 ? 'ex-trust-hi' : score >= 5 ? 'ex-trust-mid' : 'ex-trust-lo';+ return `<span class="ex-trust ${cls}">${esc(score.toFixed(0))}<span class="of">/10</span></span>`;+}++function volumeCell(e) {+ if (e.volume_24h_usd != null) return esc(formatUsd(e.volume_24h_usd));+ if (e.volume_24h_btc != null) {+ return `${e.volume_24h_btc.toLocaleString('en-US', { maximumFractionDigits: 0 })} BTC`;+ }+ return '—';+}++const LINK_ICON =+ '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';++function sortValue(e, key) {+ if (key === 'name') return (e.name || '').toLowerCase();+ if (key === 'country') return (e.country || '').toLowerCase(); // blanks sort last+ if (key === 'rank') return e.trust_score_rank ?? Infinity;+ if (key === 'volume') return e.volume_24h_usd ?? e.volume_24h_btc ?? -Infinity;+ if (key === 'trust_score') return e.trust_score ?? -Infinity;+ if (key === 'year_established') return e.year_established ?? -Infinity;+ return 0;+}++function sortedExchanges() {+ const copy = [...state.exchanges];+ const { sortKey, sortDir } = state;+ copy.sort((a, b) => {+ const va = sortValue(a, sortKey);+ const vb = sortValue(b, sortKey);+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;+ return sortDir === 'asc' ? cmp : -cmp;+ });+ return copy;+}++function renderTable() {+ const el = $('ex-market');+ if (!state.exchanges.length) {+ el.innerHTML =+ '<div class="cv-empty">Exchange data is temporarily unavailable. Please try again shortly.</div>';+ return;+ }++ const head = COLUMNS.map((col) => {+ const active = col.key === state.sortKey;+ const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ }).join('');++ const rows = sortedExchanges()+ .map((e) => {+ const rowAttrs = e.url ? ` data-href="${esc(e.url)}"` : '';+ return `+ <tr${rowAttrs}>+ <td class="rank cv-mono left">${e.trust_score_rank ?? '—'}</td>+ <td class="left name-cell"><span class="inner">+ ${e.image ? `<img src="${esc(e.image)}" alt="" loading="lazy" width="24" height="24" data-no-dark-filter />` : ''}+ <span class="nm">${esc(e.name)}</span>+ </span></td>+ <td>${trustBadge(e.trust_score)}</td>+ <td class="price">${volumeCell(e)}</td>+ <td class="left dim hide-md">${esc(e.country || '—')}</td>+ <td class="dim hide-lg cv-mono">${e.year_established ?? '—'}</td>+ <td class="ex-link-cell">${+ e.url+ ? `<a href="${esc(e.url)}" class="ex-link" target="_blank" rel="noopener noreferrer" aria-label="Open ${esc(e.name)} (opens in a new tab)">${LINK_ICON}</a>`+ : ''+ }</td>+ </tr>`;+ })+ .join('');++ el.innerHTML = `+ <div class="cv-table-wrap">+ <table class="cv-table ex-table">+ <thead><tr>${head}<th aria-hidden="true"></th></tr></thead>+ <tbody>${rows}</tbody>+ </table>+ </div>`;++ el.querySelectorAll('th[data-key]').forEach((th) => {+ const activate = () => {+ const key = th.dataset.key;+ if (key === state.sortKey) {+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';+ } else {+ state.sortKey = key;+ // Text columns default A→Z; numeric columns default high→low.+ state.sortDir =+ key === 'name' || key === 'country' || key === 'rank' ? 'asc' : 'desc';+ }+ renderTable();+ };+ th.addEventListener('click', activate);+ th.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ activate();+ }+ });+ });++ // Whole row opens the exchange in a new tab; the icon link inside stays a real+ // anchor for middle-click / keyboard users.+ el.querySelectorAll('tr[data-href]').forEach((tr) => {+ tr.addEventListener('click', (e) => {+ if (e.target.closest('a')) return;+ window.open(tr.dataset.href, '_blank', 'noopener');+ });+ });+}++// ── Boot ──────────────────────────────────────────────────────────────────────++function renderSkeleton() {+ $('ex-stats').innerHTML =+ '<div style="display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(200px,1fr))">' ++ Array.from({ length: 2 }, () => '<div class="cv-skel" style="height:6rem"></div>').join(+ '',+ ) ++ '</div>';+ $('ex-market').innerHTML =+ '<div class="cv-table-wrap" style="padding:0.75rem">' ++ Array.from(+ { length: 12 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('') ++ '</div>';+}++async function load() {+ renderSkeleton();+ try {+ const data = await getJson('/api/coin/exchanges');+ state.exchanges = Array.isArray(data.exchanges) ? data.exchanges : [];+ state.btcUsd = data.btc_usd ?? null;+ $('ex-updated').textContent =+ `Updated ${new Date(data.updated_at || Date.now()).toLocaleTimeString('en-US')} · source: CoinGecko`;+ } catch {+ state.exchanges = [];+ $('ex-updated').textContent = '';+ }+ renderStats();+ renderTable();+}++load();diff --git a/src/game/camera-modes.js b/src/game/camera-modes.jsnew file mode 100644index 000000000..a693b252b--- /dev/null+++ b/src/game/camera-modes.js@@ -0,0 +1,155 @@+// Camera modes — a shared 4-mode chase camera (follow / cinematic / firstperson+// / topdown), extracted from `/walk` (W01: open-world foundation) so `/play`+// gets the same camera system instead of a second, divergent implementation.+// See prompts/agent-briefs/W-world-online/PORT-CHECKLIST.md P1.4.+//+// `computeCameraForMode()` is the pure per-frame pose math (no allocation+// beyond a shared scratch, no side effects) — both `walk.js` and+// `coincommunities.js` can call it directly for a one-shot pose. It is a+// faithful port of the FOV table / orbit math walk.js carried inline; 'follow'+// matches the orbit formula `/play` already used so switching to this module+// doesn't shift the default view.+//+// `createCameraModeController()` wraps it with mode cycling, localStorage+// persistence, and a cross-fade transition so a mode swap doesn't pop.++import { Vector3 } from 'three';++export const CAMERA_MODES = ['follow', 'cinematic', 'firstperson', 'topdown'];++export const CAMERA_MODE_LABELS = {+ follow: 'Follow',+ cinematic: 'Cinematic',+ firstperson: 'First Person',+ topdown: 'Top Down',+};++export const CAMERA_MODE_FOV = { follow: 50, cinematic: 35, firstperson: 75, topdown: 50 };++const CINEMATIC_ORBIT_SPEED = 0.15; // rad/s — the auto-orbit's angular speed+const CINEMATIC_RADIUS_MULT = 1.8; // × avatar height, scaled further by zoom+const CINEMATIC_HEIGHT_MULT = 0.7; // × avatar height+const FP_EYE_HEIGHT_MULT = 0.9; // fraction of avatar height for the eye position+const TOPDOWN_HEIGHT = 18; // metres straight above the avatar++const TRANSITION_DUR = 0.5; // seconds a mode swap cross-fades over++// Hot-path scratch — computeCameraForMode runs every frame; reuse instead of+// allocating fresh Vector3s per call. The caller must read pos/look before the+// next call (or copy them out) — they're not retained across frames.+const _pos = new Vector3();+const _look = new Vector3();+const _offset = new Vector3();+const _fwd = new Vector3();+const _result = { pos: _pos, look: _look };++/**+ * Pure per-frame camera pose for one mode.+ *+ * @param {string} mode one of CAMERA_MODES (unknown modes fall back to 'follow')+ * @param {import('three').Vector3} avatarPos world position (feet/base)+ * @param {number} avatarHeight metres — drives eye height / cinematic framing+ * @param {{yaw?:number, pitch?:number, dist?:number, cinematicAngle?:number, lookOffsetY?:number}} [orbit]+ * yaw/pitch/dist are the player's mouse-drag orbit (also the cinematic+ * distance/zoom multiplier); cinematicAngle is the slow auto-orbit angle in+ * radians — advance it via the controller's tick(dt) or roll your own.+ * @returns {{pos:import('three').Vector3, look:import('three').Vector3}} shared scratch+ */+export function computeCameraForMode(mode, avatarPos, avatarHeight, orbit = {}) {+ const { yaw = 0, pitch = 0.5, dist = 9, cinematicAngle = 0, lookOffsetY = 1.4 } = orbit;+ const height = avatarHeight || 1.8;+ const pos = _pos, look = _look;+ if (mode === 'cinematic') {+ const r = height * CINEMATIC_RADIUS_MULT * (dist / 9);+ const h = height * CINEMATIC_HEIGHT_MULT;+ pos.set(+ avatarPos.x + Math.cos(cinematicAngle) * r,+ avatarPos.y + h + 0.8,+ avatarPos.z + Math.sin(cinematicAngle) * r,+ );+ look.set(avatarPos.x, avatarPos.y + lookOffsetY, avatarPos.z);+ } else if (mode === 'firstperson') {+ const eyeH = height * FP_EYE_HEIGHT_MULT;+ pos.set(avatarPos.x, avatarPos.y + eyeH, avatarPos.z);+ _fwd.set(Math.sin(yaw), 0, Math.cos(yaw));+ look.copy(pos).addScaledVector(_fwd, 5);+ look.y -= 0.15; // slight downward gaze+ } else if (mode === 'topdown') {+ pos.set(avatarPos.x, avatarPos.y + TOPDOWN_HEIGHT, avatarPos.z + 0.01);+ look.set(avatarPos.x, avatarPos.y, avatarPos.z);+ } else {+ // 'follow' (default) — matches /play's original fixed orbit exactly.+ const cp = Math.cos(pitch), sp = Math.sin(pitch);+ _offset.set(Math.sin(yaw) * cp * dist, sp * dist + 1.4, Math.cos(yaw) * cp * dist);+ pos.set(avatarPos.x - _offset.x, avatarPos.y + _offset.y, avatarPos.z - _offset.z);+ look.set(avatarPos.x, avatarPos.y + lookOffsetY, avatarPos.z);+ }+ return _result;+}++/**+ * A small stateful wrapper: current mode (persisted), cycling, first-person+ * avatar-hide hint, and a cross-fade so switching modes glides instead of+ * popping. Callers own the Camera and the avatar visibility toggle.+ *+ * @param {{ storageKey?:string, initialMode?:string, onChange?:(mode:string)=>void }} [opts]+ */+export function createCameraModeController({ storageKey = 'camera-mode', initialMode, onChange } = {}) {+ let mode = CAMERA_MODES.includes(initialMode) ? initialMode : 'follow';+ try {+ const saved = storageKey && localStorage.getItem(storageKey);+ if (saved && CAMERA_MODES.includes(saved)) mode = saved;+ } catch { /* storage blocked (private mode / sandboxed iframe) */ }++ let cinematicAngle = 0;+ let transition = 0; // 0 = settled, >0 = mid cross-fade+ const from = { pos: new Vector3(), fov: CAMERA_MODE_FOV[mode] };+ let toFov = CAMERA_MODE_FOV[mode];++ function setMode(next, camera) {+ if (!CAMERA_MODES.includes(next) || next === mode) return;+ if (camera) { from.pos.copy(camera.position); from.fov = camera.fov; }+ mode = next;+ toFov = CAMERA_MODE_FOV[mode];+ transition = TRANSITION_DUR;+ try { if (storageKey) localStorage.setItem(storageKey, mode); } catch { /* blocked */ }+ onChange?.(mode);+ }++ return {+ get mode() { return mode; },+ isFirstPerson: () => mode === 'firstperson',+ setMode,+ cycle(camera) {+ const idx = CAMERA_MODES.indexOf(mode);+ setMode(CAMERA_MODES[(idx + 1) % CAMERA_MODES.length], camera);+ },+ /** Advance the cinematic auto-orbit and any in-flight mode transition. */+ tick(dt) {+ cinematicAngle += dt * CINEMATIC_ORBIT_SPEED;+ if (transition > 0) transition = Math.max(0, transition - dt);+ },+ /**+ * Apply this frame's pose to `camera`. `lerpFactor` (0..1] smooths normal+ * follow (1 = snap, matching /play's original instant-follow feel); a+ * live mode transition always cross-fades regardless of lerpFactor.+ */+ apply(camera, avatarPos, avatarHeight, orbit, lerpFactor = 1) {+ const desired = computeCameraForMode(mode, avatarPos, avatarHeight, { ...orbit, cinematicAngle });+ if (transition > 0) {+ const t = 1 - transition / TRANSITION_DUR;+ const ease = t * t * (3 - t * 2);+ camera.position.lerpVectors(from.pos, desired.pos, ease);+ camera.fov = from.fov + (toFov - from.fov) * ease;+ } else if (lerpFactor >= 1) {+ camera.position.copy(desired.pos);+ camera.fov = toFov;+ } else {+ camera.position.lerp(desired.pos, lerpFactor);+ camera.fov = toFov;+ }+ camera.lookAt(desired.look);+ camera.updateProjectionMatrix();+ },+ };+}diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 3363ba2f3..f0fe6e924 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -24,6 +24,12 @@ import { AnimationManager } from '../animation-manager.js';import { CommunityNet } from './community-net.js';import { CommunityUI } from './coincommunities-ui.js';import { createWorldEnvironment, seedFromString } from './world-env.js';+import { createDistrict } from './district.js';+import { DISTRICT, clampToBounds } from './world-zones.js';+import { PhysicsWorld } from '../physics/physics-world.js';+import { createDayNightCycle } from './day-night.js';+import { worldClock } from '../shared/world-clock.js';+import { createCameraModeController, CAMERA_MODE_LABELS } from './camera-modes.js';import { createChartScreen } from './chart-screen.js';import { mountOracleRibbon } from './oracle-ribbon.js';import { MarketReactor } from './market-reactor.js';@@ -87,7 +93,12 @@ const CONFETTI_COLORS = ['#ffffff', '#e8e8e8', '#fff8e1', '#e3f2fd', '#f3e5f5',// also sends these bounds in every game:king message; this is the render default.const KING_ZONE = { x: 0, z: -12, r: 3.5 };-const WORLD_RADIUS = 58; // a touch inside the server's 60m clamp+// The Downtown plaza radius (matches world-zones.js DISTRICT.plazaRadius) — the+// dressed circle world-env.js/district.js build around. W01: movement itself is+// no longer clamped to this disc; it's bounded by the much larger square+// DISTRICT/WORLD_BOUND (world-zones.js), which mirrors the server's own clamp so+// players can walk/drive the full district, not just the plaza.+const WORLD_RADIUS = 58;const MOVE_SPEED = 4.2;const RUN_SPEED = 8.0; // hold Shift to sprintconst RUN_TIMESCALE = 1.7; // speed the walk cycle up so a sprint reads as a run@@ -324,6 +335,24 @@ export class CoinCommunities {this._last = performance.now();this._lastKick = 0; // R05: timestamp of last ball:kick intent (client-side rate limit)+ // W01: real Rapier collision. A single physics world + character controller+ // persist for the whole session (Rapier's WASM init is memoized globally);+ // district building colliders are rebuilt per coin in enter(). Movement in+ // _stepLocal falls back to the legacy direct-mutation path until this+ // resolves, so the first frame or two before Rapier's WASM loads still play.+ this._physicsOk = false;+ this._physics = null;+ this._character = null;+ this._physicsActivePrev = false;+ this._physicsReady = this._initPhysics();++ // W01: four-mode chase camera (follow/cinematic/firstperson/topdown),+ // shared with /walk via camera-modes.js. 'c' cycles it (see _bindInput).+ this._camModes = createCameraModeController({+ storageKey: 'play:camera-mode',+ onChange: (m) => this.ui?.toast(`Camera: ${CAMERA_MODE_LABELS[m]}`, 'info'),+ });+// Embed mode: `?bg=transparent` clears the canvas to alpha 0 and drops the// graded sky + fog so the world composites onto the host page (e.g. the IBM// x402 showcase) instead of sitting in its own black box. Default play is@@ -436,6 +465,22 @@ export class CoinCommunities {}}+ // W01: boot the shared Rapier world once. A flat ground collider covers the+ // whole district (buildings are added per-coin in enter(), once the district+ // grid is built). Never throws — a WASM failure (unsupported browser, blocked+ // worker) degrades to the legacy direct-mutation movement path instead of+ // wedging boot.+ async _initPhysics() {+ try {+ this._physics = await PhysicsWorld.create({ gravity: { x: 0, y: -GRAVITY, z: 0 } });+ this._physics.addGround(0, DISTRICT.half + 40);+ this._physicsOk = true;+ } catch (err) {+ log.warn('[coincommunities] physics init failed — falling back to legacy movement:', err?.message);+ this._physicsOk = false;+ }+ }+async _hideBootLoader() {const l = document.getElementById('kx-loading');if (!l) return;@@ -543,6 +588,10 @@ export class CoinCommunities {// and the slowly turning coin totem._tickEnv(dt) {this.env?.update(dt);+ // W01: real time of day, deterministic from wall-clock time (worldClock) —+ // every client in every world computes the identical sun/sky/lamp state+ // with zero network sync, exactly like the /agent-screen ambient stage.+ this._dayNight?.setTime(worldClock(Date.now()));if (this._coinSpin) this._coinSpin.rotation.y += dt * 0.5;if (this._screenPulse) {this._screenT = (this._screenT || 0) + dt;@@ -808,12 +857,38 @@ export class CoinCommunities {// palette, and flora derived deterministically from the coin's mint, so// every community has its own recognisable world.this.env?.dispose();+ this._district?.dispose();// The flagship town pins its signature biome; every other coin draws its// look from the mint seed.const biomeOverride = this._biomePin || (isHomeTown(coin.mint) ? (coin.biome || HOME_TOWN.biome) : undefined);this.env = createWorldEnvironment(this.scene, this.renderer, WORLD_RADIUS, { mint: coin.mint, biome: biomeOverride });this.ui.toast(`${coin.symbol ? '$' + coin.symbol : coin.name || 'Community'} — ${this.env.biome.label}`, 'info');+ // W01: the drivable street grid ringing Downtown — same seed as the biome+ // so it's identical for every client, themed from the same palette. The+ // day/night cycle drives its window/streetlamp glow via setNight().+ this._district = createDistrict(this.scene, {+ seed: this.env.seed, biome: this.env.biome, playRadius: WORLD_RADIUS,+ });+ this._dayNight = createDayNightCycle(this.env, this._district);++ // W01: real collision. Await the one-time Rapier boot (usually long since+ // resolved by the time a player clears the lobby + avatar load), then swap+ // in this coin's building colliders and (re)place the kinematic character+ // at the fresh spawn point. The character controller persists across coin+ // switches — only its colliders and position change.+ await this._physicsReady;+ if (this._physicsOk && this._physics) {+ this._physics.clearObstacles();+ for (const c of this._district.colliders) this._physics.addStaticBox(c);+ const spawn = { x: this.localPos.x, y: 0, z: this.localPos.z };+ if (!this._character) this._character = this._physics.createCharacter({ position: spawn });+ else this._character.setPosition(spawn);+ this._physicsActivePrev = false; // resync _stepLocal to this fresh spawn next frame+ this.vy = 0; this.grounded = true;+ }+ if (epoch !== this._enterEpoch) return; // backed out during the physics await+// Build the coin's world + local avatar.this._buildTotem(coin);this._buildScreen(coin);@@ -2123,6 +2198,12 @@ export class CoinCommunities {this._inspectNearest();return;}+ // C cycles the camera: follow → cinematic → first person → top down.+ if (k === 'c' && !this.buildHud.active && !e.repeat) {+ e.preventDefault();+ this._camModes.cycle(this.camera);+ return;+ }// Q — hold to open the emote wheel, release to play the selected clip.// Ignore auto-repeat (held key fires many keydowns) and build mode.if (k === 'q' && !this.buildHud.active && !e.repeat) {@@ -2888,6 +2969,10 @@ export class CoinCommunities {if (this.phase === 'world') {this._stepLocal(dt);+ // Step the Rapier world AFTER _stepLocal so it consumes the character's+ // queued kinematic move from this same frame (and advances any dynamic+ // props/vehicles later briefs add).+ if (this._physicsOk && this._physics) this._physics.step(dt);this._checkFloorOccupancy();this.localAnim?.update(dt);this.localCosmetics?.tick(dt);@@ -2917,7 +3002,7 @@ export class CoinCommunities {}}this._tickEnv(dt);- this._updateCamera();+ this._updateCamera(dt);this.renderer.render(this.scene, this.camera);}@@ -2930,13 +3015,6 @@ export class CoinCommunities {}_stepLocal(dt) {- // Vertical integration first so a jump arcs even while standing still.- if (!this.grounded) {- this.vy -= GRAVITY * dt;- this.localPos.y += this.vy * dt;- if (this.localPos.y <= 0) { this.localPos.y = 0; this.vy = 0; this.grounded = true; }- }-// Build intent from keys + joystick, relative to camera yaw.let ix = 0, iz = 0;if (this.keys.has('w') || this.keys.has('arrowup')) iz -= 1;@@ -2946,22 +3024,18 @@ export class CoinCommunities {if (this._joy) { ix += this._joy.x; iz += this._joy.z; }const running = this.keys.has('shift');const mag = Math.hypot(ix, iz);- if (mag > 0.05) {- ix /= Math.max(1, mag); iz /= Math.max(1, mag);+ const moving = mag > 0.05;+ let wx = 0, wz = 0;+ if (moving) {+ const nx = ix / Math.max(1, mag), nz = iz / Math.max(1, mag);// Map intent into world space using the camera's own basis so the// keys read screen-relative: forward (W/up) goes straight away from// the camera, D/right tracks screen-right. Camera forward is// (sinYaw, cosYaw) and camera-right is (cosYaw, -sinYaw) — see// _updateCamera. world = ix*right + (-iz)*forward.const sin = Math.sin(this.camYaw), cos = Math.cos(this.camYaw);- const wx = ix * cos - iz * sin;- const wz = -ix * sin - iz * cos;- const speed = running ? RUN_SPEED : MOVE_SPEED;- this.localPos.x += wx * speed * dt;- this.localPos.z += wz * speed * dt;- // clamp to plaza- const r = Math.hypot(this.localPos.x, this.localPos.z);- if (r > WORLD_RADIUS) { this.localPos.x *= WORLD_RADIUS / r; this.localPos.z *= WORLD_RADIUS / r; }+ wx = nx * cos - nz * sin;+ wz = -nx * sin - nz * cos;this.localYaw = Math.atan2(wx, wz);const want = running ? 'run' : 'walk';if (this.motion !== want) { this.motion = want; this.localAnim?.crossfadeTo(CLIP_WALK, 0.18); }@@ -2972,6 +3046,53 @@ export class CoinCommunities {if (this.localAnim?.currentName === CLIP_WALK) {this.localAnim.setSpeed(this.motion === 'run' ? RUN_TIMESCALE : 1);}++ const speed = running ? RUN_SPEED : MOVE_SPEED;+ // W01: the Rapier kinematic character controller is authoritative for+ // collision (district buildings, ground) once physics has booted; it+ // slides along walls, steps up curbs, and reports real ground contact+ // instead of the flat y<=0 assumption the legacy path used. physics.step()+ // (called from _loop, after this) consumes the queued move.+ if (this._physicsOk && this._character) {+ if (!this._physicsActivePrev) {+ this._character.setPosition({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z });+ this.vy = 0;+ this._physicsActivePrev = true;+ }+ this.vy -= GRAVITY * dt;+ if (this.vy < -40) this.vy = -40; // terminal velocity guard+ const res = this._character.move({+ x: moving ? wx * speed * dt : 0,+ y: this.vy * dt,+ z: moving ? wz * speed * dt : 0,+ });+ this.grounded = res.grounded;+ if (this.grounded && this.vy < 0) this.vy = 0;+ // Boundary safety — mirrors the server's square WORLD_BOUND clamp+ // (world-zones.js DISTRICT.half) so client and server never disagree+ // on the world's edge. Snap the body too so the next query starts clean.+ const clamped = clampToBounds(res.position.x, res.position.z);+ if (clamped.x !== res.position.x || clamped.z !== res.position.z) {+ this._character.setPosition({ x: clamped.x, y: res.position.y, z: clamped.z });+ }+ this.localPos.set(clamped.x, res.position.y, clamped.z);+ } else {+ this._physicsActivePrev = false;+ // Legacy direct-mutation fallback — only live for the brief window+ // before Rapier's WASM finishes loading (or if it fails to load at all).+ if (!this.grounded) {+ this.vy -= GRAVITY * dt;+ this.localPos.y += this.vy * dt;+ if (this.localPos.y <= 0) { this.localPos.y = 0; this.vy = 0; this.grounded = true; }+ }+ if (moving) {+ this.localPos.x += wx * speed * dt;+ this.localPos.z += wz * speed * dt;+ const clamped = clampToBounds(this.localPos.x, this.localPos.z);+ this.localPos.x = clamped.x; this.localPos.z = clamped.z;+ }+ }+if (this.localRig) { this.localRig.position.copy(this.localPos); this.localRig.rotation.y = this.localYaw; }this._checkBallKick();}@@ -3022,18 +3143,28 @@ export class CoinCommunities {this.voice.update({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z }, peers, forward);}- _updateCamera() {- // Track the avatar on the ground plane only — ignore jump height so the- // camera stays planted while the character hops.- const target = this.phase === 'world' && this.localRig- ? new Vector3(this.localPos.x, 0, this.localPos.z)- : new Vector3(0, 2, 0);- const cp = Math.cos(this.camPitch), sp = Math.sin(this.camPitch);- const ox = Math.sin(this.camYaw) * cp * this.camDist;- const oz = Math.cos(this.camYaw) * cp * this.camDist;- const oy = sp * this.camDist + 1.4;- this.camera.position.set(target.x - ox, target.y + oy, target.z - oz);- this.camera.lookAt(target.x, target.y + 1.4, target.z);+ // W01: four-mode chase camera (follow/cinematic/firstperson/topdown) via the+ // shared camera-modes.js controller — see the constructor and the 'c' key in+ // _bindInput. 'follow' reproduces the original fixed orbit exactly, so the+ // default view is unchanged; the other three are new.+ _updateCamera(dt) {+ this._camTarget = this._camTarget || new Vector3();+ // Track the avatar on the ground plane only in follow/cinematic/topdown —+ // ignore jump height so those cameras stay planted while the character+ // hops. First person tracks the real (jump-inclusive) height for the eye.+ const inWorld = this.phase === 'world' && this.localRig;+ const fp = this._camModes.isFirstPerson();+ const target = inWorld+ ? this._camTarget.set(this.localPos.x, fp ? this.localPos.y : 0, this.localPos.z)+ : this._camTarget.set(0, 2, 0);+ this._camModes.tick(dt || 0);+ this._camModes.apply(this.camera, target, this.localHeight || 1.7, {+ // First person looks where the avatar faces (localYaw); every other+ // mode orbits on the mouse-drag yaw (camYaw).+ yaw: fp ? this.localYaw : this.camYaw,+ pitch: this.camPitch, dist: this.camDist,+ });+ if (this.localRig) this.localRig.visible = !fp;}_updateLabels() {diff --git a/src/screener.css b/src/screener.cssnew file mode 100644index 000000000..01fa97841--- /dev/null+++ b/src/screener.css@@ -0,0 +1,122 @@+/*+ * /screener — token screener. Reuses cv-table, cv-search, cv-pill and the+ * hm-seg segmented control from coin-pages.css; this file styles only the+ * filter control row (selects, reset, result count) that is unique here.+ */++.scr-controls {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ gap: 0.75rem;+ margin-bottom: 1rem;+}++.scr-field {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ font-size: 0.6875rem;+ font-weight: 500;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--cv-text-3);+}+.scr-field select {+ appearance: none;+ font: inherit;+ font-size: 0.8125rem;+ font-weight: 400;+ letter-spacing: normal;+ text-transform: none;+ color: var(--cv-text);+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ padding: 0.5rem 2rem 0.5rem 0.75rem;+ cursor: pointer;+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");+ background-repeat: no-repeat;+ background-position: right 0.5rem center;+ background-size: 1rem;+ transition:+ border-color 0.15s,+ box-shadow 0.15s;+}+.scr-field select:hover {+ border-color: var(--cv-border-hover);+}+.scr-field select:focus {+ outline: none;+ border-color: var(--cv-accent);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 20%, transparent);+}++.scr-reset {+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-size: 0.8125rem;+ font-weight: 500;+ color: var(--cv-text-2);+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ padding: 0.5rem 1rem;+ transition:+ background 0.15s,+ color 0.15s,+ border-color 0.15s;+}+.scr-reset:hover {+ background: var(--cv-surface-2);+ color: var(--cv-text);+ border-color: var(--cv-border-hover);+}+.scr-reset:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}++.scr-meta {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ margin-bottom: 1rem;+}+.scr-count {+ font-size: 0.8125rem;+ font-weight: 500;+ color: var(--cv-text-2);+ font-variant-numeric: tabular-nums;+}++.scr-empty-reset {+ appearance: none;+ border: 0;+ background: transparent;+ padding: 0;+ font: inherit;+ color: var(--cv-accent);+ cursor: pointer;+ text-decoration: underline;+}+.scr-empty-reset:hover {+ color: var(--cv-accent-hover);+}+.scr-empty-reset:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+ border-radius: var(--cv-radius-sm);+}++@media (max-width: 639px) {+ .scr-field {+ flex: 1 1 45%;+ }+ .scr-field select {+ width: 100%;+ }+}diff --git a/src/screener.js b/src/screener.jsnew file mode 100644index 000000000..c931e4c69--- /dev/null+++ b/src/screener.js@@ -0,0 +1,252 @@+// /screener — client-side token screener over the live top-250 markets.+// Loads /api/coin/markets?page=1&per_page=250 once, then filters and sorts+// entirely in the browser: text search, gainers/losers, market-cap and volume+// floors, and click-to-sort columns reusing the shared cv-table pattern from+// coins-index.js. Every row links to the rich /coin/:id detail page.++import { formatUsd, formatPrice, formatPercent, escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── State ─────────────────────────────────────────────────────────────────────++const COLUMNS = [+ { key: 'rank', label: '#', left: true, hide: 'hide-sm', num: true },+ { key: 'name', label: 'Coin', left: true },+ { key: 'price', label: 'Price', num: true },+ { key: 'change_24h', label: '24h %', num: true },+ { key: 'change_7d', label: '7d %', hide: 'hide-md', num: true },+ { key: 'market_cap', label: 'Mkt Cap', hide: 'hide-lg', num: true },+ { key: 'volume_24h', label: 'Vol (24h)', hide: 'hide-lg', num: true },+];++const state = {+ coins: [],+ loaded: false,+ error: false,+ sortKey: 'rank',+ sortDir: 'asc',+ q: '',+ dir: 'all', // all | gainers | losers+ minMcap: 0,+ minVol: 0,+};++// ── Filtering + sorting ────────────────────────────────────────────────────────++function filtered() {+ const q = state.q.toLowerCase();+ return state.coins.filter((c) => {+ if (q && !`${c.name} ${c.symbol}`.toLowerCase().includes(q)) return false;+ if (state.dir === 'gainers' && !((c.change_24h ?? 0) > 0)) return false;+ if (state.dir === 'losers' && !((c.change_24h ?? 0) < 0)) return false;+ if (state.minMcap && (c.market_cap ?? 0) < state.minMcap) return false;+ if (state.minVol && (c.volume_24h ?? 0) < state.minVol) return false;+ return true;+ });+}++function sortValue(c, key) {+ if (key === 'name') return (c.name || '').toLowerCase();+ if (key === 'rank') return c.rank ?? Infinity;+ return c[key] ?? -Infinity;+}++function sorted(rows) {+ const { sortKey, sortDir } = state;+ return [...rows].sort((a, b) => {+ const va = sortValue(a, sortKey);+ const vb = sortValue(b, sortKey);+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;+ return sortDir === 'asc' ? cmp : -cmp;+ });+}++// ── Rendering ─────────────────────────────────────────────────────────────────++function pctCell(v, extraClass = '') {+ if (v == null) return `<td class="pct dim ${extraClass}">—</td>`;+ const up = v >= 0;+ return `<td class="pct ${up ? 'cv-up' : 'cv-down'} ${extraClass}"><span aria-hidden="true">${up ? '▲' : '▼'}</span>${esc(formatPercent(v))}</td>`;+}++function updateCount(shown) {+ const el = $('scr-count');+ if (!el) return;+ if (!state.loaded) {+ el.textContent = '';+ return;+ }+ el.textContent = `${shown.toLocaleString('en-US')} of ${state.coins.length.toLocaleString('en-US')} coins`;+}++function renderTable() {+ const el = $('scr-table');++ if (state.error) {+ el.innerHTML =+ '<div class="cv-empty">Market data is temporarily unavailable. Please try again shortly.</div>';+ updateCount(0);+ return;+ }+ if (!state.loaded) return; // skeleton already on screen++ const rows = sorted(filtered());+ updateCount(rows.length);++ if (!rows.length) {+ el.innerHTML =+ '<div class="cv-empty">No coins match these filters. Try widening your market-cap or volume floor, or <button type="button" class="scr-empty-reset" id="scr-empty-reset">reset all filters</button>.</div>';+ $('scr-empty-reset')?.addEventListener('click', resetFilters);+ return;+ }++ const head = COLUMNS.map((col) => {+ const active = col.key === state.sortKey;+ const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ }).join('');++ const body = rows+ .map((c) => {+ const href = `/coin/${encodeURIComponent(c.id)}`;+ return `+ <tr data-href="${esc(href)}">+ <td class="rank hide-sm cv-mono">${c.rank ?? '—'}</td>+ <td class="left name-cell"><a href="${esc(href)}"><span class="inner">+ ${c.image ? `<img src="${esc(c.image)}" alt="" loading="lazy" width="24" height="24" data-no-dark-filter />` : ''}+ <span class="nm">${esc(c.name)}</span>+ <span class="sym">${esc(c.symbol)}</span>+ </span></a></td>+ <td class="price">${esc(formatPrice(c.price))}</td>+ ${pctCell(c.change_24h)}+ ${pctCell(c.change_7d, 'hide-md')}+ <td class="dim hide-lg">${esc(formatUsd(c.market_cap))}</td>+ <td class="dim hide-lg">${esc(formatUsd(c.volume_24h))}</td>+ </tr>`;+ })+ .join('');++ el.innerHTML = `+ <div class="cv-table-wrap">+ <table class="cv-table">+ <thead><tr>${head}</tr></thead>+ <tbody>${body}</tbody>+ </table>+ </div>`;++ el.querySelectorAll('th[data-key]').forEach((th) => {+ const activate = () => {+ const key = th.dataset.key;+ if (key === state.sortKey) {+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';+ } else {+ state.sortKey = key;+ state.sortDir = key === 'name' || key === 'rank' ? 'asc' : 'desc';+ }+ renderTable();+ };+ th.addEventListener('click', activate);+ th.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ activate();+ }+ });+ });++ el.querySelectorAll('tr[data-href]').forEach((tr) => {+ tr.addEventListener('click', (e) => {+ if (e.target.closest('a')) return;+ location.href = tr.dataset.href;+ });+ });+}++// ── Controls ──────────────────────────────────────────────────────────────────++function resetFilters() {+ state.q = '';+ state.dir = 'all';+ state.minMcap = 0;+ state.minVol = 0;+ state.sortKey = 'rank';+ state.sortDir = 'asc';+ $('scr-search-input').value = '';+ $('scr-mcap').value = '0';+ $('scr-vol').value = '0';+ $('scr-dir')+ .querySelectorAll('button')+ .forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.dir === 'all')));+ renderTable();+}++function wireControls() {+ const input = $('scr-search-input');+ let timer = null;+ input.addEventListener('input', () => {+ clearTimeout(timer);+ timer = setTimeout(() => {+ state.q = input.value.trim();+ renderTable();+ }, 200);+ });++ $('scr-dir')+ .querySelectorAll('button')+ .forEach((btn) => {+ btn.addEventListener('click', () => {+ state.dir = btn.dataset.dir;+ $('scr-dir')+ .querySelectorAll('button')+ .forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));+ renderTable();+ });+ });++ $('scr-mcap').addEventListener('change', (e) => {+ state.minMcap = Number(e.target.value) || 0;+ renderTable();+ });+ $('scr-vol').addEventListener('change', (e) => {+ state.minVol = Number(e.target.value) || 0;+ renderTable();+ });+ $('scr-reset').addEventListener('click', resetFilters);+}++// ── Load ──────────────────────────────────────────────────────────────────────++async function load() {+ const el = $('scr-table');+ el.innerHTML =+ '<div class="cv-table-wrap" style="padding:0.75rem">' ++ Array.from(+ { length: 14 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('') ++ '</div>';+ try {+ const { coins } = await getJson('/api/coin/markets?page=1&per_page=250');+ state.coins = Array.isArray(coins) ? coins : [];+ state.loaded = true;+ $('scr-updated').textContent = `Updated ${new Date().toLocaleTimeString('en-US')}`;+ } catch {+ state.error = true;+ $('scr-updated').textContent = '';+ }+ renderTable();+}++wireControls();+load();diff --git a/src/stablecoins.css b/src/stablecoins.cssnew file mode 100644index 000000000..59b39c27e--- /dev/null+++ b/src/stablecoins.css@@ -0,0 +1,81 @@+/*+ * /stablecoins — small additions on top of coin-pages.css. Everything here is+ * scoped to sc-* helpers: the stat grid, the peg-mechanism filter (reusing the+ * hm-seg segmented-control look), mechanism chips, chain tags, and the off-peg+ * deviation badge. All colors reference the shared --cv-* tokens so both themes+ * are covered automatically.+ */++.sc-stats-grid {+ display: grid;+ gap: 1rem;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ margin-bottom: 1.5rem;+}++/* Filter row: reuse the heatmap segmented control, allow it to wrap on mobile. */+#sc-filter {+ flex-wrap: wrap;+}++/* Off-peg deviation badge next to a depegged price. */+.sc-depeg {+ margin-left: 0.4rem;+ font-size: 0.6875rem;+ font-weight: 600;+ font-family: var(--cv-font-mono);+ vertical-align: middle;+ opacity: 0.85;+}++/* Peg-mechanism chip — colored per mechanism, built on the shared .cv-chip. */+.cv-chip.sc-mech {+ border: 1px solid transparent;+ white-space: nowrap;+}+.cv-chip.sc-mech.fiat {+ background: color-mix(in srgb, var(--cv-accent) 14%, transparent);+ color: var(--cv-accent);+ border-color: color-mix(in srgb, var(--cv-accent) 30%, transparent);+}+.cv-chip.sc-mech.crypto {+ background: var(--cv-green-soft);+ color: var(--cv-green);+ border-color: color-mix(in srgb, var(--cv-green) 30%, transparent);+}+.cv-chip.sc-mech.algo {+ background: color-mix(in srgb, #f59e0b 16%, transparent);+ color: #b45309;+ border-color: color-mix(in srgb, #f59e0b 34%, transparent);+}+html[data-theme='dark'] .cv-chip.sc-mech.algo,+html:not([data-theme='light']) .cv-chip.sc-mech.algo {+ color: #fbbf24;+}+.cv-chip.sc-mech.other {+ background: var(--cv-surface-3);+ color: var(--cv-text-2);+ border-color: var(--cv-border);+}++/* Chain tags — compact, mono, wrap under their cell. */+.sc-chains {+ display: inline-flex;+ flex-wrap: wrap;+ gap: 0.3rem;+ max-width: 15rem;+}+.sc-chain {+ font-size: 0.6875rem;+ font-weight: 500;+ color: var(--cv-text-2);+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-sm);+ padding: 0.0625rem 0.375rem;+ white-space: nowrap;+}+.sc-chain.more {+ color: var(--cv-text-3);+ background: transparent;+}diff --git a/src/stablecoins.js b/src/stablecoins.jsnew file mode 100644index 000000000..8785541f3--- /dev/null+++ b/src/stablecoins.js@@ -0,0 +1,349 @@+// /stablecoins — stablecoin market-cap board, part of the three.ws Markets+// surface. Header stat cards (total mcap, count, top dominance), a peg-mechanism+// filter, and a sortable table of the top 100 stablecoins by circulating supply.+// Each row shows peg health (price colored by deviation from its $1.00 peg),+// market cap, dominance share, mechanism, and the chains it lives on. Data is the+// free, keyless DeFiLlama stablecoins API via /api/defi/stablecoins.++import { formatUsd, formatPrice, escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// ── Stat cards ────────────────────────────────────────────────────────────────++const ICONS = {+ trend: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>',+ coins: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6"/><path d="M18.09 10.37A6 6 0 1 1 10.34 18"/><path d="M7 6h1v4"/><path d="m16.71 13.88.7.71-2.82 2.82"/></svg>',+ pie: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.21 15.89A10 10 0 1 1 8 2.83"/><path d="M22 12A10 10 0 0 0 12 2v10z"/></svg>',+};++function statCard({ label, value, delta, deltaClass, icon }) {+ return `+ <div class="cv-stat-card">+ <div style="min-width:0">+ <p class="label">${esc(label)}</p>+ <p class="value cv-mono">${esc(value)}</p>+ ${delta ? `<p class="delta ${deltaClass || ''}">${esc(delta)}</p>` : ''}+ </div>+ <span class="icon" aria-hidden="true">${ICONS[icon] || ''}</span>+ </div>`;+}++// ── Peg-mechanism display ──────────────────────────────────────────────────────++// DeFiLlama's raw mechanism tokens → { css class, human label }. Unknown tokens+// keep their raw value, title-cased, under a neutral "other" class.+const MECHANISMS = {+ 'fiat-backed': { cls: 'fiat', label: 'Fiat-backed' },+ 'crypto-backed': { cls: 'crypto', label: 'Crypto-backed' },+ algorithmic: { cls: 'algo', label: 'Algorithmic' },+};++// DeFiLlama ships a small number of records with a misspelled mechanism token+// ("crytpo-backed"). Fold known typos into their canonical value so the filter+// and chips don't split one mechanism across two look-alike entries.+const MECH_ALIASES = { 'crytpo-backed': 'crypto-backed' };++function normalizeMechanism(raw) {+ if (typeof raw !== 'string') return raw;+ return MECH_ALIASES[raw] || raw;+}++function titleCase(s) {+ return String(s || '')+ .replace(/[-_]/g, ' ')+ .replace(/\b\w/g, (c) => c.toUpperCase());+}++function mechanism(raw) {+ if (!raw) return { cls: 'other', label: 'Unknown' };+ return MECHANISMS[raw] || { cls: 'other', label: titleCase(raw) };+}++// ── Peg health ─────────────────────────────────────────────────────────────────++// Peg health is only meaningful against a known target. USD-pegged assets peg to+// $1.00, so deviation = |price − 1|. Within 0.5% reads healthy (green); beyond+// reads off-peg (red). Non-USD pegs (peggedEUR, peggedGBP, …) have no $1 target+// available here, so they render neutral rather than being falsely flagged.+function pegHealth(price, pegType) {+ if (price == null || !Number.isFinite(price)) return { cls: '', dev: null };+ if (pegType && pegType !== 'peggedUSD') return { cls: '', dev: null };+ const dev = price - 1;+ return { cls: Math.abs(dev) <= 0.005 ? 'on' : 'off', dev };+}++function priceCell(c) {+ const { cls, dev } = pegHealth(c.price, c.peg_type);+ const toneClass = cls === 'on' ? 'cv-up' : cls === 'off' ? 'cv-down' : 'dim';+ const price = esc(formatPrice(c.price));+ // Only surface a deviation badge when the asset is measurably off its peg —+ // that's the signal worth drawing the eye to.+ const badge =+ cls === 'off' && dev != null+ ? `<span class="sc-depeg">${dev >= 0 ? '+' : '−'}${(Math.abs(dev) * 100).toFixed(1)}%</span>`+ : '';+ return `<td class="price cv-mono ${toneClass}">${price}${badge}</td>`;+}++// ── Table ───────────────────────────────────────────────────────────────────────++const COLUMNS = [+ { key: 'rank', label: '#', left: true, hide: 'hide-sm', num: true },+ { key: 'name', label: 'Stablecoin', left: true },+ { key: 'price', label: 'Price · Peg', num: true },+ { key: 'circulating_usd', label: 'Market Cap', num: true },+ { key: 'dominance', label: 'Dominance', hide: 'hide-md', num: true },+ { key: 'peg_mechanism', label: 'Mechanism', hide: 'hide-lg', left: true },+ { key: 'chain_count', label: 'Chains', hide: 'hide-lg', left: true },+];++const state = {+ all: [],+ total: 0,+ updatedAt: null,+ filter: 'all',+ sortKey: 'rank',+ sortDir: 'asc',+};++function dominance(c) {+ return state.total > 0 ? (c.circulating_usd / state.total) * 100 : 0;+}++function chainsCell(c) {+ const chains = Array.isArray(c.chains) ? c.chains : [];+ if (!chains.length) return '<td class="hide-lg left dim">—</td>';+ const shown = chains.slice(0, 3).map((n) => `<span class="sc-chain">${esc(n)}</span>`);+ const extra = chains.length - 3;+ if (extra > 0) shown.push(`<span class="sc-chain more">+${extra}</span>`);+ return `<td class="hide-lg left"><span class="sc-chains">${shown.join('')}</span></td>`;+}++function sortValue(c, key) {+ if (key === 'name') return (c.name || '').toLowerCase();+ if (key === 'rank') return c._rank ?? Infinity;+ if (key === 'dominance') return dominance(c);+ if (key === 'peg_mechanism') return mechanism(c.peg_mechanism).label.toLowerCase();+ return c[key] ?? 0;+}++function visibleRows() {+ let rows = state.all;+ if (state.filter !== 'all') rows = rows.filter((c) => (c.peg_mechanism || '') === state.filter);+ const { sortKey, sortDir } = state;+ const copy = [...rows];+ copy.sort((a, b) => {+ const va = sortValue(a, sortKey);+ const vb = sortValue(b, sortKey);+ const cmp = typeof va === 'string' ? va.localeCompare(vb) : va - vb;+ return sortDir === 'asc' ? cmp : -cmp;+ });+ return copy;+}++function renderTable() {+ const el = $('sc-table');+ const rows = visibleRows();++ if (!state.all.length) {+ el.innerHTML =+ '<div class="cv-empty">Stablecoin data is temporarily unavailable. Please <a href="/stablecoins">try again</a> shortly.</div>';+ return;+ }+ if (!rows.length) {+ el.innerHTML = `<div class="cv-empty">No stablecoins match this filter. <a href="#" data-reset="1">Show all</a>.</div>`;+ el.querySelector('[data-reset]')?.addEventListener('click', (e) => {+ e.preventDefault();+ setFilter('all');+ });+ return;+ }++ const head = COLUMNS.map((col) => {+ const active = col.key === state.sortKey;+ const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';+ return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ }).join('');++ const body = rows+ .map((c) => {+ const m = mechanism(c.peg_mechanism);+ return `+ <tr>+ <td class="rank hide-sm cv-mono">${c._rank ?? '—'}</td>+ <td class="left name-cell"><span class="inner">+ <span class="nm">${esc(c.name)}</span>+ <span class="sym">${esc(c.symbol)}</span>+ </span></td>+ ${priceCell(c)}+ <td class="cv-mono">${esc(formatUsd(c.circulating_usd))}</td>+ <td class="cv-mono hide-md dim">${dominance(c).toFixed(2)}%</td>+ <td class="left hide-lg"><span class="cv-chip sc-mech ${m.cls}">${esc(m.label)}</span></td>+ ${chainsCell(c)}+ </tr>`;+ })+ .join('');++ el.innerHTML = `+ <div class="cv-table-wrap">+ <table class="cv-table">+ <thead><tr>${head}</tr></thead>+ <tbody>${body}</tbody>+ </table>+ </div>`;++ el.querySelectorAll('th[data-key]').forEach((th) => {+ const activate = () => {+ const key = th.dataset.key;+ if (key === state.sortKey) {+ state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';+ } else {+ state.sortKey = key;+ state.sortDir =+ key === 'name' || key === 'rank' || key === 'peg_mechanism' ? 'asc' : 'desc';+ }+ renderTable();+ };+ th.addEventListener('click', activate);+ th.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ activate();+ }+ });+ });+}++// ── Filters ─────────────────────────────────────────────────────────────────────++function setFilter(value) {+ state.filter = value;+ const seg = $('sc-filter');+ seg?.querySelectorAll('button').forEach((b) => {+ b.setAttribute('aria-pressed', String(b.dataset.mech === value));+ });+ renderTable();+}++function renderFilters() {+ const seg = $('sc-filter');+ if (!seg) return;+ // Derive the filter set from the data — only mechanisms actually present get a+ // chip, in the canonical order, with anything unrecognised grouped last.+ const present = new Set(state.all.map((c) => c.peg_mechanism).filter(Boolean));+ const order = ['fiat-backed', 'crypto-backed', 'algorithmic'];+ const known = order.filter((m) => present.has(m));+ const others = [...present].filter((m) => !order.includes(m)).sort();+ const chips = [{ mech: 'all', label: 'All' }].concat(+ known.map((m) => ({ mech: m, label: mechanism(m).label })),+ others.map((m) => ({ mech: m, label: mechanism(m).label })),+ );+ seg.innerHTML = chips+ .map(+ (c) =>+ `<button type="button" data-mech="${esc(c.mech)}" aria-pressed="${c.mech === state.filter}">${esc(c.label)}</button>`,+ )+ .join('');+ seg.querySelectorAll('button').forEach((b) => {+ b.addEventListener('click', () => setFilter(b.dataset.mech));+ });+}++// ── Stats ───────────────────────────────────────────────────────────────────────++function renderStats() {+ const el = $('sc-stats');+ const top = state.all[0];+ const topDom = top ? dominance(top) : null;+ const cards = [+ statCard({+ label: 'Total Stablecoin Market Cap',+ value: formatUsd(state.total),+ icon: 'trend',+ }),+ statCard({+ label: 'Stablecoins Tracked',+ value: state.count != null ? state.count.toLocaleString('en-US') : '—',+ icon: 'coins',+ }),+ ];+ if (top && topDom != null) {+ cards.push(+ statCard({+ label: `${top.symbol || top.name} Dominance`,+ value: `${topDom.toFixed(1)}%`,+ delta: 'Largest stablecoin',+ icon: 'pie',+ }),+ );+ }+ el.innerHTML = `<div class="sc-stats-grid">${cards.join('')}</div>`;+}++function renderUpdated() {+ const el = $('sc-updated');+ if (!el) return;+ const when = state.updatedAt+ ? new Date(state.updatedAt).toLocaleTimeString('en-US', {+ hour: '2-digit',+ minute: '2-digit',+ })+ : null;+ el.textContent = when ? `Data: DeFiLlama · updated ${when}` : 'Data: DeFiLlama';+}++// ── Boot ─────────────────────────────────────────────────────────────────────────++function skeletons() {+ $('sc-stats').innerHTML =+ '<div class="sc-stats-grid">' ++ Array.from({ length: 3 }, () => '<div class="cv-skel" style="height:6.5rem"></div>').join(+ '',+ ) ++ '</div>';+ $('sc-table').innerHTML =+ '<div class="cv-table-wrap" style="padding:0.75rem">' ++ Array.from(+ { length: 12 },+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',+ ).join('') ++ '</div>';+}++async function load() {+ skeletons();+ try {+ const data = await getJson('/api/defi/stablecoins');+ const list = Array.isArray(data.stablecoins) ? data.stablecoins : [];+ state.all = list.map((c, i) => ({+ ...c,+ peg_mechanism: normalizeMechanism(c.peg_mechanism),+ _rank: i + 1,+ }));+ state.total = Number.isFinite(data.total_mcap) ? data.total_mcap : 0;+ state.count = Number.isFinite(data.count) ? data.count : state.all.length;+ state.updatedAt = data.updated_at || null;+ renderStats();+ renderFilters();+ renderTable();+ renderUpdated();+ } catch {+ state.all = [];+ $('sc-stats').innerHTML = '';+ renderTable();+ renderUpdated();+ }+}++load();diff --git a/tests/agent-avatar-mood-gesture.test.js b/tests/agent-avatar-mood-gesture.test.jsnew file mode 100644index 000000000..8762f9a41--- /dev/null+++ b/tests/agent-avatar-mood-gesture.test.js@@ -0,0 +1,165 @@+/**+ * AgentAvatar × sustained mood → gesture-slot bias — unit tests.+ *+ * Exercises Stage 3.5 of `_tickEmotion()`: the sustained mood layer (valence ×+ * arousal, set via `setMood()`) biasing which gesture *slot* the avatar plays,+ * on top of the pre-existing transient-emotion gesture triggers (Stage 3) and+ * the facial/postural mood layer (`_applyMoodLayer`). No Three.js render loop+ * or real animation clips are needed — `_tickEmotion()` is called directly+ * against a minimal fake viewer, mirroring the approach in+ * tests/agent-avatar-lipsync.test.js.+ */++import { describe, it, expect, beforeEach } from 'vitest';++let AgentAvatar;++// ── Fakes ────────────────────────────────────────────────────────────────────++// Object3D-shaped root with a no-op traverse — enough for `_findHeadBone()`+// and `_trackBodyToCamera()` to no-op safely without a real skeleton.+function makeRoot() {+ return {+ isObject3D: true,+ children: [],+ traverse(fn) {+ fn(this);+ },+ };+}++/**+ * Fake AnimationManager. `loadedNames` is the whitelist of clip names that+ * "exist" on this rig (isLoaded → true); everything else is unregistered.+ * Records every clip name actually handed to play()/crossfadeTo() so tests+ * can assert the gesture bias never reaches for a name outside the whitelist.+ */+function makeFakeAnimationManager(loadedNames = []) {+ const loaded = new Set(loadedNames);+ const played = [];+ return {+ currentName: null,+ isLoaded: (name) => loaded.has(name),+ getAnimationDefs: () => [],+ play: (name) => {+ played.push(name);+ return Promise.resolve(true);+ },+ crossfadeTo: (name) => {+ played.push(name);+ },+ played,+ };+}++function makeFakeViewer(am) {+ return {+ content: makeRoot(),+ animationManager: am,+ state: {},+ };+}++function makeAvatar(am) {+ const viewer = makeFakeViewer(am);+ const protocol = {}; // unused outside attach()+ const identity = { id: 'test' };+ return new AgentAvatar(viewer, protocol, identity);+}++// Ticks with a large dt so `_moodApplied` (lerp factor `dt * 1.2`, clamped to+// 1) fully converges to the mood target within a single tick, and a second+// tick is enough for Stage 3.5 (which reads the *previous* frame's applied+// mood, since it runs before Stage 4's lerp) to see the converged value.+function settleMood(avatar, times = 3) {+ for (let i = 0; i < times; i++) avatar._tickEmotion(1);+}++beforeEach(async () => {+ if (!AgentAvatar) {+ const mod = await import('../src/agent-avatar.js');+ AgentAvatar = mod.AgentAvatar;+ }+});++describe('AgentAvatar — sustained mood → gesture-slot bias', () => {+ it('a sustained high-arousal-positive mood biases toward the energetic (celebrate) gesture', () => {+ const am = makeFakeAnimationManager(['celebrate', 'defeated']);+ const avatar = makeAvatar(am);++ avatar.setMood(0.6, 0.8); // clearly up + energetic+ settleMood(avatar);++ expect(am.played).toContain('celebrate');+ expect(am.played).not.toContain('defeated');+ });++ it('a sustained low-arousal-negative mood biases away from the energetic gesture', () => {+ const am = makeFakeAnimationManager(['celebrate', 'defeated']);+ const avatar = makeAvatar(am);++ avatar.setMood(-0.6, 0.1); // clearly down + subdued+ settleMood(avatar);++ expect(am.played).not.toContain('celebrate');+ // The concern slot resolves to the "defeated" library clip by default —+ // confirms the bias picked the opposite-valence gesture, not silence.+ expect(am.played).toContain('defeated');+ });++ it('a neutral resting mood (defaults, setMood never called) triggers no gesture bias', () => {+ const am = makeFakeAnimationManager(['celebrate', 'defeated']);+ const avatar = makeAvatar(am);++ settleMood(avatar); // _mood.active stays false — no setMood() call++ expect(am.played).toEqual([]);+ });++ it('never selects a clip that is not registered on the attached rig', () => {+ // Nothing is loaded and no defs are registered — every slot resolves to+ // an unregistered clip name. The bias must not hand an unknown name to+ // play()/crossfadeTo(); it degrades to the embedded-clip fallback (a+ // silent no-op here, since the fake viewer has no `mixer`/`clips`).+ const am = makeFakeAnimationManager([]);+ const avatar = makeAvatar(am);++ avatar.setMood(0.9, 0.95); // maximally energetic + positive+ expect(() => settleMood(avatar)).not.toThrow();++ expect(am.played).toEqual([]);+ });++ it('composes with meta.edits.animations — an overridden celebrate slot plays the custom clip', () => {+ const am = makeFakeAnimationManager(['victory-dance-custom']);+ const avatar = makeAvatar(am);+ avatar.setAnimationMap({ celebrate: 'victory-dance-custom' });++ avatar.setMood(0.6, 0.8);+ settleMood(avatar);++ expect(am.played).toContain('victory-dance-custom');+ expect(am.played).not.toContain('celebrate');+ });++ it('a live transient emotion spike still takes priority over the sustained mood bias', () => {+ const am = makeFakeAnimationManager(['celebrate', 'defeated']);+ const avatar = makeAvatar(am);++ // Sustained mood says "down + subdued" (would bias toward `concern`)...+ avatar.setMood(-0.6, 0.1);+ // ...but a momentary celebration spike (e.g. a skill just succeeded) is+ // injected via the public emote path, well above the Stage-3 threshold.+ avatar._injectStimulus('celebration', 0.9);++ // Only 2 ticks: the transient spike decays below the 0.6 threshold after+ // ~2s (DECAY.celebration = 0.18/s), at which point Stage 3 correctly+ // falls through to the sustained mood bias below it — that hand-off is+ // the intended behaviour, not something this test covers. Within the+ // window the spike is still live, mood must not preempt it.+ settleMood(avatar, 2);++ expect(am.played).toContain('celebrate');+ expect(am.played).not.toContain('defeated');+ });+});diff --git a/tests/api/dance-tip.test.js b/tests/api/dance-tip.test.jsindex 7adfd4119..d368ff750 100644--- a/tests/api/dance-tip.test.js+++ b/tests/api/dance-tip.test.js@@ -295,8 +295,8 @@ describe('twerk — pole style', () => {});describe('Bazaar discovery schema', () => {- it('marks the endpoint discoverable', () => {- expect(BAZAAR_SCHEMA.discoverable).toBe(true);+ it('marks the endpoint as delisted (internal-use, not agent-discoverable)', () => {+ expect(BAZAAR_SCHEMA.discoverable).toBe(false);});it("advertises every STYLES key in the input `dance` enum", () => {diff --git a/tests/api/v1-free-tier.test.js b/tests/api/v1-free-tier.test.jsnew file mode 100644index 000000000..782892f31--- /dev/null+++ b/tests/api/v1-free-tier.test.js@@ -0,0 +1,287 @@+// Free tier lane for the aggregator (api/v1/x/[...slug].js).+//+// An unauthenticated caller (no BYOK key, no three.ws credentials) on an+// endpoint marked `free: { perMin, perDay }` in api/v1/_providers.js gets a+// real per-IP quota BEFORE the x402 402 challenge — the tests pin the contract+// that makes "the free crypto API" true instead of marketing copy:+// • a free endpoint (coingecko/price) serves real upstream data with zero+// credentials, against a fetch stub shaped like the REAL CoinGecko response,+// • RateLimit-* + X-Free-Tier headers are present on every free response,+// • quota exhaustion falls through to the x402 lane (not a bare 429),+// • a non-free endpoint (openai/chat) never touches the free lane at all,+// • the catalog (GET /api/v1/x) exposes each endpoint's free quota (or false).+//+// The rate limiter is mocked (switchable per test) and the network is stubbed+// via global fetch, so the suite runs fully offline while exercising the real+// handler and the real executeUpstream/resolveUpstreamKey engine. getPaidHandler+// is stubbed to a minimal 402 responder so this suite stays scoped to the+// aggregator's OWN routing decision (free → serve, exhausted → hand off to the+// x402 lane); the x402 challenge's own correctness is covered by the existing+// x402 test suites (x402-discovery-parity, audit:x402-catalog, etc.).++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { Readable } from 'node:stream';++// Switchable free-lane quota results — flip per test.+let freeMinOk = true;+let freeDayOk = true;+const freeMinCalls = [];+const freeDayCalls = [];++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ apiV1: async () => ({ success: true, limit: 120, remaining: 119, reset: Date.now() + 60_000 }),+ apiV1FreeMin: async (key, perMin) => {+ freeMinCalls.push({ key, perMin });+ return freeMinOk+ ? { success: true, limit: perMin, remaining: perMin - 1, reset: Date.now() + 45_000 }+ : { success: false, limit: perMin, remaining: 0, reset: Date.now() + 45_000 };+ },+ apiV1FreeDay: async (key, perDay) => {+ freeDayCalls.push({ key, perDay });+ return freeDayOk+ ? { success: true, limit: perDay, remaining: perDay - 1, reset: Date.now() + 86_400_000 }+ : { success: false, limit: perDay, remaining: 0, reset: Date.now() + 86_400_000 };+ },+ },+ clientIp: () => '203.0.113.7',+}));++vi.mock('../../api/_lib/auth.js', () => ({+ authenticateBearer: async () => null,+ extractBearer: () => null,+ getSessionUser: async () => null,+ hasScope: () => true,+}));++const recordedEvents = [];+vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: (evt) => recordedEvents.push(evt),+}));++// Boundary stubs for infra this route never truly exercises in the free/402+// paths under test (mirrors tests/api/v1-text-to-3d.test.js's pattern).+vi.mock('../../api/_lib/db.js', () => ({+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: () => {} }));+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => null, drain: async () => {} }));++// Real executeUpstream/resolveUpstreamKey (exercised against the fetch stub+// below); getPaidHandler stubbed to a minimal, honest 402 responder so this+// suite proves the ROUTING decision (serve free vs. hand off to x402), not the+// paidEndpoint challenge internals (covered elsewhere).+const paidHandlerCalls = [];+vi.mock('../../api/_lib/aggregator.js', async () => {+ const actual = await vi.importActual('../../api/_lib/aggregator.js');+ return {+ ...actual,+ getPaidHandler: (provider, endpoint) => {+ paidHandlerCalls.push({ provider: provider.id, endpoint: endpoint.id });+ return async (req, res) => {+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ x402Version: 1, accepts: [], _stub: 'paidHandler' }));+ };+ },+ };+});++const ORIGINAL_FETCH = globalThis.fetch;++beforeEach(() => {+ freeMinOk = true;+ freeDayOk = true;+ freeMinCalls.length = 0;+ freeDayCalls.length = 0;+ recordedEvents.length = 0;+ paidHandlerCalls.length = 0;+});+afterEach(() => {+ globalThis.fetch = ORIGINAL_FETCH;+ vi.restoreAllMocks();+});++function makeReq({ method = 'GET', url, body = null, headers = {} } = {}) {+ const raw = body == null ? '' : JSON.stringify(body);+ const stream = Readable.from(raw ? [Buffer.from(raw)] : []);+ stream.method = method;+ stream.url = url;+ stream.headers = { host: 'three.ws', ...headers, ...(body != null ? { 'content-type': 'application/json' } : {}) };+ return stream;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) {+ this._h[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._h[k.toLowerCase()];+ },+ end(body) {+ this._body = body;+ this.writableEnded = true;+ },+ };+}++async function dispatch(req, res) {+ const mod = await import('../../api/v1/x/[...slug].js');+ await mod.default(req, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++// Real-shaped CoinGecko /simple/price response (no transform on coingecko/price+// — passthrough), so the fixture below IS the exact JSON the free lane returns.+const COINGECKO_PRICE_FIXTURE = { solana: { usd: 141.23 } };++function jsonFetchResponse(obj, { status = 200 } = {}) {+ return {+ ok: status >= 200 && status < 300,+ status,+ text: async () => JSON.stringify(obj),+ };+}++describe('free tier — serves a free endpoint with zero credentials', () => {+ it('coingecko/price returns real upstream data, no auth, no payment', async () => {+ globalThis.fetch = vi.fn(async (url) => {+ expect(String(url)).toContain('api.coingecko.com/api/v3/simple/price');+ expect(String(url)).toContain('ids=solana');+ return jsonFetchResponse(COINGECKO_PRICE_FIXTURE);+ });++ const req = makeReq({ url: '/api/v1/x/coingecko/price?ids=solana' });+ const res = makeRes();+ const { body } = await dispatch(req, res);++ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual(COINGECKO_PRICE_FIXTURE);+ expect(body._meta).toMatchObject({ provider: 'coingecko', endpoint: 'price', billing: 'free' });+ expect(body._meta.free_remaining).toEqual({ per_min: 29, per_day: 1999 });+ });++ it('sets X-Free-Tier and RateLimit-* headers on the free response', async () => {+ globalThis.fetch = vi.fn(async () => jsonFetchResponse(COINGECKO_PRICE_FIXTURE));+ const req = makeReq({ url: '/api/v1/x/coingecko/price?ids=solana' });+ const res = makeRes();+ await dispatch(req, res);++ expect(res._h['x-free-tier']).toBe('1');+ expect(res._h['ratelimit-limit']).toBeDefined();+ expect(res._h['ratelimit-remaining']).toBeDefined();+ expect(res._h['ratelimit-reset']).toBeDefined();+ });++ it('meters the free call with billing: free (funnel adoption is measurable)', async () => {+ globalThis.fetch = vi.fn(async () => jsonFetchResponse(COINGECKO_PRICE_FIXTURE));+ const req = makeReq({ url: '/api/v1/x/coingecko/price?ids=solana' });+ await dispatch(req, makeRes());++ expect(recordedEvents).toHaveLength(1);+ expect(recordedEvents[0]).toMatchObject({+ kind: 'api',+ tool: 'v1.x.coingecko.price',+ status: 'ok',+ meta: { billing: 'free', ip: '203.0.113.7' },+ });+ });++ it('checks both the per-minute and per-day buckets, keyed per provider/endpoint/IP', async () => {+ globalThis.fetch = vi.fn(async () => jsonFetchResponse(COINGECKO_PRICE_FIXTURE));+ await dispatch(makeReq({ url: '/api/v1/x/coingecko/price?ids=solana' }), makeRes());++ expect(freeMinCalls).toEqual([{ key: 'coingecko:price:203.0.113.7', perMin: 30 }]);+ expect(freeDayCalls).toEqual([{ key: 'coingecko:price:203.0.113.7', perDay: 2000 }]);+ });+});++describe('free tier — quota exhaustion falls through to the x402 lane', () => {+ it('over the daily quota → hands off to getPaidHandler (real 402), never calls the upstream', async () => {+ freeDayOk = false;+ globalThis.fetch = vi.fn(async () => {+ throw new Error('must not call the upstream once the free quota is exhausted');+ });++ const req = makeReq({ url: '/api/v1/x/coingecko/price?ids=solana' });+ const res = makeRes();+ const { body } = await dispatch(req, res);++ expect(res.statusCode).toBe(402);+ expect(body._stub).toBe('paidHandler');+ expect(paidHandlerCalls).toEqual([{ provider: 'coingecko', endpoint: 'price' }]);+ // Reset hint rides a header since the 402 body shape is spec-locked.+ expect(res._h['x-free-tier-reset']).toBeDefined();+ expect(() => new Date(res._h['x-free-tier-reset']).toISOString()).not.toThrow();+ expect(res._h['x-free-tier']).toBe('1');+ });++ it('over the per-minute burst quota also falls through, with burst-window headers', async () => {+ freeMinOk = false;+ globalThis.fetch = vi.fn(async () => {+ throw new Error('must not call the upstream once the free quota is exhausted');+ });++ const req = makeReq({ url: '/api/v1/x/coingecko/price?ids=solana' });+ const res = makeRes();+ const { body } = await dispatch(req, res);++ expect(res.statusCode).toBe(402);+ expect(body._stub).toBe('paidHandler');+ // The blocking bucket (perMin, limit 30) drives the RateLimit-* headers.+ expect(res._h['ratelimit-limit']).toBe('30');+ });+});++describe('free tier — a non-free endpoint never engages the free lane', () => {+ it('openai/chat 402s immediately without checking any free quota', async () => {+ const req = makeReq({+ method: 'POST',+ url: '/api/v1/x/openai/chat',+ body: { model: 'gpt-4o-mini', messages: [{ role: 'user', content: 'hi' }] },+ });+ const res = makeRes();+ const { body } = await dispatch(req, res);++ expect(res.statusCode).toBe(402);+ expect(body._stub).toBe('paidHandler');+ expect(paidHandlerCalls).toEqual([{ provider: 'openai', endpoint: 'chat' }]);+ expect(freeMinCalls).toHaveLength(0);+ expect(freeDayCalls).toHaveLength(0);+ expect(res._h['x-free-tier']).toBeUndefined();+ });+});++describe('free tier — catalog discovery', () => {+ it('GET /api/v1/x exposes each endpoint\'s free quota, or false when not free', async () => {+ const req = makeReq({ url: '/api/v1/x' });+ const res = makeRes();+ const { body } = await dispatch(req, res);++ expect(res.statusCode).toBe(200);+ expect(body.data.billing.free).toMatch(/free/i);++ const coingecko = body.data.providers.find((p) => p.id === 'coingecko');+ const price = coingecko.endpoints.find((e) => e.id === 'price');+ expect(price.free).toEqual({ perMin: 30, perDay: 2000 });+ const markets = coingecko.endpoints.find((e) => e.id === 'markets');+ expect(markets.free).toEqual({ perMin: 30, perDay: 2000 });++ const defillama = body.data.providers.find((p) => p.id === 'defillama');+ for (const e of defillama.endpoints) {+ expect(e.free).toEqual({ perMin: 30, perDay: 2000 });+ }++ const openai = body.data.providers.find((p) => p.id === 'openai');+ const chat = openai.endpoints.find((e) => e.id === 'chat');+ expect(chat.free).toBe(false);+ });+});diff --git a/tests/api/v1-provider-coingecko-expansion.test.js b/tests/api/v1-provider-coingecko-expansion.test.jsnew file mode 100644index 000000000..5a3ad1dad--- /dev/null+++ b/tests/api/v1-provider-coingecko-expansion.test.js@@ -0,0 +1,213 @@+// Tests for the CoinGecko provider's expanded endpoints (api/v1/_providers.js):+// coin, trending, token-price, global, ohlc — added alongside the original+// price/markets pair to give agents real coverage instead of two endpoints.+//+// No live network: transforms are pure functions, exercised against fixtures+// trimmed from REAL captures against api.coingecko.com on 2026-07-08 (full+// per-currency objects trimmed to `usd` only — the transform only ever reads+// `.usd`, so this is a faithful shape, not a mock of our own code) plus+// malformed payloads. Descriptor integrity + required-param enforcement via+// ENDPOINT_INDEX and the query() builders.++import { describe, it, expect } from 'vitest';+import { PROVIDERS, ENDPOINT_INDEX } from '../../api/v1/_providers.js';++const coingecko = PROVIDERS.find((p) => p.id === 'coingecko');+const ep = (id) => ENDPOINT_INDEX.get(`coingecko/${id}`).endpoint;++describe('coingecko provider — descriptor integrity', () => {+ it('exposes price, markets, coin, trending, token-price, global, ohlc — all indexed and free-tiered', () => {+ expect(coingecko.endpoints.map((e) => e.id)).toEqual([+ 'price',+ 'markets',+ 'coin',+ 'trending',+ 'token-price',+ 'global',+ 'ohlc',+ ]);+ for (const id of ['coin', 'trending', 'token-price', 'global', 'ohlc']) {+ const e = ENDPOINT_INDEX.get(`coingecko/${id}`);+ expect(e, `coingecko/${id} indexed`).toBeTruthy();+ expect(e.endpoint.method).toBe('GET');+ expect(e.endpoint.scope).toBe('agents:read');+ expect(e.endpoint.free).toEqual({ perMin: 20, perDay: 1500 });+ expect(typeof e.endpoint.summary).toBe('string');+ expect(e.endpoint.summary.length).toBeGreaterThan(0);+ expect(e.endpoint.params).toBeTruthy();+ }+ });+});++// ── coin ─────────────────────────────────────────────────────────────────────+describe('coingecko/coin', () => {+ const COIN_FIXTURE = {+ id: 'solana',+ symbol: 'sol',+ name: 'Solana',+ market_cap_rank: 7,+ description: { en: 'Solana is a high-performance Layer 1 blockchain. '.repeat(30) },+ market_data: {+ current_price: { usd: 80.4 },+ ath: { usd: 293.31 },+ ath_change_percentage: { usd: -72.6 },+ atl: { usd: 0.500801 },+ atl_change_percentage: { usd: 15960.2 },+ market_cap: { usd: 46794500862 },+ fully_diluted_valuation: { usd: 50700000000 },+ total_volume: { usd: 2179803115 },+ circulating_supply: 581713615.3253177,+ total_supply: 629846029.4214532,+ max_supply: null,+ price_change_percentage_24h: -2.16777,+ price_change_percentage_7d: 9.76133,+ price_change_percentage_30d: 5.1,+ last_updated: '2026-07-08T00:00:00.000Z',+ },+ };++ it('slims to market essentials with description truncated to 500 chars', () => {+ const out = ep('coin').transform(COIN_FIXTURE);+ expect(out).toMatchObject({+ id: 'solana',+ symbol: 'sol',+ name: 'Solana',+ market_cap_rank: 7,+ price_usd: 80.4,+ ath_usd: 293.31,+ atl_usd: 0.500801,+ market_cap_usd: 46794500862,+ total_volume_usd: 2179803115,+ circulating_supply: 581713615.3253177,+ price_change_percentage_24h: -2.16777,+ price_change_percentage_7d: 9.76133,+ });+ expect(out.description.length).toBe(500);+ });++ it('tolerates a null description and malformed payloads', () => {+ expect(() => ep('coin').transform({ ...COIN_FIXTURE, description: undefined })).not.toThrow();+ expect(ep('coin').transform(null)).toBeNull();+ expect(ep('coin').transform('nope')).toBe('nope');+ });++ it('requires id and applies the four flatten flags', () => {+ expect(() => ep('coin').path({})).toThrow(/id/);+ const q = ep('coin').query({ id: 'solana' });+ expect(q).toEqual({+ localization: 'false',+ tickers: 'false',+ community_data: 'false',+ developer_data: 'false',+ });+ });+});++// ── trending ─────────────────────────────────────────────────────────────────+describe('coingecko/trending', () => {+ const TRENDING_FIXTURE = {+ coins: [+ { item: { id: 'solana', symbol: 'sol', name: 'Solana', market_cap_rank: 7, price_btc: 0.00126444 } },+ ],+ categories: [+ { id: 107, name: 'Launchpad', slug: 'launchpad', coins_count: '198', data: { market_cap: 5354790876.7 } },+ ],+ };++ it('slims coins and categories', () => {+ const out = ep('trending').transform(TRENDING_FIXTURE);+ expect(out).toEqual({+ coins: [{ id: 'solana', symbol: 'sol', name: 'Solana', market_cap_rank: 7, price_btc: 0.00126444 }],+ categories: [{ id: 107, name: 'Launchpad', slug: 'launchpad', coins_count: '198', market_cap_usd: 5354790876.7 }],+ });+ });++ it('tolerates malformed payloads', () => {+ expect(ep('trending').transform(null)).toEqual({ coins: [], categories: [] });+ expect(ep('trending').transform({})).toEqual({ coins: [], categories: [] });+ });++ it('takes no required params', () => {+ expect(ep('trending').query({})).toEqual({});+ });+});++// ── token-price ──────────────────────────────────────────────────────────────+describe('coingecko/token-price', () => {+ it('defaults platform to solana and requires addresses', () => {+ expect(() => ep('token-price').query({})).toThrow(/addresses/);+ expect(+ ep('token-price').query({ addresses: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' }),+ ).toEqual({+ contract_addresses: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ vs_currencies: 'usd',+ });+ });++ it('honors an explicit platform + vs_currencies', () => {+ expect(ep('token-price').path({ platform: 'ethereum' })).toBe('/simple/token_price/ethereum');+ expect(+ ep('token-price').query({ addresses: '0xabc', vs_currencies: 'eur' }),+ ).toEqual({ contract_addresses: '0xabc', vs_currencies: 'eur' });+ });+});++// ── global ───────────────────────────────────────────────────────────────────+describe('coingecko/global', () => {+ const GLOBAL_FIXTURE = {+ data: {+ active_cryptocurrencies: 17339,+ markets: 1493,+ total_market_cap: { usd: 2274686337878.679 },+ total_volume: { usd: 91000000000 },+ market_cap_percentage: { btc: 55.2, eth: 12.1 },+ market_cap_change_percentage_24h_usd: -1.2,+ updated_at: 1783468699,+ },+ };++ it('slims to the market snapshot fields', () => {+ expect(ep('global').transform(GLOBAL_FIXTURE)).toEqual({+ active_cryptocurrencies: 17339,+ markets: 1493,+ total_market_cap_usd: 2274686337878.679,+ total_volume_usd: 91000000000,+ btc_dominance: 55.2,+ eth_dominance: 12.1,+ market_cap_change_percentage_24h_usd: -1.2,+ updated_at: 1783468699,+ });+ });++ it('tolerates a missing data block', () => {+ expect(ep('global').transform({})).toMatchObject({ active_cryptocurrencies: undefined });+ expect(ep('global').transform(null)).toMatchObject({ active_cryptocurrencies: undefined });+ });+});++// ── ohlc ─────────────────────────────────────────────────────────────────────+describe('coingecko/ohlc', () => {+ const OHLC_FIXTURE = [+ [1783386000000, 82.27, 82.34, 82.22, 82.3],+ [1783387800000, 82.32, 82.32, 82.0, 82.0],+ ];++ it('maps each candle to a named object', () => {+ expect(ep('ohlc').transform(OHLC_FIXTURE)).toEqual([+ { t: 1783386000000, o: 82.27, h: 82.34, l: 82.22, c: 82.3 },+ { t: 1783387800000, o: 82.32, h: 82.32, l: 82.0, c: 82.0 },+ ]);+ });++ it('tolerates malformed payloads', () => {+ expect(ep('ohlc').transform(null)).toEqual([]);+ expect(ep('ohlc').transform('nope')).toEqual([]);+ });++ it('requires id and clamps days to the allowed set', () => {+ expect(() => ep('ohlc').path({})).toThrow(/id/);+ expect(ep('ohlc').query({ id: 'solana' })).toEqual({ vs_currency: 'usd', days: '1' });+ expect(ep('ohlc').query({ id: 'solana', days: '7' })).toEqual({ vs_currency: 'usd', days: '7' });+ expect(ep('ohlc').query({ id: 'solana', days: '999' })).toEqual({ vs_currency: 'usd', days: '1' });+ });+});diff --git a/tests/api/v1-provider-dexscreener.test.js b/tests/api/v1-provider-dexscreener.test.jsnew file mode 100644index 000000000..9aa7fb6d6--- /dev/null+++ b/tests/api/v1-provider-dexscreener.test.js@@ -0,0 +1,249 @@+// Tests for the DexScreener aggregator provider (api/v1/_providers.js).+//+// DexScreener is a keyless public API — no key, no BYOK header. This provider+// replaces the paid token-intel/three-intel DexScreener passthroughs with the+// honest free surface agents can already get at the source.+//+// No live network here — the descriptor's transforms are pure functions, so we+// exercise them against fixtures captured from the REAL api.dexscreener.com on+// 2026-07-08 (verified live: /latest/dex/tokens/{addr}, /latest/dex/search,+// /latest/dex/pairs/{chain}/{pair}, /token-profiles/latest/v1,+// /token-boosts/latest/v1 — the $THREE mint used throughout) plus malformed+// payloads, and assert descriptor integrity via ENDPOINT_INDEX and+// required-param enforcement via the path()/query() builders.++import { describe, it, expect } from 'vitest';+import { PROVIDERS, ENDPOINT_INDEX } from '../../api/v1/_providers.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const dexscreener = PROVIDERS.find((p) => p.id === 'dexscreener');+const ep = (id) => ENDPOINT_INDEX.get(`dexscreener/${id}`).endpoint;++// ── Fixtures: trimmed but real-shaped captures from api.dexscreener.com ──────+// Captured live 2026-07-08 for the $THREE mint on its deepest pumpswap pair.+const PAIR = {+ chainId: 'solana',+ dexId: 'pumpswap',+ url: 'https://dexscreener.com/solana/5byl7mzolabynwmpzkpkjf4mgkz7febzranos19pre2z',+ pairAddress: '5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z',+ baseToken: { address: THREE_MINT, name: 'three.ws', symbol: 'three' },+ quoteToken: { address: 'So11111111111111111111111111111111111111112', name: 'Wrapped SOL', symbol: 'SOL' },+ priceNative: '0.00001627',+ priceUsd: '0.001311',+ txns: { m5: { buys: 3, sells: 1 }, h1: { buys: 322, sells: 139 }, h6: { buys: 5792, sells: 1973 }, h24: { buys: 21764, sells: 8364 } },+ volume: { h24: 355485.08, h6: 58293.76, h1: 6777.49, m5: 346.6 },+ priceChange: { m5: 1.12, h1: 1.1, h6: -17.02, h24: -11.46 },+ liquidity: { usd: 183541.34, base: 69958010, quote: 1138.3755 },+ fdv: 1311470,+ marketCap: 1311470,+ pairCreatedAt: 1777446541000,+ info: {+ imageUrl: 'https://cdn.dexscreener.com/cms/images/j22gRd6Z2GowwOvM?width=800&height=800&quality=95&format=auto',+ websites: [{ url: 'https://three.ws/', label: 'Website' }],+ socials: [{ url: 'https://x.com/trythreews', type: 'twitter' }],+ },+ boosts: { active: 10 },+};++const LOW_LIQ_PAIR = {+ chainId: 'solana',+ dexId: 'raydium',+ pairAddress: 'LowLiqPairAddress1111111111111111111111111',+ baseToken: { address: THREE_MINT, name: 'three.ws', symbol: 'three' },+ quoteToken: { symbol: 'USDC' },+ priceUsd: '0.001300',+ liquidity: { usd: 500 },+ volume: { h24: 10 },+ priceChange: { h24: -1 },+ txns: { h24: { buys: 1, sells: 0 } },+};++const PAIRS_RESPONSE = { schemaVersion: '1.0.0', pairs: [LOW_LIQ_PAIR, PAIR] };++const PROFILE = {+ url: 'https://dexscreener.com/solana/d41maqylwbehvzprm674oyiqwa4ghyt9zxw4ckq3pump',+ chainId: 'solana',+ tokenAddress: 'D41mAqyLwbEhVZpRM674oyiQWa4ghYT9zXw4CKQ3pump',+ icon: 'https://cdn.dexscreener.com/cms/images/EfOCKeRcqdv7b_lA?width=64&height=64&fit=crop&quality=95&format=auto',+ description: 'The White Whale LIVE on pumpfun',+ links: [{ type: 'twitter', url: 'https://x.com/i/communities/2036583572375740715' }],+ cto: false,+ updatedAt: '2026-07-08T00:38:43.039Z',+};++const BOOST = {+ url: 'https://dexscreener.com/solana/7aj9sdzw6sodb8ajnekesewtqvvhyz4gg85h3c1ypump',+ chainId: 'solana',+ tokenAddress: '7AJ9sdZW6Sodb8ajnEkESeWtQVVHyZ4Gg85H3c1Ypump',+ description: 'The Rizzler is the king of all bulls, he runs the trenches.',+ icon: 'ALdFj3-jvz_VfihQ',+ links: [+ { type: 'twitter', url: 'https://x.com/i/communities/2000665667108774278' },+ { type: 'telegram', url: 'https://t.me/rizzbull' },+ ],+ totalAmount: 60,+ amount: 10,+};++describe('dexscreener provider — descriptor integrity', () => {+ it('is registered as a keyless crypto-market-data provider', () => {+ expect(dexscreener).toBeTruthy();+ expect(dexscreener.category).toBe('crypto-market-data');+ expect(dexscreener.base).toBe('https://api.dexscreener.com');+ expect(dexscreener.requiresKey).toBe(false);+ expect(dexscreener.byokHeader).toBeNull();+ expect(dexscreener.envVar).toBeNull();+ });++ it('exposes token, search, pair, profiles, boosts — all indexed, GET, scoped, priced, free-tiered', () => {+ expect(dexscreener.endpoints.map((e) => e.id)).toEqual(['token', 'search', 'pair', 'profiles', 'boosts']);+ for (const id of ['token', 'search', 'pair', 'profiles', 'boosts']) {+ const e = ENDPOINT_INDEX.get(`dexscreener/${id}`);+ expect(e, `dexscreener/${id} indexed`).toBeTruthy();+ expect(e.endpoint.method).toBe('GET');+ expect(e.endpoint.scope).toBe('agents:read');+ expect(e.endpoint.priceAtomics).toBe('1000');+ expect(typeof e.endpoint.summary).toBe('string');+ expect(e.endpoint.summary.length).toBeGreaterThan(0);+ expect(e.endpoint.params).toBeTruthy();+ }+ });++ it('sets tighter free quotas for profiles/boosts than the pair endpoints', () => {+ for (const id of ['token', 'search', 'pair']) {+ expect(ep(id).free).toEqual({ perMin: 30, perDay: 3000 });+ }+ for (const id of ['profiles', 'boosts']) {+ expect(ep(id).free).toEqual({ perMin: 10, perDay: 500 });+ }+ });+});++describe('dexscreener/token — path + transform', () => {+ it('requires addresses and caps the path at 30 comma-separated entries', () => {+ expect(() => ep('token').path({})).toThrow(/addresses/);+ expect(ep('token').path({ addresses: THREE_MINT })).toBe(`/latest/dex/tokens/${THREE_MINT}`);+ const many = Array.from({ length: 40 }, (_, i) => `mint${i}`).join(',');+ const path = ep('token').path({ addresses: many });+ expect(decodeURIComponent(path).split(',')).toHaveLength(30);+ });++ it('slims pairs to the agent-useful subset, sorted by liquidity desc', () => {+ const out = ep('token').transform(PAIRS_RESPONSE);+ expect(out).toEqual([+ {+ chainId: 'solana',+ dexId: 'pumpswap',+ pairAddress: '5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z',+ baseToken: { address: THREE_MINT, name: 'three.ws', symbol: 'three' },+ quoteToken: { symbol: 'SOL' },+ priceUsd: '0.001311',+ priceNative: '0.00001627',+ liquidity: { usd: 183541.34 },+ fdv: 1311470,+ marketCap: 1311470,+ volume: { h24: 355485.08 },+ priceChange: { h1: 1.1, h6: -17.02, h24: -11.46 },+ txns: { h24: { buys: 21764, sells: 8364 } },+ pairCreatedAt: 1777446541000,+ url: 'https://dexscreener.com/solana/5byl7mzolabynwmpzkpkjf4mgkz7febzranos19pre2z',+ },+ {+ chainId: 'solana',+ dexId: 'raydium',+ pairAddress: 'LowLiqPairAddress1111111111111111111111111',+ baseToken: { address: THREE_MINT, name: 'three.ws', symbol: 'three' },+ quoteToken: { symbol: 'USDC' },+ priceUsd: '0.001300',+ priceNative: null,+ liquidity: { usd: 500 },+ fdv: null,+ marketCap: null,+ volume: { h24: 10 },+ priceChange: { h1: null, h6: null, h24: -1 },+ txns: { h24: { buys: 1, sells: 0 } },+ pairCreatedAt: null,+ url: null,+ },+ ]);+ });++ it('caps at 30 pairs and tolerates malformed payloads', () => {+ const many = { pairs: Array.from({ length: 50 }, (_, i) => ({ ...PAIR, pairAddress: `p${i}`, liquidity: { usd: i } })) };+ expect(ep('token').transform(many)).toHaveLength(30);+ expect(ep('token').transform(null)).toEqual([]);+ expect(ep('token').transform({})).toEqual([]);+ expect(ep('token').transform({ pairs: null })).toEqual([]);+ expect(ep('token').transform({ pairs: [null, {}] })).toHaveLength(1);+ });+});++describe('dexscreener/search — path + transform', () => {+ it('requires q and caps at 20 pairs', () => {+ expect(() => ep('search').query({})).toThrow(/q/);+ expect(ep('search').query({ q: 'three.ws' })).toEqual({ q: 'three.ws' });+ const many = { pairs: Array.from({ length: 30 }, (_, i) => ({ ...PAIR, pairAddress: `p${i}` })) };+ expect(ep('search').transform(many)).toHaveLength(20);+ });+});++describe('dexscreener/pair — path + transform', () => {+ it('requires chain and pair, builds the path-param style route', () => {+ expect(() => ep('pair').path({ pair: 'x' })).toThrow(/chain/);+ expect(() => ep('pair').path({ chain: 'solana' })).toThrow(/pair/);+ expect(ep('pair').path({ chain: 'solana', pair: '5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z' })).toBe(+ '/latest/dex/pairs/solana/5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z',+ );+ });++ it('slims the returned pair the same way as token/search', () => {+ const out = ep('pair').transform({ schemaVersion: '1.0.0', pairs: [PAIR] });+ expect(out[0].pairAddress).toBe('5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z');+ expect(out[0]).not.toHaveProperty('info');+ expect(out[0]).not.toHaveProperty('boosts');+ });+});++describe('dexscreener/profiles — transform', () => {+ it('slims each profile to chainId/tokenAddress/description/links, cap 30', () => {+ const out = ep('profiles').transform([PROFILE]);+ expect(out).toEqual([+ {+ chainId: 'solana',+ tokenAddress: 'D41mAqyLwbEhVZpRM674oyiQWa4ghYT9zXw4CKQ3pump',+ description: 'The White Whale LIVE on pumpfun',+ links: [{ type: 'twitter', url: 'https://x.com/i/communities/2036583572375740715' }],+ },+ ]);+ });++ it('caps at 30 and tolerates malformed payloads', () => {+ const many = Array.from({ length: 50 }, (_, i) => ({ ...PROFILE, tokenAddress: `t${i}` }));+ expect(ep('profiles').transform(many)).toHaveLength(30);+ expect(ep('profiles').transform(null)).toEqual([]);+ expect(ep('profiles').transform({})).toEqual([]);+ expect(ep('profiles').transform([null, {}])).toHaveLength(1);+ });+});++describe('dexscreener/boosts — transform', () => {+ it('slims each boosted token the same way as profiles', () => {+ const out = ep('boosts').transform([BOOST]);+ expect(out).toEqual([+ {+ chainId: 'solana',+ tokenAddress: '7AJ9sdZW6Sodb8ajnEkESeWtQVVHyZ4Gg85H3c1Ypump',+ description: 'The Rizzler is the king of all bulls, he runs the trenches.',+ links: [+ { type: 'twitter', url: 'https://x.com/i/communities/2000665667108774278' },+ { type: 'telegram', url: 'https://t.me/rizzbull' },+ ],+ },+ ]);+ });++ it('tolerates malformed payloads', () => {+ expect(ep('boosts').transform(null)).toEqual([]);+ expect(ep('boosts').transform('rate limited')).toEqual([]);+ });+});diff --git a/tests/api/v1-provider-llama-expansion.test.js b/tests/api/v1-provider-llama-expansion.test.jsnew file mode 100644index 000000000..bcbdd7223--- /dev/null+++ b/tests/api/v1-provider-llama-expansion.test.js@@ -0,0 +1,181 @@+// Tests for the DefiLlama provider's expanded endpoints (chains, protocol,+// chain-tvl) plus the two new sibling providers on DefiLlama's other bases —+// llama-prices (coins.llama.fi) and llama-stablecoins (stablecoins.llama.fi).+// api/v1/_providers.js is the single source of truth; these are pure+// descriptor/transform tests against fixtures trimmed from REAL captures on+// 2026-07-08, plus malformed payloads. No live network.++import { describe, it, expect } from 'vitest';+import { PROVIDERS, ENDPOINT_INDEX } from '../../api/v1/_providers.js';++const defillama = PROVIDERS.find((p) => p.id === 'defillama');+const dep = (id) => ENDPOINT_INDEX.get(`defillama/${id}`).endpoint;++describe('defillama provider — expanded descriptor integrity', () => {+ it('exposes protocols, tvl, chains, protocol, chain-tvl — all indexed and free-tiered', () => {+ expect(defillama.endpoints.map((e) => e.id)).toEqual(['protocols', 'tvl', 'chains', 'protocol', 'chain-tvl']);+ for (const id of ['chains', 'protocol', 'chain-tvl']) {+ const e = ENDPOINT_INDEX.get(`defillama/${id}`);+ expect(e, `defillama/${id} indexed`).toBeTruthy();+ expect(e.endpoint.method).toBe('GET');+ expect(e.endpoint.scope).toBe('agents:read');+ expect(e.endpoint.free).toEqual({ perMin: 30, perDay: 2000 });+ expect(typeof e.endpoint.summary).toBe('string');+ }+ });+});++describe('defillama/chains', () => {+ const CHAINS_FIXTURE = [+ { gecko_id: 'harmony', tvl: 203131.77, tokenSymbol: 'ONE', chainId: 1666600000 },+ { gecko_id: null, tvl: 95716125.93, tokenSymbol: null, chainId: 4663, name: 'Robinhood Chain' },+ { gecko_id: 'ethereum', tvl: 55000000000, tokenSymbol: 'ETH', chainId: 1, name: 'Ethereum' },+ ];++ it('slims and sorts by tvl desc', () => {+ const out = dep('chains').transform(CHAINS_FIXTURE);+ expect(out.map((c) => c.tokenSymbol)).toEqual(['ETH', null, 'ONE']);+ expect(out[0]).toEqual({ name: 'Ethereum', tvl: 55000000000, tokenSymbol: 'ETH', chainId: 1 });+ });++ it('tolerates malformed payloads', () => {+ expect(dep('chains').transform(null)).toEqual([]);+ expect(dep('chains').transform({})).toEqual([]);+ });+});++describe('defillama/protocol', () => {+ const PROTOCOL_FIXTURE = {+ name: 'Uniswap',+ category: 'Dexes',+ chains: ['Ethereum', 'Base', 'Arbitrum'],+ currentChainTvls: { Ethereum: 2110431947, Base: 411425289 },+ mcap: 5000000000,+ tvl: Array.from({ length: 50 }, (_, i) => ({ date: 1600000000 + i * 86400, totalLiquidityUSD: 1000 + i })),+ };++ it('slims to name/category/chains/current + last 30 tvl points', () => {+ const out = dep('protocol').transform(PROTOCOL_FIXTURE);+ expect(out.name).toBe('Uniswap');+ expect(out.category).toBe('Dexes');+ expect(out.chains).toEqual(['Ethereum', 'Base', 'Arbitrum']);+ expect(out.current_chain_tvls_usd).toEqual({ Ethereum: 2110431947, Base: 411425289 });+ expect(out.mcap_usd).toBe(5000000000);+ expect(out.tvl_usd).toHaveLength(30);+ expect(out.tvl_usd[0]).toEqual({ date: PROTOCOL_FIXTURE.tvl[20].date, tvl: PROTOCOL_FIXTURE.tvl[20].totalLiquidityUSD });+ });++ it('handles a short tvl series and malformed payloads', () => {+ expect(dep('protocol').transform({ name: 'x', tvl: [] }).tvl_usd).toEqual([]);+ expect(dep('protocol').transform(null)).toBeNull();+ });++ it('requires slug', () => {+ expect(() => dep('protocol').path({})).toThrow(/slug/);+ expect(dep('protocol').path({ slug: 'uniswap' })).toBe('/protocol/uniswap');+ });+});++describe('defillama/chain-tvl', () => {+ const SERIES_FIXTURE = Array.from({ length: 120 }, (_, i) => ({ date: 1600000000 + i * 86400, tvl: 100 + i }));++ it('slims to the last 90 points', () => {+ const out = dep('chain-tvl').transform(SERIES_FIXTURE);+ expect(out).toHaveLength(90);+ expect(out[0]).toEqual({ date: SERIES_FIXTURE[30].date, tvl: SERIES_FIXTURE[30].tvl });+ expect(out[89]).toEqual({ date: SERIES_FIXTURE[119].date, tvl: SERIES_FIXTURE[119].tvl });+ });++ it('tolerates malformed payloads', () => {+ expect(dep('chain-tvl').transform(null)).toEqual([]);+ });++ it('requires chain', () => {+ expect(() => dep('chain-tvl').path({})).toThrow(/chain/);+ expect(dep('chain-tvl').path({ chain: 'Solana' })).toBe('/v2/historicalChainTvl/Solana');+ });+});++// ── llama-prices ─────────────────────────────────────────────────────────────+describe('llama-prices provider', () => {+ const provider = PROVIDERS.find((p) => p.id === 'llama-prices');+ const pep = (id) => ENDPOINT_INDEX.get(`llama-prices/${id}`).endpoint;++ it('is registered as a keyless provider on coins.llama.fi', () => {+ expect(provider).toBeTruthy();+ expect(provider.base).toBe('https://coins.llama.fi');+ expect(provider.requiresKey).toBe(false);+ expect(provider.endpoints.map((e) => e.id)).toEqual(['current']);+ expect(pep('current').free).toEqual({ perMin: 30, perDay: 2000 });+ });++ it('current — normalizes the coins map and requires "coins"', () => {+ const fixture = {+ coins: {+ 'solana:FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump': {+ decimals: 6,+ symbol: 'THREE',+ price: 0.0012908347845446426,+ timestamp: 1783468699,+ confidence: 0.99,+ },+ },+ };+ expect(pep('current').transform(fixture)).toEqual({+ 'solana:FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump': {+ price: 0.0012908347845446426,+ symbol: 'THREE',+ decimals: 6,+ timestamp: 1783468699,+ confidence: 0.99,+ },+ });+ expect(() => pep('current').path({})).toThrow(/coins/);+ });++ it('tolerates malformed payloads', () => {+ expect(pep('current').transform(null)).toEqual({});+ expect(pep('current').transform({})).toEqual({});+ });+});++// ── llama-stablecoins ────────────────────────────────────────────────────────+describe('llama-stablecoins provider', () => {+ const provider = PROVIDERS.find((p) => p.id === 'llama-stablecoins');+ const sep = (id) => ENDPOINT_INDEX.get(`llama-stablecoins/${id}`).endpoint;++ it('is registered as a keyless provider on stablecoins.llama.fi', () => {+ expect(provider).toBeTruthy();+ expect(provider.base).toBe('https://stablecoins.llama.fi');+ expect(provider.category).toBe('defi-data');+ expect(provider.endpoints.map((e) => e.id)).toEqual(['list']);+ });++ it('list — slims, sorts by circulating desc, caps 50', () => {+ const assets = Array.from({ length: 60 }, (_, i) => ({+ name: `Stable${i}`,+ symbol: `S${i}`,+ pegType: 'peggedUSD',+ price: 1,+ circulating: { peggedUSD: i },+ circulatingPrevDay: { peggedUSD: i - 1 },+ }));+ const out = sep('list').transform({ peggedAssets: assets });+ expect(out).toHaveLength(50);+ expect(out[0].circulating_usd).toBe(59);+ expect(out[0]).toEqual({+ name: 'Stable59',+ symbol: 'S59',+ pegType: 'peggedUSD',+ price: 1,+ circulating_usd: 59,+ circulating_prev_day_usd: 58,+ });+ });++ it('always sends includePrices=true and tolerates malformed payloads', () => {+ expect(sep('list').query({})).toEqual({ includePrices: 'true' });+ expect(sep('list').transform(null)).toEqual([]);+ expect(sep('list').transform({})).toEqual([]);+ });+});diff --git a/tests/api/v1-provider-solana.test.js b/tests/api/v1-provider-solana.test.jsnew file mode 100644index 000000000..e35a7be45--- /dev/null+++ b/tests/api/v1-provider-solana.test.js@@ -0,0 +1,359 @@+// Tests for the Solana on-chain-reads aggregator provider (api/v1/_providers.js).+//+// This provider wraps Solana JSON-RPC as plain GET endpoints so an agent never+// hand-builds a JSON-RPC body. The caller side is GET; the upstream call is a+// POST JSON-RPC body — that GET→POST lift is the `upstreamMethod` field+// (api/_lib/aggregator.js `executeUpstream`), covered here via the `body()`+// builders (which receive the caller's query params, exactly as the engine+// calls them for a GET-caller/POST-upstream endpoint).+//+// No live network here — the descriptor's transforms are pure functions,+// exercised against fixtures captured from the REAL configured Solana RPC+// (public mainnet fallback) on 2026-07-08: getBalance, getTokenSupply,+// getTokenAccountsByOwner, getAccountInfo (all live-verified), plus the+// documented getTokenLargestAccounts/getRecentPrioritizationFees shapes and a+// real getTransaction capture for a $THREE transfer — plus RPC-error payloads,+// percentile math, and required-param enforcement via the body() builders.++import { describe, it, expect } from 'vitest';+import { PROVIDERS, ENDPOINT_INDEX } from '../../api/v1/_providers.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const solana = PROVIDERS.find((p) => p.id === 'solana');+const ep = (id) => ENDPOINT_INDEX.get(`solana/${id}`).endpoint;++const RPC_ERROR_INVALID_PARAM = { jsonrpc: '2.0', id: 1, error: { code: -32602, message: 'Invalid param: Invalid' } };+const RPC_ERROR_RATE_LIMITED = { jsonrpc: '2.0', id: 1, error: { code: 429, message: 'Too many requests for a specific RPC call' } };++describe('solana provider — descriptor integrity', () => {+ it('is registered as a keyless onchain-data provider on a resolved RPC base', () => {+ expect(solana).toBeTruthy();+ expect(solana.category).toBe('onchain-data');+ expect(solana.requiresKey).toBe(false);+ expect(solana.byokHeader).toBeNull();+ expect(solana.envVar).toBeNull();+ expect(typeof solana.base).toBe('string');+ expect(solana.base.startsWith('http')).toBe(true);+ });++ it('exposes all 7 reads — GET caller-side, POST upstream, scoped, priced, free-tiered', () => {+ expect(solana.endpoints.map((e) => e.id)).toEqual([+ 'balance',+ 'token-holdings',+ 'token-supply',+ 'largest-holders',+ 'transaction',+ 'account',+ 'priority-fees',+ ]);+ for (const e of solana.endpoints) {+ expect(e.method, `${e.id} caller method`).toBe('GET');+ expect(e.upstreamMethod, `${e.id} upstream method`).toBe('POST');+ expect(e.scope).toBe('agents:read');+ expect(e.priceAtomics).toBe('1000');+ expect(e.free).toEqual({ perMin: 20, perDay: 2000 });+ expect(typeof e.summary).toBe('string');+ expect(e.summary.length).toBeGreaterThan(0);+ expect(e.params).toBeTruthy();+ expect(typeof e.body).toBe('function');+ }+ });+});++describe('solana/balance', () => {+ it('requires address and builds a getBalance JSON-RPC body', () => {+ expect(() => ep('balance').body({})).toThrow(/address/);+ expect(ep('balance').body({ address: '11111111111111111111111111111111' })).toEqual({+ jsonrpc: '2.0',+ id: 1,+ method: 'getBalance',+ params: ['11111111111111111111111111111111'],+ });+ });++ it('converts lamports to sol from a real-shaped response', () => {+ // Captured live 2026-07-08: getBalance("11111111111111111111111111111111").+ const fixture = { jsonrpc: '2.0', id: 1, result: { context: { apiVersion: '4.1.0', slot: 431484341 }, value: 1 } };+ expect(ep('balance').transform(fixture)).toEqual({ lamports: 1, sol: 1e-9 });+ });++ it('surfaces an RPC error as a client-fault HTTP error, not a payload', () => {+ expect(() => ep('balance').transform(RPC_ERROR_INVALID_PARAM)).toThrow(/Invalid param/);+ try {+ ep('balance').transform(RPC_ERROR_INVALID_PARAM);+ } catch (e) {+ expect(e.status).toBe(400);+ expect(e.code).toBe('rpc_invalid_request');+ }+ });++ it('maps a non-caller-fault RPC error (rate limit) to a 502', () => {+ try {+ ep('balance').transform(RPC_ERROR_RATE_LIMITED);+ throw new Error('should have thrown');+ } catch (e) {+ expect(e.status).toBe(502);+ expect(e.code).toBe('rpc_upstream_error');+ }+ });+});++describe('solana/token-holdings', () => {+ it('requires owner and builds a getTokenAccountsByOwner JSON-RPC body', () => {+ expect(() => ep('token-holdings').body({})).toThrow(/owner/);+ const body = ep('token-holdings').body({ owner: 'DdCL89km6hCardM5rNbEKEiQUFDhp2NG6nz9qkbbQpNw' });+ expect(body.method).toBe('getTokenAccountsByOwner');+ expect(body.params[0]).toBe('DdCL89km6hCardM5rNbEKEiQUFDhp2NG6nz9qkbbQpNw');+ expect(body.params[1]).toEqual({ programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' });+ expect(body.params[2]).toEqual({ encoding: 'jsonParsed' });+ });++ it('slims parsed token accounts, filters zero balances, sorts largest first', () => {+ // Captured live 2026-07-08: getTokenAccountsByOwner for a real wallet.+ const fixture = {+ jsonrpc: '2.0',+ id: 1,+ result: {+ context: { slot: 431484541 },+ value: [+ {+ pubkey: 'FPk1bPtMfxPg1AQDbZ3fccg88FziAnssB2z9L29aRvHc',+ account: {+ data: {+ program: 'spl-token',+ parsed: {+ info: {+ mint: '6iKXPHDxHBMnsmpcwoMbLi8xedKvBXpwQErEhdBVGBB',+ owner: 'DdCL89km6hCardM5rNbEKEiQUFDhp2NG6nz9qkbbQpNw',+ state: 'initialized',+ tokenAmount: { amount: '3514399525981', decimals: 6, uiAmount: 3514399.525981, uiAmountString: '3514399.525981' },+ },+ type: 'account',+ },+ },+ },+ },+ {+ pubkey: '2gKwXijKbC5Sdr7VgZV5c9WCH9bZ7MjGES6f49GCD2Gx',+ account: {+ data: {+ program: 'spl-token',+ parsed: {+ info: {+ mint: 'JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN',+ owner: 'DdCL89km6hCardM5rNbEKEiQUFDhp2NG6nz9qkbbQpNw',+ state: 'initialized',+ tokenAmount: { amount: '0', decimals: 6, uiAmount: 0, uiAmountString: '0' },+ },+ type: 'account',+ },+ },+ },+ },+ ],+ },+ };+ expect(ep('token-holdings').transform(fixture)).toEqual([+ { mint: '6iKXPHDxHBMnsmpcwoMbLi8xedKvBXpwQErEhdBVGBB', amount: '3514399525981', decimals: 6, uiAmount: 3514399.525981 },+ ]);+ });++ it('tolerates an empty/malformed value array', () => {+ expect(ep('token-holdings').transform({ result: { value: [] } })).toEqual([]);+ expect(ep('token-holdings').transform({ result: {} })).toEqual([]);+ });+});++describe('solana/token-supply', () => {+ it('requires mint and builds a getTokenSupply JSON-RPC body', () => {+ expect(() => ep('token-supply').body({})).toThrow(/mint/);+ expect(ep('token-supply').body({ mint: THREE_MINT })).toEqual({+ jsonrpc: '2.0',+ id: 1,+ method: 'getTokenSupply',+ params: [THREE_MINT],+ });+ });++ it('slims the real $THREE supply response', () => {+ // Captured live 2026-07-08: getTokenSupply(THREE_MINT).+ const fixture = {+ jsonrpc: '2.0',+ id: 1,+ result: { context: { apiVersion: '4.1.0', slot: 431484344 }, value: { amount: '999683493875007', decimals: 6, uiAmount: 999683493.875007, uiAmountString: '999683493.875007' } },+ };+ expect(ep('token-supply').transform(fixture)).toEqual({ amount: '999683493875007', decimals: 6, uiAmount: 999683493.875007 });+ });++ it('404s a mint with no value (not an SPL token)', () => {+ expect(() => ep('token-supply').transform({ result: { value: null } })).toThrow(/mint not found/);+ try {+ ep('token-supply').transform({ result: { value: null } });+ } catch (e) {+ expect(e.status).toBe(404);+ expect(e.code).toBe('mint_not_found');+ }+ });+});++describe('solana/largest-holders', () => {+ it('requires mint and caps at 20', () => {+ expect(() => ep('largest-holders').body({})).toThrow(/mint/);+ // Documented shape: result.value is an array of up to 20 holder accounts.+ const fixture = {+ result: {+ value: Array.from({ length: 25 }, (_, i) => ({ address: `Holder${i}`, amount: String(1000 - i), decimals: 6, uiAmount: 1000 - i })),+ },+ };+ const out = ep('largest-holders').transform(fixture);+ expect(out).toHaveLength(20);+ expect(out[0]).toEqual({ address: 'Holder0', uiAmount: 1000 });+ });++ it('tolerates a malformed value array', () => {+ expect(ep('largest-holders').transform({ result: {} })).toEqual([]);+ });+});++describe('solana/transaction', () => {+ it('requires signature and builds a getTransaction JSON-RPC body', () => {+ expect(() => ep('transaction').body({})).toThrow(/signature/);+ const sig = '2Gz7S6GCjoJb6wj2s4prUZj75B36n2bpa6GRh7op7qv8eBMP5hucG4a3N2pSga8t9frWJhoHjj3eJDaFEEgCv19W';+ expect(ep('transaction').body({ signature: sig })).toEqual({+ jsonrpc: '2.0',+ id: 1,+ method: 'getTransaction',+ params: [sig, { encoding: 'jsonParsed', maxSupportedTransactionVersion: 0 }],+ });+ });++ it('slims a real transaction to slot/blockTime/fee/err/signers/logs/token deltas', () => {+ // Trimmed but real-shaped capture (2026-07-08) of a $THREE transferChecked+ // instruction — full instruction tree/rewards/inner instructions dropped,+ // meta.preTokenBalances/postTokenBalances/logMessages/accountKeys kept.+ const fixture = {+ jsonrpc: '2.0',+ id: 1,+ result: {+ blockTime: 1783471283,+ slot: 431484410,+ transaction: {+ message: {+ accountKeys: [+ { pubkey: 'DdCL89km6hCardM5rNbEKEiQUFDhp2NG6nz9qkbbQpNw', signer: true, source: 'transaction', writable: true },+ { pubkey: '4MGFkWT5ML3M5dRkMmLqHXD8SbELvj5a9ywGyzpLVnCW', signer: false, source: 'transaction', writable: true },+ ],+ },+ signatures: ['2Gz7S6GCjoJb6wj2s4prUZj75B36n2bpa6GRh7op7qv8eBMP5hucG4a3N2pSga8t9frWJhoHjj3eJDaFEEgCv19W'],+ },+ meta: {+ err: null,+ fee: 40665,+ logMessages: Array.from({ length: 30 }, (_, i) => `log line ${i}`),+ preTokenBalances: [+ { accountIndex: 2, mint: THREE_MINT, owner: 'DdCL89km6hCardM5rNbEKEiQUFDhp2NG6nz9qkbbQpNw', uiTokenAmount: { amount: '18394271251', decimals: 6, uiAmount: 18394.271251 } },+ ],+ postTokenBalances: [+ { accountIndex: 2, mint: THREE_MINT, owner: 'DdCL89km6hCardM5rNbEKEiQUFDhp2NG6nz9qkbbQpNw', uiTokenAmount: { amount: '0', decimals: 6, uiAmount: null } },+ { accountIndex: 3, mint: 'So11111111111111111111111111111111111111112', owner: 'NewHolderXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', uiTokenAmount: { amount: '5000000000', decimals: 9, uiAmount: 5 } },+ ],+ },+ },+ };+ const out = ep('transaction').transform(fixture);+ expect(out.slot).toBe(431484410);+ expect(out.blockTime).toBe(1783471283);+ expect(out.fee).toBe(40665);+ expect(out.err).toBeNull();+ expect(out.signers).toEqual(['DdCL89km6hCardM5rNbEKEiQUFDhp2NG6nz9qkbbQpNw']);+ expect(out.logMessages).toHaveLength(20); // truncated to first 20 lines+ expect(out.tokenBalanceChanges).toContainEqual({ mint: THREE_MINT, owner: 'DdCL89km6hCardM5rNbEKEiQUFDhp2NG6nz9qkbbQpNw', delta: -18394.271251 });+ expect(out.tokenBalanceChanges).toContainEqual({ mint: 'So11111111111111111111111111111111111111112', owner: 'NewHolderXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', delta: 5 });+ });++ it('404s an unknown/unfinalized signature (result: null)', () => {+ expect(() => ep('transaction').transform({ jsonrpc: '2.0', id: 1, result: null })).toThrow(/transaction not found/);+ try {+ ep('transaction').transform({ jsonrpc: '2.0', id: 1, result: null });+ } catch (e) {+ expect(e.status).toBe(404);+ expect(e.code).toBe('transaction_not_found');+ }+ });+});++describe('solana/account', () => {+ it('requires address and builds a getAccountInfo JSON-RPC body', () => {+ expect(() => ep('account').body({})).toThrow(/address/);+ expect(ep('account').body({ address: THREE_MINT })).toEqual({+ jsonrpc: '2.0',+ id: 1,+ method: 'getAccountInfo',+ params: [THREE_MINT, { encoding: 'jsonParsed' }],+ });+ });++ it('slims the real $THREE mint account (Token-2022, jsonParsed)', () => {+ // Captured live 2026-07-08: getAccountInfo(THREE_MINT, jsonParsed).+ const fixture = {+ jsonrpc: '2.0',+ id: 1,+ result: {+ context: { apiVersion: '4.1.0', slot: 431484381 },+ value: {+ data: { program: 'spl-token-2022', parsed: { info: { decimals: 6, supply: '999683493875007' }, type: 'mint' }, space: 411 },+ executable: false,+ lamports: 46804176073,+ owner: 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',+ space: 411,+ },+ },+ };+ expect(ep('account').transform(fixture)).toEqual({+ owner: 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',+ lamports: 46804176073,+ executable: false,+ program: 'spl-token-2022',+ parsedType: 'mint',+ });+ });++ it('404s an unfunded/nonexistent address (value: null)', () => {+ expect(() => ep('account').transform({ result: { value: null } })).toThrow(/account not found/);+ try {+ ep('account').transform({ result: { value: null } });+ } catch (e) {+ expect(e.status).toBe(404);+ expect(e.code).toBe('account_not_found');+ }+ });+});++describe('solana/priority-fees', () => {+ it('takes no params and builds a getRecentPrioritizationFees JSON-RPC body', () => {+ expect(ep('priority-fees').body({})).toEqual({ jsonrpc: '2.0', id: 1, method: 'getRecentPrioritizationFees', params: [] });+ });++ it('computes p50/p75/p95/max from a real-shaped fee list', () => {+ // Captured live 2026-07-08: getRecentPrioritizationFees([]) — last ~150 slots.+ const fees = [0, 0, 0, 100, 200, 5000];+ const fixture = { jsonrpc: '2.0', id: 1, result: fees.map((prioritizationFee, i) => ({ slot: 431484227 + i, prioritizationFee })) };+ const out = ep('priority-fees').transform(fixture);+ expect(out.max).toBe(5000);+ expect(out.p50).toBeGreaterThanOrEqual(0);+ expect(out.p95).toBeLessThanOrEqual(5000);+ expect(out.p50).toBeLessThanOrEqual(out.p75);+ expect(out.p75).toBeLessThanOrEqual(out.p95);+ expect(out.p95).toBeLessThanOrEqual(out.max);+ });++ it('returns all zeros for an empty fee list', () => {+ expect(ep('priority-fees').transform({ jsonrpc: '2.0', id: 1, result: [] })).toEqual({ p50: 0, p75: 0, p95: 0, max: 0 });+ });++ it('is order-independent (percentiles sort internally)', () => {+ const asc = { result: [10, 20, 30, 40, 100].map((f) => ({ prioritizationFee: f })) };+ const desc = { result: [100, 40, 30, 20, 10].map((f) => ({ prioritizationFee: f })) };+ expect(ep('priority-fees').transform(asc)).toEqual(ep('priority-fees').transform(desc));+ });+});diff --git a/tests/api/v1-resolve.test.js b/tests/api/v1-resolve.test.jsnew file mode 100644index 000000000..8517a97e7--- /dev/null+++ b/tests/api/v1-resolve.test.js@@ -0,0 +1,221 @@+// GET /api/v1/resolve — free ENS + SNS name resolution.+//+// The endpoint wraps two existing platform resolvers rather than+// reimplementing them: the shared EVM failover provider (api/_lib/evm/rpc.js+// `evmFallbackProvider`, the same one api/agents/ens/[name].js already uses+// for ENS) and src/solana/sns.js's `resolveSnsName` / `reverseLookupAddress`+// (the exact module api/sns.js and api/sns-subdomain.js already share for+// SNS). These tests mock those two modules at the boundary and exercise the+// real handler: forward .eth / .sol resolution, reverse address lookups in+// both directions, an unsupported suffix (400), an unresolvable name/address+// (404, not 500), the per-IP rate limit (429), and the catalog registration.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { Readable } from 'node:stream';++const THREE_ETH_ADDR = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';+const THREE_SOL_ADDR = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// Switchable per-IP quota result — flip `quotaOk` per test.+let quotaOk = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ apiV1: async () => ({ success: true, limit: 120, remaining: 119, reset: Date.now() + 60_000 }),+ resolveIp: async () =>+ quotaOk+ ? { success: true, limit: 30, remaining: 29, reset: Date.now() + 60_000 }+ : { success: false, limit: 30, remaining: 0, reset: Date.now() + 60_000 },+ },+ clientIp: () => '203.0.113.9',+}));++// SNS resolver stub — mirrors api/sns.js's own dependency, src/solana/sns.js.+let snsForward = async () => null;+let snsReverse = async () => null;+vi.mock('../../src/solana/sns.js', () => ({+ resolveSnsName: (name) => snsForward(name),+ reverseLookupAddress: (addr) => snsReverse(addr),+}));++// EVM provider stub — mirrors evmFallbackProvider's ethers Provider surface+// (resolveName / lookupAddress), the same shape api/agents/ens/[name].js relies on.+let ensForward = async () => null;+let ensReverse = async () => null;+vi.mock('../../api/_lib/evm/rpc.js', () => ({+ evmFallbackProvider: async () => ({+ resolveName: (name) => ensForward(name),+ lookupAddress: (addr) => ensReverse(addr),+ }),+}));++beforeEach(() => {+ quotaOk = true;+ snsForward = async () => null;+ snsReverse = async () => null;+ ensForward = async () => null;+ ensReverse = async () => null;+});+afterEach(() => {+ vi.restoreAllMocks();+});++function makeReq({ url = '/api/v1/resolve', host = 'three.ws' } = {}) {+ const stream = Readable.from([]);+ stream.method = 'GET';+ stream.url = url;+ stream.headers = { host };+ return stream;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; this.writableEnded = true; },+ };+}++async function dispatch(req, res) {+ const mod = await import('../../api/v1/resolve.js');+ await mod.default(req, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++// ── Forward resolution ──────────────────────────────────────────────────────+describe('GET /api/v1/resolve — forward', () => {+ it('resolves a .eth name to its Ethereum address via ENS', async () => {+ ensForward = async (name) => (name === 'vitalik.eth' ? THREE_ETH_ADDR : null);+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/resolve?name=vitalik.eth' }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({+ name: 'vitalik.eth',+ chain: 'ethereum',+ address: THREE_ETH_ADDR,+ source: 'ens',+ });+ expect(res.getHeader('cache-control')).toMatch(/max-age=300/);+ });++ it('resolves a .sol name to its Solana owner via SNS', async () => {+ snsForward = async (name) => (name === 'bonfida.sol' ? THREE_SOL_ADDR : null);+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/resolve?name=bonfida.sol' }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({+ name: 'bonfida.sol',+ chain: 'solana',+ address: THREE_SOL_ADDR,+ source: 'sns',+ });+ });++ it('returns 404 not_found (never 500) when an ENS name does not resolve', async () => {+ ensForward = async () => null;+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/resolve?name=doesnotexist12345.eth' }), makeRes());+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('returns 404 not_found (never 500) when a .sol name does not resolve', async () => {+ snsForward = async () => null;+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/resolve?name=doesnotexist12345.sol' }), makeRes());+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('rejects an unsupported suffix with 400 naming the supported suffixes', async () => {+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/resolve?name=foo.com' }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('unsupported_suffix');+ expect(body.error_description).toMatch(/\.eth/);+ expect(body.error_description).toMatch(/\.sol/);+ });++ it('rejects a request with neither name nor address', async () => {+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/resolve' }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('rejects a request passing both name and address', async () => {+ const url = `/api/v1/resolve?name=vitalik.eth&address=${THREE_SOL_ADDR}`;+ const { res, body } = await dispatch(makeReq({ url }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('validation_error');+ });+});++// ── Reverse resolution ──────────────────────────────────────────────────────+describe('GET /api/v1/resolve — reverse', () => {+ it('reverse-resolves a Solana address to its primary SNS domain', async () => {+ snsReverse = async (addr) => (addr === THREE_SOL_ADDR ? 'bonfida.sol' : null);+ const { res, body } = await dispatch(makeReq({ url: `/api/v1/resolve?address=${THREE_SOL_ADDR}` }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({+ address: THREE_SOL_ADDR,+ chain: 'solana',+ name: 'bonfida.sol',+ source: 'sns',+ });+ });++ it('reverse-resolves an Ethereum address to its primary ENS name', async () => {+ ensReverse = async (addr) => (addr === THREE_ETH_ADDR ? 'vitalik.eth' : null);+ const { res, body } = await dispatch(makeReq({ url: `/api/v1/resolve?address=${THREE_ETH_ADDR}` }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({+ address: THREE_ETH_ADDR,+ chain: 'ethereum',+ name: 'vitalik.eth',+ source: 'ens',+ });+ });++ it('returns 404 not_found when a Solana address has no favorite domain', async () => {+ snsReverse = async () => null;+ const { res, body } = await dispatch(makeReq({ url: `/api/v1/resolve?address=${THREE_SOL_ADDR}` }), makeRes());+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('rejects a malformed address with 400', async () => {+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/resolve?address=not-an-address' }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('rejects a chain hint that mismatches the address format', async () => {+ const url = `/api/v1/resolve?address=${THREE_SOL_ADDR}&chain=ethereum`;+ const { res, body } = await dispatch(makeReq({ url }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('validation_error');+ });+});++// ── Rate limit ───────────────────────────────────────────────────────────────+describe('GET /api/v1/resolve — rate limit', () => {+ it('returns 429 when the per-IP quota is exhausted', async () => {+ quotaOk = false;+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/resolve?name=vitalik.eth' }), makeRes());+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ expect(res.getHeader('retry-after')).toBeTruthy();+ });+});++// ── Catalog registration ────────────────────────────────────────────────────+describe('/api/v1 catalog', () => {+ it('registers the resolve endpoint as a free, public GET', async () => {+ const { CATALOG } = await import('../../api/v1/_catalog.js');+ const entry = CATALOG.find((e) => e.id === 'v1.resolve');+ expect(entry).toBeTruthy();+ expect(entry.method).toBe('GET');+ expect(entry.path).toBe('/api/v1/resolve');+ expect(entry.auth).toBe('public');+ expect(entry.params.name).toBeTruthy();+ expect(entry.params.address).toBeTruthy();+ });+});diff --git a/tests/api/v1-sentiment-intel.test.js b/tests/api/v1-sentiment-intel.test.jsnew file mode 100644index 000000000..9025d5c20--- /dev/null+++ b/tests/api/v1-sentiment-intel.test.js@@ -0,0 +1,217 @@+// POST /api/v1/sentiment, GET /api/v1/market/intel, GET /api/v1/market/projects+//+// These three v1 routes already existed (afc56503b) but were undocumented and+// untested. This suite pins the contract catalog prompt 08 audits:+// • sentiment is genuinely public (no aixbt/session/key needed) and rate-limited+// per-IP by the gateway's shared apiV1 bucket, not silently unlimited.+// • market/intel + market/projects degrade to an honest 503 `not_configured`+// (never a 500) when AIXBT_API_KEY is absent, and serve real aixbt-shaped+// data — publicly, no auth required — the moment it is.+// • the gateway's per-IP rate limit (429) applies to every route.+// • the /api/v1 catalog entries match observed behavior (path/auth/summary).+//+// The rate limiter, auth resolution, and usage metering are mocked (pure unit+// boundary); aixbt itself is mocked at `api/_lib/aixbt.js` with real-shaped+// fixtures rather than re-stubbing its HTTP client.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Readable } from 'node:stream';++let apiV1Ok = true;+let aixbtGlobalOk = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ apiV1: async () =>+ apiV1Ok+ ? { success: true, limit: 120, remaining: 119, reset: Date.now() + 60_000 }+ : { success: false, limit: 120, remaining: 0, reset: Date.now() + 60_000 },+ aixbtGlobal: async () =>+ aixbtGlobalOk+ ? { success: true, limit: 1800, remaining: 1799, reset: Date.now() + 3_600_000 }+ : { success: false, limit: 1800, remaining: 0, reset: Date.now() + 3_600_000 },+ },+ clientIp: () => '203.0.113.7',+}));++vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: async () => null,+ authenticateBearer: async () => null,+ extractBearer: () => null,+ hasScope: () => true,+}));++vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: () => {},+}));++let aixbtEnabledFlag = true;+vi.mock('../../api/_lib/aixbt.js', () => ({+ aixbtEnabled: () => aixbtEnabledFlag,+ getIntel: async ({ limit, category, chain } = {}) => ({+ intel: [+ {+ id: 'intel-1',+ text: 'Momentum building in AI-agent infrastructure narratives.',+ category: category || 'narrative',+ chain: chain || 'solana',+ createdAt: '2026-07-08T00:00:00.000Z',+ },+ ].slice(0, limit || 20),+ pagination: { limit: limit || 20, page: 1, hasMore: false },+ }),+ getProjects: async ({ limit, page, names, chain } = {}) => ({+ projects: [+ {+ id: 'proj-1',+ name: names || 'three.ws',+ ticker: 'THREE',+ chain: chain || 'solana',+ momentumScore: 87,+ },+ ].slice(0, limit || 20),+ pagination: { limit: limit || 20, page: page || 1, hasMore: false },+ }),+}));++beforeEach(() => {+ apiV1Ok = true;+ aixbtGlobalOk = true;+ aixbtEnabledFlag = true;+});++function makeReq({ method = 'GET', url, host = 'three.ws', body } = {}) {+ const payload = body ? Buffer.from(JSON.stringify(body)) : null;+ const stream = payload ? Readable.from([payload]) : Readable.from([]);+ stream.method = method;+ stream.url = url;+ stream.headers = {+ host,+ ...(payload ? { 'content-type': 'application/json' } : {}),+ };+ return stream;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; this.writableEnded = true; },+ };+}++async function dispatch(modPath, req, res) {+ vi.resetModules();+ const mod = await import(modPath);+ await mod.default(req, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++// ── POST /api/v1/sentiment — genuinely public, no key needed ──────────────────+describe('POST /api/v1/sentiment', () => {+ it('classifies text with no auth required', async () => {+ const req = makeReq({ method: 'POST', url: '/api/v1/sentiment', body: { text: 'This is amazing, bullish, great news!' } });+ const { res, body } = await dispatch('../../api/v1/sentiment.js', req, makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.data.sentiment).toBe('Positive');+ expect(typeof body.data.score).toBe('number');+ });++ it('rejects an empty text with 400', async () => {+ const req = makeReq({ method: 'POST', url: '/api/v1/sentiment', body: { text: ' ' } });+ const { res, body } = await dispatch('../../api/v1/sentiment.js', req, makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('rate-limits per IP (429, not a hang or 500)', async () => {+ apiV1Ok = false;+ const req = makeReq({ method: 'POST', url: '/api/v1/sentiment', body: { text: 'hello' } });+ const { res, body } = await dispatch('../../api/v1/sentiment.js', req, makeRes());+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ });+});++// ── GET /api/v1/market/intel — free once aixbt is configured, honest 503 if not+describe('GET /api/v1/market/intel', () => {+ it('returns 503 not_configured when AIXBT_API_KEY is absent — never a 500', async () => {+ aixbtEnabledFlag = false;+ const req = makeReq({ url: '/api/v1/market/intel' });+ const { res, body } = await dispatch('../../api/v1/market/intel.js', req, makeRes());+ // The gateway's `wrap` renders the canonical missing-env envelope: 503+ // not_configured, with a ref instead of the raw var name (which secret is+ // unset is operator information — see api/_lib/http.js `wrap`). The+ // operator-facing detail (AIXBT_API_KEY) is logged server-side.+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('not_configured');+ expect(body.error_description).toMatch(/not configured on this deployment/i);+ });++ it('serves real-shaped intel publicly with no auth once configured', async () => {+ const req = makeReq({ url: '/api/v1/market/intel?limit=5&category=narrative' });+ const { res, body } = await dispatch('../../api/v1/market/intel.js', req, makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.data.source).toBe('aixbt');+ expect(Array.isArray(body.data.intel)).toBe(true);+ expect(body.data.intel[0]).toMatchObject({ id: 'intel-1', category: 'narrative' });+ });++ it('returns 429 when the shared aixbt ceiling is exhausted', async () => {+ aixbtGlobalOk = false;+ const req = makeReq({ url: '/api/v1/market/intel' });+ const { res, body } = await dispatch('../../api/v1/market/intel.js', req, makeRes());+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ });++ it('rate-limits per IP at the gateway level (429)', async () => {+ apiV1Ok = false;+ const req = makeReq({ url: '/api/v1/market/intel' });+ const { res, body } = await dispatch('../../api/v1/market/intel.js', req, makeRes());+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ });+});++// ── GET /api/v1/market/projects — same contract as market/intel ───────────────+describe('GET /api/v1/market/projects', () => {+ it('returns 503 not_configured when AIXBT_API_KEY is absent', async () => {+ aixbtEnabledFlag = false;+ const req = makeReq({ url: '/api/v1/market/projects' });+ const { res, body } = await dispatch('../../api/v1/market/projects.js', req, makeRes());+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('not_configured');+ expect(body.error_description).toMatch(/not configured on this deployment/i);+ });++ it('serves real-shaped, momentum-ranked projects publicly once configured', async () => {+ const req = makeReq({ url: '/api/v1/market/projects?limit=10&chain=solana' });+ const { res, body } = await dispatch('../../api/v1/market/projects.js', req, makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.data.source).toBe('aixbt');+ expect(body.data.projects[0]).toMatchObject({ id: 'proj-1', chain: 'solana' });+ });+});++// ── /api/v1 catalog — entries match observed behavior ──────────────────────────+describe('/api/v1 catalog — sentiment + market intel/projects', () => {+ it('registers all three with accurate path/auth/summary', async () => {+ const { CATALOG } = await import('../../api/v1/_catalog.js');++ const sentiment = CATALOG.find((e) => e.id === 'v1.sentiment');+ expect(sentiment).toMatchObject({ method: 'POST', path: '/api/v1/sentiment', auth: 'public' });+ expect(sentiment.summary).toMatch(/sentiment/i);++ const intel = CATALOG.find((e) => e.id === 'v1.market.intel');+ expect(intel).toMatchObject({ method: 'GET', path: '/api/v1/market/intel', auth: 'optional' });+ expect(intel.summary).toMatch(/narrative|intelligence/i);++ const projects = CATALOG.find((e) => e.id === 'v1.market.projects');+ expect(projects).toMatchObject({ method: 'GET', path: '/api/v1/market/projects', auth: 'optional' });+ expect(projects.summary).toMatch(/momentum|projects/i);+ });+});diff --git a/tests/api/x402-embody.test.js b/tests/api/x402-embody.test.jsnew file mode 100644index 000000000..f3e22ee61--- /dev/null+++ b/tests/api/x402-embody.test.js@@ -0,0 +1,167 @@+// Tests for POST /api/x402/embody (api/x402/embody.js) — the paid one-call+// embodiment endpoint: prompt/image → rigged GLB → durable persona → embed.+//+// The generate/rig/persona boundaries are dependency-injected so runEmbodyChain+// is exercised end-to-end offline against real-shaped forge/persona payloads —+// no network, no GPU, no payment. Validation is checked directly (it runs+// post-verify / pre-settle, so a rejected body is never charged).++import { describe, it, expect } from 'vitest';+import { runEmbodyChain, _validate, _buildBundle } from '../../api/x402/embody.js';+import { TTS_VOICE_IDS, DEFAULT_VOICE } from '../../api/_lib/tts-voices.js';++const BASE = 'https://three.ws';++// Real-shaped forge terminal payloads.+const genDone = { status: 'done', glb_url: 'https://pub-xxxx.r2.dev/forge/anon/mesh.glb', backend: 'nvidia', tier: 'draft' };+const rigDone = { status: 'done', glb_url: 'https://pub-xxxx.r2.dev/forge/anon/rigged.glb' };++function fakeGenerate(result = genDone) { return async () => result; }+function fakeRig(result = rigDone) { return async () => result; }+function fakeCreatePersona() {+ return async (input) => ({+ id: 'persona_test123abc',+ owner_id: null,+ name: input.name,+ glb_url: input.glbUrl,+ glb_key: 'personas/persona_test123abc.glb',+ voice: input.voice,+ emotion_baseline: 'neutral',+ look: input.look,+ source_prompt: input.sourcePrompt,+ turn_count: 0,+ });+}++// ── Validation ──────────────────────────────────────────────────────────────+describe('embody validation', () => {+ it('requires a name', () => {+ expect(() => _validate({ prompt: 'a knight' })).toThrow(/name is required/);+ });+ it('rejects an over-long name', () => {+ expect(() => _validate({ name: 'x'.repeat(65), prompt: 'a knight' })).toThrow(/≤64/);+ });+ it('requires exactly one of prompt / image_url', () => {+ expect(() => _validate({ name: 'A' })).toThrow(/either a prompt or an image_url/);+ expect(() => _validate({ name: 'A', prompt: 'x', image_url: 'https://e.com/i.png' })).toThrow(/exactly one/);+ });+ it('rejects a malformed image_url', () => {+ expect(() => _validate({ name: 'A', image_url: 'not-a-url' })).toThrow(/valid URL/);+ expect(() => _validate({ name: 'A', image_url: 'ftp://e.com/i.png' })).toThrow(/http/);+ });+ it('defaults voice to the platform default and accepts a valid voice', () => {+ expect(_validate({ name: 'A', prompt: 'x' }).voice).toBe(DEFAULT_VOICE);+ expect(_validate({ name: 'A', prompt: 'x', voice: TTS_VOICE_IDS[1] }).voice).toBe(TTS_VOICE_IDS[1]);+ });+ it('rejects an unknown voice with the valid list', () => {+ let err;+ try { _validate({ name: 'A', prompt: 'x', voice: 'gilbert' }); } catch (e) { err = e; }+ expect(err.code).toBe('invalid_voice');+ expect(err.valid_voices).toEqual(TTS_VOICE_IDS);+ });+ it('accepts a valid prompt request and clamps personality', () => {+ const v = _validate({ name: ' Nova ', prompt: ' a scout ', personality: 'p'.repeat(700) });+ expect(v.name).toBe('Nova');+ expect(v.prompt).toBe('a scout');+ expect(v.personality.length).toBe(600);+ });+});++// ── Chain ───────────────────────────────────────────────────────────────────+describe('runEmbodyChain', () => {+ it('generates, rigs, and mints a durable persona', async () => {+ const out = await runEmbodyChain(+ { base: BASE, name: 'Nova', prompt: 'a scout', personality: 'curious', voice: 'nova' },+ { generateFn: fakeGenerate(), rigFn: fakeRig(), createPersonaFn: fakeCreatePersona() },+ );+ expect(out.rigged).toBe(true);+ expect(out.glbUrl).toBe(rigDone.glb_url); // rigged GLB wins+ expect(out.persona.id).toBe('persona_test123abc');+ expect(out.persona.look).toEqual({ rigged: true, style: 'curious' });+ });++ it('passes image_url through as a reconstruction input', async () => {+ let captured;+ const gen = async (_b, args) => { captured = args; return genDone; };+ await runEmbodyChain(+ { base: BASE, name: 'A', prompt: '', imageUrl: 'https://e.com/i.png', personality: '', voice: 'nova' },+ { generateFn: gen, rigFn: fakeRig(), createPersonaFn: fakeCreatePersona() },+ );+ expect(captured.imageUrls).toEqual(['https://e.com/i.png']);+ expect(captured.prompt).toBeUndefined();+ });++ it('degrades to the un-rigged mesh when rigging fails (never a hard failure)', async () => {+ const out = await runEmbodyChain(+ { base: BASE, name: 'A', prompt: 'a rock creature', personality: '', voice: 'nova' },+ { generateFn: fakeGenerate(), rigFn: async () => { throw new Error('rig lane down'); }, createPersonaFn: fakeCreatePersona() },+ );+ expect(out.rigged).toBe(false);+ expect(out.glbUrl).toBe(genDone.glb_url); // falls back to the mesh+ });++ it('degrades to the mesh when rigging times out', async () => {+ const out = await runEmbodyChain(+ { base: BASE, name: 'A', prompt: 'x', personality: '', voice: 'nova' },+ { generateFn: fakeGenerate(), rigFn: fakeRig({ _timedOut: true }), createPersonaFn: fakeCreatePersona() },+ );+ expect(out.rigged).toBe(false);+ expect(out.glbUrl).toBe(genDone.glb_url);+ });++ it('throws generation_timeout (no persona) when generation times out', async () => {+ let err;+ try {+ await runEmbodyChain(+ { base: BASE, name: 'A', prompt: 'x', personality: '', voice: 'nova' },+ { generateFn: fakeGenerate({ _timedOut: true }), rigFn: fakeRig(), createPersonaFn: fakeCreatePersona() },+ );+ } catch (e) { err = e; }+ expect(err.code).toBe('generation_timeout');+ expect(err.status).toBe(504);+ });++ it('throws generation_failed when generation returns no model', async () => {+ let err;+ try {+ await runEmbodyChain(+ { base: BASE, name: 'A', prompt: 'x', personality: '', voice: 'nova' },+ { generateFn: fakeGenerate({ status: 'done' }), rigFn: fakeRig(), createPersonaFn: fakeCreatePersona() },+ );+ } catch (e) { err = e; }+ expect(err.code).toBe('generation_failed');+ });+});++// ── Bundle / embed ──────────────────────────────────────────────────────────+describe('buildBundle', () => {+ const chain = {+ persona: { id: 'persona_abc', glb_url: 'https://pub-xxxx.r2.dev/personas/persona_abc.glb' },+ glbUrl: 'https://pub-xxxx.r2.dev/personas/persona_abc.glb',+ rigged: true,+ voice: 'nova',+ name: 'Nova',+ };++ it('returns every documented field, all resolvable', () => {+ const b = _buildBundle(BASE, chain);+ expect(b.agent_id).toBe('persona_abc');+ expect(b.glb_url).toBe(chain.glbUrl);+ expect(b.viewer_url).toBe(`${BASE}/viewer?src=${encodeURIComponent(chain.glbUrl)}`);+ expect(b.reload_url).toBe(`${BASE}/api/mcp3d/persona?id=persona_abc`);+ expect(b.voice).toBe('nova');+ expect(b.rigged).toBe(true);+ expect(b.name).toBe('Nova');+ });++ it('embed_html is a single self-contained iframe pointing at the persona embed', () => {+ const b = _buildBundle(BASE, chain);+ expect(b.embed_html).toMatch(/^<iframe /);+ expect(b.embed_html).toContain('persona=persona_abc');+ expect(b.embed_html).toContain('allowfullscreen');+ // profile_url is the same hosted presence page the iframe frames+ expect(b.profile_url).toContain('/embodiment/embed');+ expect(b.profile_url).toContain('persona=persona_abc');+ expect(b.embed_html).toContain(b.profile_url.replace(/&/g, '&'));+ });+});diff --git a/tests/api/x402-pipeline.test.js b/tests/api/x402-pipeline.test.jsindex f9306fb60..487e7753c 100644--- a/tests/api/x402-pipeline.test.js+++ b/tests/api/x402-pipeline.test.js@@ -136,6 +136,12 @@ function makeReq({ method = 'POST', url = '/api/x402/pipeline', headers = {}, bo}const PAID = { 'x-payment': 'stub-payment-proof' };+// A distinct proof for any second paid POST in this file: the real anti-replay+// guard (api/_lib/x402/payment-identifier-server.js#checkCache) keys on a hash+// of the raw X-PAYMENT header, so two different request bodies reusing the same+// literal header collide as a payment-proof conflict (409) — correct behavior+// for a real proof, but a test needs a unique header per distinct paid request.+const PAID_2 = { 'x-payment': 'stub-payment-proof-2' };beforeEach(() => {gcpControl.next = () => ({ status: 'running' });@@ -267,7 +273,7 @@ describe('POST /api/x402/pipeline — paid job + per-stage progress, end to end'describe('POST /api/x402/pipeline — partial-failure semantics', () => {it('marks the job failed at the failing stage but keeps completed outputs', async () => {const res = makeRes();- await handler(makeReq({ body: { stages: ['generate', 'rig'], prompt: 'a brass owl' }, headers: PAID }), res);+ await handler(makeReq({ body: { stages: ['generate', 'rig'], prompt: 'a brass owl' }, headers: PAID_2 }), res);const submit = JSON.parse(res.body);const { job_id: jobId, job_token: token } = submit;diff --git a/tests/api/x402-spec.test.js b/tests/api/x402-spec.test.jsindex ee4001929..e38ff7671 100644--- a/tests/api/x402-spec.test.js+++ b/tests/api/x402-spec.test.js@@ -628,7 +628,7 @@ describe('solanaSettleable', () => {describe('buildExactRequirements', () => {// Shared accept builder for the hand-rolled endpoints (model-check, mint-to-mesh,- // vanity, vanity-verifiable, revenue-vision). Solana always leads; Base only rides+ // vanity, vanity-verifiable, mint-to-mesh-batch). Solana always leads; Base only rides// along when settleable, so a dead Base facilitator is never advertised.const SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';const BASE = 'eip155:8453';diff --git a/tests/bnb-babt-check-endpoint.test.js b/tests/bnb-babt-check-endpoint.test.jsnew file mode 100644index 000000000..dc3b650ed--- /dev/null+++ b/tests/bnb-babt-check-endpoint.test.js@@ -0,0 +1,148 @@+/**+ * GET /api/bnb/babt-check — integration tests.+ *+ * `../api/_lib/bnb/babt.js` and `../api/_lib/rate-limit.js` are mocked so the+ * suite runs deterministically without a live RPC/Redis (kept in its own+ * file, separate from tests/bnb-babt.test.js, because vi.mock hoists+ * per-file and would otherwise shadow the real `hasBabt` those lib tests+ * exercise directly).+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const HOLDER = '0x04d1C36842430A169D132ADa68006e6Bb9E3808b';+const NON_HOLDER = '0x000000000000000000000000000000000000dEaD';++const rl = { ok: true };+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })) },+ clientIp: () => '127.0.0.1',+}));++const babtState = { mode: 'holder' };+vi.mock('../api/_lib/bnb/babt.js', async () => {+ const actual = await vi.importActual('../api/_lib/bnb/babt.js');+ return {+ ...actual,+ hasBabt: vi.fn(async (address, network) => {+ const net = network || 'bscMainnet';+ if (babtState.mode === 'unreachable') {+ throw new actual.BabtCheckError('BABT balanceOf read failed: timeout', {+ network: net,+ contract: actual.BABT_CONTRACTS[net],+ });+ }+ return {+ address,+ network: net,+ holdsBabt: babtState.mode === 'holder',+ tokenId: babtState.mode === 'holder' ? '1316815' : null,+ contract: actual.BABT_CONTRACTS[net],+ checkedAt: new Date().toISOString(),+ };+ }),+ };+});++const { default: handler } = await import('../api/bnb/babt-check.js');++function makeReq(url) {+ return { method: 'GET', url, headers: { origin: 'https://three.ws' }, socket: { remoteAddress: '127.0.0.1' } };+}+function makeRes() {+ const r = { statusCode: 200, _h: {}, _b: null };+ r.setHeader = (k, v) => { r._h[k] = v; };+ r.getHeader = (k) => r._h[k];+ r.end = (b) => { r._b = b; };+ Object.defineProperty(r, '_s', { get() { return this.statusCode; } });+ Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });+ return r;+}+async function call(qs) {+ const req = makeReq(`/api/bnb/babt-check${qs}`);+ const res = makeRes();+ await handler(req, res);+ return res;+}++beforeEach(() => {+ rl.ok = true;+ babtState.mode = 'holder';+});+afterEach(() => {+ vi.clearAllMocks();+});++describe('GET /api/bnb/babt-check — input validation', () => {+ it('400 when address is missing', async () => {+ const r = await call('');+ expect(r._s).toBe(400);+ expect(r.json().error).toBe('bad_request');+ });+ it('400 on a malformed address', async () => {+ const r = await call('?address=not-an-address');+ expect(r._s).toBe(400);+ });+ it('400 on a Solana address (wrong chain)', async () => {+ const r = await call('?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');+ expect(r._s).toBe(400);+ });+ it('400 on an unknown network param', async () => {+ const r = await call(`?address=${HOLDER}&network=nonsense`);+ expect(r._s).toBe(400);+ });+});++describe('GET /api/bnb/babt-check — success', () => {+ it('200 with holdsBabt:true for a holder', async () => {+ const r = await call(`?address=${HOLDER}`);+ expect(r._s).toBe(200);+ const body = r.json();+ expect(body.holdsBabt).toBe(true);+ expect(body.tokenId).toBe('1316815');+ expect(body.network).toBe('bscMainnet');+ expect(body.explorer).toContain(body.contract);+ });++ it('200 with holdsBabt:false for a non-holder', async () => {+ babtState.mode = 'non-holder';+ const r = await call(`?address=${NON_HOLDER}`);+ expect(r._s).toBe(200);+ expect(r.json().holdsBabt).toBe(false);+ });++ it('200 on testnet, includes the developer-only caveat note', async () => {+ const r = await call(`?address=${HOLDER}&network=testnet`);+ expect(r._s).toBe(200);+ const body = r.json();+ expect(body.network).toBe('bscTestnet');+ expect(body.note).toMatch(/developers testing/i);+ });+});++describe('GET /api/bnb/babt-check — upstream failure', () => {+ it('502 contract_unreachable when the on-chain read fails', async () => {+ babtState.mode = 'unreachable';+ const r = await call(`?address=${HOLDER}`);+ expect(r._s).toBe(502);+ expect(r.json().error).toBe('contract_unreachable');+ });+});++describe('GET /api/bnb/babt-check — rate limiting', () => {+ it('429 when the IP bucket is exhausted', async () => {+ rl.ok = false;+ const r = await call(`?address=${HOLDER}`);+ expect(r._s).toBe(429);+ });+});++describe('GET /api/bnb/babt-check — method + CORS', () => {+ it('405 on POST', async () => {+ const req = makeReq(`/api/bnb/babt-check?address=${HOLDER}`);+ req.method = 'POST';+ const res = makeRes();+ await handler(req, res);+ expect(res._s).toBe(405);+ });+});diff --git a/tests/bnb-babt.test.js b/tests/bnb-babt.test.jsnew file mode 100644index 000000000..facadd4a7--- /dev/null+++ b/tests/bnb-babt.test.js@@ -0,0 +1,104 @@+/**+ * BABT (Binance Account Bound Token) holder-check lib — unit tests.+ *+ * `hasBabt` is exercised with an injected mock viem client (deterministic, no+ * live network) for every code path: holder, non-holder, tokenIdOf failure,+ * and a hard contract-read failure. One opt-in live test (BNB_LIVE_RPC=1)+ * re-proves the real mainnet holder captured in docs/bnb-babt-findings.md —+ * found by scanning real Transfer/mint logs on the real BABT contract.+ *+ * Endpoint tests live in tests/bnb-babt-check-endpoint.test.js — kept in a+ * separate file because that suite mocks `../api/_lib/bnb/babt.js` itself+ * (vi.mock is hoisted per-file, so it would otherwise shadow the real+ * `hasBabt` these lib tests exercise directly).+ */++import { describe, it, expect } from 'vitest';+import { hasBabt, BabtCheckError, BABT_CONTRACTS } from '../api/_lib/bnb/babt.js';++const HOLDER = '0x04d1C36842430A169D132ADa68006e6Bb9E3808b';+const NON_HOLDER = '0x000000000000000000000000000000000000dEaD';++function mockClient({ balance, tokenId, failBalance, failTokenId }) {+ return {+ async readContract({ functionName }) {+ if (functionName === 'balanceOf') {+ if (failBalance) throw new Error('rpc timeout');+ return balance;+ }+ if (functionName === 'tokenIdOf') {+ if (failTokenId) throw new Error('tokenIdOf reverted');+ return tokenId;+ }+ throw new Error(`unexpected functionName ${functionName}`);+ },+ };+}++describe('BABT_CONTRACTS', () => {+ it('matches the addresses confirmed real in docs/bnb-babt-findings.md', () => {+ expect(BABT_CONTRACTS.bscMainnet).toBe('0x2B09d47D550061f995A3b5C6F0Fd58005215D7c8');+ expect(BABT_CONTRACTS.bscTestnet).toBe('0x984E6a7b9cb73cB7884c9ca9b1Ee625546F9D0E3');+ });+});++describe('hasBabt', () => {+ it('maps balanceOf > 0 to holdsBabt:true and resolves tokenIdOf', async () => {+ const client = mockClient({ balance: 1n, tokenId: 1316815n });+ const out = await hasBabt(HOLDER, 'bscMainnet', { client });+ expect(out.holdsBabt).toBe(true);+ expect(out.tokenId).toBe('1316815');+ expect(out.network).toBe('bscMainnet');+ expect(out.contract).toBe(BABT_CONTRACTS.bscMainnet);+ expect(typeof out.checkedAt).toBe('string');+ });++ it('maps balanceOf = 0 to holdsBabt:false and does not call tokenIdOf', async () => {+ const client = mockClient({ balance: 0n, failTokenId: true }); // would throw if called+ const out = await hasBabt(NON_HOLDER, 'bscMainnet', { client });+ expect(out.holdsBabt).toBe(false);+ expect(out.tokenId).toBeNull();+ });++ it('a tokenIdOf failure after a confirmed holder does not downgrade holdsBabt', async () => {+ const client = mockClient({ balance: 1n, failTokenId: true });+ const out = await hasBabt(HOLDER, 'bscMainnet', { client });+ expect(out.holdsBabt).toBe(true);+ expect(out.tokenId).toBeNull();+ });++ it('a balanceOf read failure throws a typed BabtCheckError', async () => {+ const client = mockClient({ failBalance: true });+ await expect(hasBabt(HOLDER, 'bscMainnet', { client })).rejects.toBeInstanceOf(BabtCheckError);+ });++ it('rejects a syntactically invalid address before any network call', async () => {+ await expect(hasBabt('not-an-address')).rejects.toBeInstanceOf(TypeError);+ });++ it('rejects a Solana address (wrong chain format)', async () => {+ await expect(hasBabt('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')).rejects.toBeInstanceOf(TypeError);+ });++ it('defaults to mainnet when network is omitted', async () => {+ const client = mockClient({ balance: 0n });+ const out = await hasBabt(NON_HOLDER, undefined, { client });+ expect(out.network).toBe('bscMainnet');+ });++ it('resolves the testnet contract when network is bscTestnet', async () => {+ const client = mockClient({ balance: 0n });+ const out = await hasBabt(NON_HOLDER, 'bscTestnet', { client });+ expect(out.network).toBe('bscTestnet');+ expect(out.contract).toBe(BABT_CONTRACTS.bscTestnet);+ });++ // Opt-in live smoke test — re-proves the real mint found in+ // docs/bnb-babt-findings.md against the real mainnet contract.+ const liveTest = process.env.BNB_LIVE_RPC ? it : it.skip;+ liveTest('real mainnet holder balanceOf/tokenIdOf (live RPC)', async () => {+ const out = await hasBabt(HOLDER, 'bscMainnet');+ expect(out.holdsBabt).toBe(true);+ expect(out.tokenId).toBeTruthy();+ }, 20000);+});diff --git a/tests/bnb-hub-helpers.test.js b/tests/bnb-hub-helpers.test.jsnew file mode 100644index 000000000..b06888df9--- /dev/null+++ b/tests/bnb-hub-helpers.test.js@@ -0,0 +1,96 @@+// Pure helpers behind the /bnb hub page: block-time formatting and the+// track-availability gating that decides "live" vs "coming soon" per card.+// See prompts/bnb-chain/19-bnb-hub-page.md — "Pure helpers (stat formatting,+// track-availability gating) in tests/".++import { describe, expect, it } from 'vitest';+import {+ formatBlockTime,+ formatBlockNumber,+ deltaFromTarget,+ trackLiveness,+ combineTrackStates,+} from '../src/bnb-hub-helpers.js';++describe('formatBlockTime', () => {+ it('returns an em dash for missing/invalid input', () => {+ expect(formatBlockTime(null)).toBe('—');+ expect(formatBlockTime(undefined)).toBe('—');+ expect(formatBlockTime(NaN)).toBe('—');+ expect(formatBlockTime(-5)).toBe('—');+ });+ it('formats sub-second readings with two decimals', () => {+ expect(formatBlockTime(450)).toBe('0.45s');+ expect(formatBlockTime(470)).toBe('0.47s');+ expect(formatBlockTime(0)).toBe('0.00s');+ });+ it('formats one-second-plus readings with one decimal', () => {+ expect(formatBlockTime(2000)).toBe('2.0s');+ expect(formatBlockTime(12340)).toBe('12.3s');+ });+});++describe('formatBlockNumber', () => {+ it('returns an em dash for missing/invalid input', () => {+ expect(formatBlockNumber(null)).toBe('—');+ expect(formatBlockNumber(NaN)).toBe('—');+ });+ it('locale-groups integers', () => {+ expect(formatBlockNumber(108693266)).toBe('108,693,266');+ expect(formatBlockNumber(0)).toBe('0');+ });+});++describe('deltaFromTarget', () => {+ it('returns null when either input is missing (e.g. testnet has no target)', () => {+ expect(deltaFromTarget(460, null)).toBeNull();+ expect(deltaFromTarget(null, 450)).toBeNull();+ expect(deltaFromTarget(460, 0)).toBeNull();+ });+ it('signs a slower-than-target measurement positive', () => {+ expect(deltaFromTarget(459, 450)).toBe('+2.0%');+ });+ it('signs a faster-than-target measurement negative', () => {+ expect(deltaFromTarget(432, 450)).toBe('-4.0%');+ });+ it('reads exactly-on-target as +0.0%', () => {+ expect(deltaFromTarget(450, 450)).toBe('+0.0%');+ });+});++describe('trackLiveness', () => {+ it('treats a network failure (null status) as coming-soon — fails closed', () => {+ expect(trackLiveness(null)).toBe('coming-soon');+ });+ it('treats 404 as coming-soon — the route genuinely is not deployed', () => {+ expect(trackLiveness(404)).toBe('coming-soon');+ });+ it('treats any 5xx as coming-soon — an erroring dependency never reads as shipped', () => {+ expect(trackLiveness(500)).toBe('coming-soon');+ expect(trackLiveness(503)).toBe('coming-soon');+ });+ it('treats 200 as live', () => {+ expect(trackLiveness(200)).toBe('live');+ });+ it('treats 405 as live — a POST-only endpoint probed with GET/HEAD still exists', () => {+ expect(trackLiveness(405)).toBe('live');+ });+ it('treats other 4xx (e.g. 400/401/403) as live — the route resolves', () => {+ expect(trackLiveness(400)).toBe('live');+ expect(trackLiveness(401)).toBe('live');+ expect(trackLiveness(403)).toBe('live');+ });+});++describe('combineTrackStates', () => {+ it('is coming-soon for an empty list', () => {+ expect(combineTrackStates([])).toBe('coming-soon');+ expect(combineTrackStates(undefined)).toBe('coming-soon');+ });+ it('is live only when every check is live', () => {+ expect(combineTrackStates(['live'])).toBe('live');+ expect(combineTrackStates(['live', 'live'])).toBe('live');+ expect(combineTrackStates(['live', 'coming-soon'])).toBe('coming-soon');+ expect(combineTrackStates(['coming-soon', 'coming-soon'])).toBe('coming-soon');+ });+});diff --git a/tests/bnb-mpp-buyer.test.js b/tests/bnb-mpp-buyer.test.jsnew file mode 100644index 000000000..0d3758903--- /dev/null+++ b/tests/bnb-mpp-buyer.test.js@@ -0,0 +1,130 @@+/**+ * MPP (b402) buyer client — unit tests.+ *+ * A fake fetch stands in for an MPP-protected server (402 → 200). The signing+ * account is synthetic and the credential is really signed, so the happy path+ * exercises `buildEip3009Payment` end-to-end. The load-bearing assertion is the+ * hard `maxSpend` cap: an over-quote must be refused with ZERO network payment.+ */++import { describe, it, expect } from 'vitest';+import { getAddress } from 'viem';+import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';+import { encodeXPaymentResponse } from '@bnb-chain/mpp/b402/server';+import { mppFetch, MppBuyerError, MPP_BUYER_NETWORKS } from '../api/_lib/bnb/mpp-buyer.js';++const account = privateKeyToAccount(generatePrivateKey());+const URL = 'https://three.ws/api/x402/three-intel';+const PAYTO = getAddress('0x000000000000000000000000000000000000beef');+const ASSET = getAddress('0x0000000000000000000000000000000000005535');++function requirement(over = {}) {+ return {+ scheme: 'exact',+ network: 'eip155:97',+ amount: '10000',+ asset: ASSET,+ payTo: PAYTO,+ maxTimeoutSeconds: 300,+ extra: { name: 'USD', version: '1', assetTransferMethod: 'eip3009', signerAddress: PAYTO },+ ...over,+ };+}++function makeServer({ accepts, settle = true } = {}) {+ let calls = 0;+ const menu = accepts || [requirement()];+ const fetchImpl = async (_url, init) => {+ calls++;+ const h = init.headers || {};+ const hasPayment = h['X-PAYMENT'] || h['x-payment'];+ if (!hasPayment) {+ return new Response(JSON.stringify({ x402Version: 2, accepts: menu }), {+ status: 402,+ headers: { 'content-type': 'application/json' },+ });+ }+ const headers = { 'content-type': 'application/json' };+ if (settle) {+ headers['x-payment-response'] = encodeXPaymentResponse({+ success: true,+ transaction: '0x' + 'a'.repeat(64),+ network: 'eip155:97',+ payer: account.address,+ });+ }+ return new Response(JSON.stringify({ symbol: 'THREE', signal: 'bullish' }), { status: 200, headers });+ };+ return { fetchImpl, calls: () => calls };+}++describe('mppFetch — happy path', () => {+ it('pays the 402 and returns the 200 body + settlement', async () => {+ const srv = makeServer();+ const out = await mppFetch(URL, { method: 'GET' }, { account, maxSpend: '20000', fetchImpl: srv.fetchImpl });+ expect(out.ok).toBe(true);+ expect(out.result).toMatchObject({ symbol: 'THREE', signal: 'bullish' });+ expect(out.settlement).toBeTruthy();+ expect(srv.calls()).toBe(2); // probe + paid+ });+});++describe('mppFetch — maxSpend cap (load-bearing)', () => {+ it('refuses an over-budget quote with zero payment attempted', async () => {+ const srv = makeServer({ accepts: [requirement({ amount: '999999' })] });+ const out = await mppFetch(URL, { method: 'GET' }, { account, maxSpend: '10000', fetchImpl: srv.fetchImpl });+ expect(out).toMatchObject({ ok: false, abort: true, code: 'over_budget' });+ expect(srv.calls()).toBe(1); // only the probe — no payment sent+ });+});++describe('mppFetch — unsupported / missing requirements', () => {+ it('refuses when the only BNB option is a non-eip3009 credential', async () => {+ const srv = makeServer({ accepts: [requirement({ extra: { ...requirement().extra, assetTransferMethod: 'permit2-exact' } })] });+ const out = await mppFetch(URL, {}, { account, maxSpend: '20000', fetchImpl: srv.fetchImpl });+ expect(out).toMatchObject({ ok: false, abort: true, code: 'unsupported_credential' });+ expect(srv.calls()).toBe(1);+ });++ it('refuses when no BNB network is offered', async () => {+ const srv = makeServer({ accepts: [requirement({ network: 'eip155:8453' })] });+ const out = await mppFetch(URL, {}, { account, maxSpend: '20000', fetchImpl: srv.fetchImpl });+ expect(out).toMatchObject({ ok: false, abort: true, code: 'no_bnb_requirement' });+ });+});++describe('mppFetch — passthrough + validation', () => {+ it('returns a non-402 response as-is without paying', async () => {+ const fetchImpl = async () => new Response(JSON.stringify({ ok: 1 }), { status: 200, headers: { 'content-type': 'application/json' } });+ const out = await mppFetch(URL, {}, { account, maxSpend: '20000', fetchImpl });+ expect(out.ok).toBe(true);+ expect(out.result).toMatchObject({ ok: 1 });+ });++ it('surfaces a still-402 after payment as payment_rejected (bounded, no infinite retry)', async () => {+ let calls = 0;+ const fetchImpl = async () => {+ calls++;+ return new Response(JSON.stringify({ x402Version: 2, accepts: [requirement()], error: 'still_unpaid' }), {+ status: 402,+ headers: { 'content-type': 'application/json' },+ });+ };+ const out = await mppFetch(URL, {}, { account, maxSpend: '20000', fetchImpl });+ expect(out.ok).toBe(false);+ expect(out.status).toBe(402);+ expect(calls).toBe(2); // probe + one paid attempt, then stop+ });++ it('throws MppBuyerError when no account is supplied', async () => {+ await expect(mppFetch(URL, {}, { maxSpend: '10000' })).rejects.toBeInstanceOf(MppBuyerError);+ });++ it('throws MppBuyerError when maxSpend is omitted', async () => {+ await expect(mppFetch(URL, {}, { account })).rejects.toMatchObject({ code: 'no_cap' });+ });++ it('exports the two BNB networks', () => {+ expect(MPP_BUYER_NETWORKS).toEqual(['eip155:56', 'eip155:97']);+ });+});diff --git a/tests/bnb-mpp-server.test.js b/tests/bnb-mpp-server.test.jsnew file mode 100644index 000000000..ed5467197--- /dev/null+++ b/tests/bnb-mpp-server.test.js@@ -0,0 +1,186 @@+/**+ * MPP (BNB Machine Payments Protocol / b402) server adapter — unit tests.+ *+ * Credentials are REAL: `buildEip3009Payment` signs an actual EIP-712+ * TransferWithAuthorization with a synthetic account, so `mppVerify`'s+ * `recoverEip3009Payer` runs the true recovery path (no faked signatures).+ * On-chain settlement is exercised with an injected facilitator client — the+ * real b402 `/settle` needs merchant RSA creds we don't ship in tests.+ */++import { describe, it, expect, beforeEach } from 'vitest';+import { getAddress } from 'viem';+import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';+import { buildEip3009Payment, encodeXPayment } from '@bnb-chain/mpp/b402';+import {+ mppRequirements,+ mppChallenge,+ mppVerify,+ mppSettle,+ mppVerifyAndSettle,+ looksLikeMppPayment,+ isMppPayment,+ MPP_NETWORKS,+ MppError,+} from '../api/_lib/bnb/mpp-server.js';++const account = privateKeyToAccount(generatePrivateKey());+const ROUTE = '/api/x402/three-intel';+const PAYTO = getAddress('0x000000000000000000000000000000000000beef');+const ASSET = getAddress('0x0000000000000000000000000000000000005535'); // synthetic eip3009 token++function reqObj({ amount = '10000', network = MPP_NETWORKS.bscTestnet } = {}) {+ return {+ scheme: 'exact',+ network,+ amount,+ asset: ASSET,+ payTo: PAYTO,+ maxTimeoutSeconds: 300,+ extra: { name: 'USD', version: '1', assetTransferMethod: 'eip3009', signerAddress: PAYTO },+ };+}++async function header(requirements) {+ const payload = await buildEip3009Payment({ account, requirements, resourceUrl: ROUTE });+ return { header: encodeXPayment(payload), payload };+}++beforeEach(() => {+ process.env.X402_PAY_TO_BSC = PAYTO;+ process.env.MPP_ASSET_ADDRESS_BSC = ASSET;+ process.env.MPP_NETWORK = MPP_NETWORKS.bscTestnet;+ delete process.env.B402_BASE_URL; // ensure no real facilitator+});++describe('mppRequirements / mppChallenge', () => {+ it('emits a spec-shaped 402 for the route (testnet default)', async () => {+ const challenge = await mppChallenge({ route: ROUTE, priceAtomics: '10000', description: 'oracle' });+ expect(challenge.x402Version).toBe(2);+ expect(Array.isArray(challenge.accepts)).toBe(true);+ const [r] = challenge.accepts;+ expect(r.network).toBe(MPP_NETWORKS.bscTestnet);+ expect(r.payTo).toBe(PAYTO);+ expect(r.amount).toBe('10000');+ expect(r.extra.assetTransferMethod).toBe('eip3009');+ });++ it('prefers a live /supported kind for asset name + signer', async () => {+ const r = await mppRequirements({+ route: ROUTE,+ priceAtomics: '10000',+ supported: { kinds: [{ network: MPP_NETWORKS.bscTestnet, asset: ASSET, extra: { name: 'United Stables', signerAddress: '0xabc', assetTransferMethod: 'eip3009' } }] },+ });+ expect(r.extra.name).toBe('United Stables');+ expect(r.extra.signerAddress).toBe('0xabc');+ });++ it('throws MppError when no payTo is configured', async () => {+ delete process.env.X402_PAY_TO_BSC;+ delete process.env.MPP_PAY_TO_BSC;+ await expect(mppRequirements({ route: ROUTE, priceAtomics: '10000' })).rejects.toBeInstanceOf(MppError);+ });+});++describe('mppVerify — real EIP-3009 credential', () => {+ it('verifies a valid credential and recovers the payer', async () => {+ const requirements = reqObj();+ const { header: h } = await header(requirements);+ const out = await mppVerify({ headers: { 'x-payment': h } }, requirements);+ expect(out.ok).toBe(true);+ expect(out.payer.toLowerCase()).toBe(account.address.toLowerCase());+ });++ it('rejects a missing X-PAYMENT with 402', async () => {+ const out = await mppVerify({ headers: {} }, reqObj());+ expect(out).toMatchObject({ ok: false, code: 'no_payment', status: 402 });+ });++ it('rejects an offer whose amount does not match our requirements', async () => {+ const { header: h } = await header(reqObj({ amount: '999999' }));+ const out = await mppVerify({ headers: { 'x-payment': h } }, reqObj({ amount: '10000' }));+ expect(out).toMatchObject({ ok: false, code: 'offer_mismatch' });+ });++ it('rejects a non-BNB network payment (leaves it to x402)', async () => {+ const { header: h } = await header(reqObj({ network: 'eip155:8453' }));+ const out = await mppVerify({ headers: { 'x-payment': h } }, reqObj({ network: 'eip155:8453' }));+ // pin passes network equality but isMppPayment gate rejects non-BNB.+ expect(out.ok).toBe(false);+ expect(['wrong_network', 'offer_mismatch']).toContain(out.code);+ });++ it('rejects an undecodable header', async () => {+ const out = await mppVerify({ headers: { 'x-payment': 'not-base64-json!!' } }, reqObj());+ expect(out.ok).toBe(false);+ expect(['bad_payment', 'unsupported_credential']).toContain(out.code);+ });++ it('replay: the same credential is rejected the second time', async () => {+ const requirements = reqObj();+ const { header: h } = await header(requirements);+ const first = await mppVerify({ headers: { 'x-payment': h } }, requirements);+ expect(first.ok).toBe(true);+ const second = await mppVerify({ headers: { 'x-payment': h } }, requirements);+ expect(second).toMatchObject({ ok: false, code: 'replay', status: 409 });+ });+});++describe('mppSettle', () => {+ it('returns mpp_not_configured (503) without merchant credentials', async () => {+ const requirements = reqObj();+ const { payload } = await header(requirements);+ const out = await mppSettle(payload, requirements, { client: null });+ expect(out).toMatchObject({ ok: false, code: 'mpp_not_configured', status: 503 });+ });++ it('settles via an injected facilitator client and encodes the response header', async () => {+ const requirements = reqObj();+ const { payload } = await header(requirements);+ const client = {+ async verify() { return { isValid: true }; },+ async settle() { return { success: true, transaction: '0x' + 'f'.repeat(64), network: requirements.network, payer: account.address }; },+ };+ const out = await mppSettle(payload, requirements, { client });+ expect(out.ok).toBe(true);+ expect(typeof out.paymentResponseHeader).toBe('string');+ expect(out.paymentResponseHeader.length).toBeGreaterThan(0);+ });++ it('surfaces a facilitator transport error as 502 (unknown state)', async () => {+ const requirements = reqObj();+ const { payload } = await header(requirements);+ const client = { async settle() { throw new Error('network down'); } };+ const out = await mppSettle(payload, requirements, { client });+ expect(out).toMatchObject({ ok: false, code: 'facilitator_unreachable', status: 502 });+ });+});++describe('mppVerifyAndSettle (convenience)', () => {+ it('verify + settle happy path with an injected client', async () => {+ const requirements = reqObj();+ const { header: h } = await header(requirements);+ const client = {+ async verify() { return { isValid: true }; },+ async settle() { return { success: true, transaction: '0x' + 'a'.repeat(64) }; },+ };+ const out = await mppVerifyAndSettle({ headers: { 'x-payment': h } }, requirements, { client });+ expect(out.ok).toBe(true);+ expect(out.payer.toLowerCase()).toBe(account.address.toLowerCase());+ });+});++describe('looksLikeMppPayment / isMppPayment', () => {+ it('true for a BNB-network payment header, false otherwise', async () => {+ const { header: h } = await header(reqObj());+ expect(looksLikeMppPayment({ headers: { 'x-payment': h } })).toBe(true);+ expect(looksLikeMppPayment({ headers: {} })).toBe(false);+ expect(looksLikeMppPayment({ headers: { 'x-payment': 'junk' } })).toBe(false);+ });++ it('isMppPayment matches the two BNB networks', () => {+ expect(isMppPayment({ accepted: { network: MPP_NETWORKS.bscMainnet } })).toBe(true);+ expect(isMppPayment({ accepted: { network: MPP_NETWORKS.bscTestnet } })).toBe(true);+ expect(isMppPayment({ accepted: { network: 'eip155:8453' } })).toBe(false);+ });+});diff --git a/tests/bnb-vault-crypto.test.js b/tests/bnb-vault-crypto.test.jsnew file mode 100644index 000000000..9c1cf5a9c--- /dev/null+++ b/tests/bnb-vault-crypto.test.js@@ -0,0 +1,210 @@+/**+ * BNB vault crypto envelope — unit tests (prompt 08).+ *+ * Exercises the real AES-256-GCM content-encryption round trip and the real+ * secp256k1 ECIES key-wrap round trip against a tiny but structurally valid+ * synthetic GLB fixture (glTF binary header + minimal JSON chunk) — no+ * mocked crypto anywhere in this suite.+ */++import { createHash } from 'node:crypto';+import { describe, it, expect } from 'vitest';+import { secp256k1 } from '@noble/curves/secp256k1.js';+import {+ encryptGlb,+ decryptGlb,+ wrapKey,+ unwrapKey,+ generateVaultKeypair,+ VaultCryptoError,+ VAULT_CRYPTO_PARAMS,+} from '../api/_lib/bnb/vault-crypto.js';++/**+ * Build a minimal but structurally valid GLB (glTF 2.0 binary container):+ * 12-byte header (magic 'glTF', version 2, total length) + one JSON chunk+ * containing the smallest legal glTF document. Real bytes, real GLB magic —+ * just no geometry, which is fine for a crypto-envelope round-trip proof.+ */+function buildSyntheticGlb() {+ const json = JSON.stringify({ asset: { version: '2.0', generator: 'three.ws-bnb-vault-test' } });+ const jsonBytes = Buffer.from(json, 'utf8');+ const pad = (4 - (jsonBytes.length % 4)) % 4;+ const jsonChunk = Buffer.concat([jsonBytes, Buffer.alloc(pad, 0x20)]); // glTF pads JSON with spaces++ const chunkHeader = Buffer.alloc(8);+ chunkHeader.writeUInt32LE(jsonChunk.length, 0);+ chunkHeader.writeUInt32LE(0x4e4f534a, 4); // 'JSON'++ const totalLength = 12 + chunkHeader.length + jsonChunk.length;+ const header = Buffer.alloc(12);+ header.writeUInt32LE(0x46546c67, 0); // magic 'glTF'+ header.writeUInt32LE(2, 4); // version+ header.writeUInt32LE(totalLength, 8);++ return Buffer.concat([header, chunkHeader, jsonChunk]);+}++describe('encryptGlb / decryptGlb round trip', () => {+ it('decrypts to byte-identical plaintext with matching sha256', () => {+ const glb = buildSyntheticGlb();+ const expectedSha256 = createHash('sha256').update(glb).digest('hex');++ const { ciphertext, contentKey, iv, authTag, sha256OfPlaintext } = encryptGlb(glb);+ expect(sha256OfPlaintext).toBe(expectedSha256);+ expect(contentKey).toHaveLength(32);+ expect(iv).toHaveLength(12);+ expect(authTag).toHaveLength(16);+ expect(ciphertext.equals(glb)).toBe(false); // actually encrypted, not passthrough++ const plaintext = decryptGlb({ ciphertext, contentKey, iv, authTag }, { expectedSha256 });+ expect(plaintext.equals(glb)).toBe(true);+ expect(createHash('sha256').update(plaintext).digest('hex')).toBe(expectedSha256);+ });++ it('rejects empty input', () => {+ expect(() => encryptGlb(Buffer.alloc(0))).toThrow(VaultCryptoError);+ });++ it('tampering one ciphertext byte throws a typed auth error, never garbage bytes', () => {+ const glb = buildSyntheticGlb();+ const { ciphertext, contentKey, iv, authTag } = encryptGlb(glb);+ const tampered = Buffer.from(ciphertext);+ tampered[0] ^= 0xff; // flip one bit's worth of byte++ let caught;+ try {+ decryptGlb({ ciphertext: tampered, contentKey, iv, authTag });+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(VaultCryptoError);+ expect(caught.name).toBe('VaultCryptoError');+ expect(caught.code).toBe('auth_failed');+ });++ it('tampering the auth tag also throws a typed auth error', () => {+ const glb = buildSyntheticGlb();+ const { ciphertext, contentKey, iv, authTag } = encryptGlb(glb);+ const tampered = Buffer.from(authTag);+ tampered[0] ^= 0xff;+ expect(() => decryptGlb({ ciphertext, contentKey, iv, authTag: tampered })).toThrow(VaultCryptoError);+ });++ it('rejects a wrong-size content key before ever touching the cipher', () => {+ const glb = buildSyntheticGlb();+ const { ciphertext, iv, authTag } = encryptGlb(glb);+ expect(() => decryptGlb({ ciphertext, contentKey: Buffer.alloc(16), iv, authTag })).toThrow(VaultCryptoError);+ });++ it('rejects a wrong-size IV before ever touching the cipher', () => {+ const glb = buildSyntheticGlb();+ const { ciphertext, contentKey, authTag } = encryptGlb(glb);+ expect(() => decryptGlb({ ciphertext, contentKey, iv: Buffer.alloc(8), authTag })).toThrow(VaultCryptoError);+ });++ it('expectedSha256 mismatch is caught even when GCM auth passes', () => {+ const glb = buildSyntheticGlb();+ const { ciphertext, contentKey, iv, authTag } = encryptGlb(glb);+ expect(() =>+ decryptGlb({ ciphertext, contentKey, iv, authTag }, { expectedSha256: 'deadbeef'.repeat(8) }),+ ).toThrow(/sha256/);+ });+});++describe('wrapKey / unwrapKey (ECIES over secp256k1)', () => {+ it('round-trips a content key with a real keypair', () => {+ const { privateKey, publicKey } = generateVaultKeypair();+ const { contentKey } = encryptGlb(buildSyntheticGlb());++ const wrapped = wrapKey(contentKey, publicKey);+ expect(wrapped.ephemeralPublicKey).toHaveLength(33); // compressed point+ expect(wrapped.ciphertext.equals(contentKey)).toBe(false);++ const unwrapped = unwrapKey(wrapped, privateKey);+ expect(unwrapped.equals(contentKey)).toBe(true);+ });++ it('accepts an uncompressed (65-byte) recipient public key too', () => {+ const { privateKey } = generateVaultKeypair();+ const uncompressedPub = Buffer.from(secp256k1.getPublicKey(privateKey, false));+ expect(uncompressedPub).toHaveLength(65);++ const { contentKey } = encryptGlb(buildSyntheticGlb());+ const wrapped = wrapKey(contentKey, uncompressedPub);+ const unwrapped = unwrapKey(wrapped, privateKey);+ expect(unwrapped.equals(contentKey)).toBe(true);+ });++ it('produces a different ephemeral key (and ciphertext) on every wrap call', () => {+ const { publicKey } = generateVaultKeypair();+ const { contentKey } = encryptGlb(buildSyntheticGlb());+ const a = wrapKey(contentKey, publicKey);+ const b = wrapKey(contentKey, publicKey);+ expect(a.ephemeralPublicKey.equals(b.ephemeralPublicKey)).toBe(false);+ expect(a.ciphertext.equals(b.ciphertext)).toBe(false);+ });++ it('unwrapping with the wrong private key fails with a typed auth error, not garbage', () => {+ const recipient = generateVaultKeypair();+ const attacker = generateVaultKeypair();+ const { contentKey } = encryptGlb(buildSyntheticGlb());++ const wrapped = wrapKey(contentKey, recipient.publicKey);++ let caught;+ try {+ unwrapKey(wrapped, attacker.privateKey);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(VaultCryptoError);+ expect(caught.code).toBe('auth_failed');+ });++ it('rejects a malformed recipient public key', () => {+ const { contentKey } = encryptGlb(buildSyntheticGlb());+ expect(() => wrapKey(contentKey, Buffer.from('not-a-point'))).toThrow(VaultCryptoError);+ });++ it('full envelope + key-wrap pipeline: encrypt -> wrap -> (simulated storage/transfer) -> unwrap -> decrypt', () => {+ const seller = generateVaultKeypair(); // stands in for the buyer's keypair receiving the key+ const glb = buildSyntheticGlb();+ const expectedSha256 = createHash('sha256').update(glb).digest('hex');++ const { ciphertext, contentKey, iv, authTag, sha256OfPlaintext } = encryptGlb(glb);+ expect(sha256OfPlaintext).toBe(expectedSha256);++ const wrapped = wrapKey(contentKey, seller.publicKey);+ // Simulate the wrapped key + ciphertext crossing the wire (JSON-safe hex round trip).+ const wire = {+ ciphertext: Buffer.from(ciphertext).toString('hex'),+ iv: Buffer.from(iv).toString('hex'),+ authTag: Buffer.from(authTag).toString('hex'),+ wrapped: {+ ephemeralPublicKey: Buffer.from(wrapped.ephemeralPublicKey).toString('hex'),+ iv: Buffer.from(wrapped.iv).toString('hex'),+ authTag: Buffer.from(wrapped.authTag).toString('hex'),+ ciphertext: Buffer.from(wrapped.ciphertext).toString('hex'),+ },+ };++ const recoveredContentKey = unwrapKey(wire.wrapped, seller.privateKey);+ const recoveredGlb = decryptGlb(+ { ciphertext: wire.ciphertext, contentKey: recoveredContentKey, iv: wire.iv, authTag: wire.authTag },+ { expectedSha256 },+ );+ expect(recoveredGlb.equals(glb)).toBe(true);+ });+});++describe('VAULT_CRYPTO_PARAMS', () => {+ it('publishes the exact algorithm/lengths the manifest spec documents', () => {+ expect(VAULT_CRYPTO_PARAMS.alg).toBe('AES-256-GCM');+ expect(VAULT_CRYPTO_PARAMS.keyLenBytes).toBe(32);+ expect(VAULT_CRYPTO_PARAMS.ivLenBytes).toBe(12);+ expect(VAULT_CRYPTO_PARAMS.authTagLenBytes).toBe(16);+ expect(VAULT_CRYPTO_PARAMS.ecies.curve).toBe('secp256k1');+ expect(VAULT_CRYPTO_PARAMS.ecies.kdf).toBe('HKDF-SHA256');+ });+});diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.jsonindex a761fedcc..ed3a314ac 100644--- a/tests/fixtures/mcp-golden-tools.json+++ b/tests/fixtures/mcp-golden-tools.json@@ -2,6 +2,7 @@"api/_mcp-studio/tools.js": [{"name": "forge_avatar",+ "title": "Generate a rigged, animation-ready avatar","descHead": "dynamic","descHash": "dynamic","annotations": "ref:GEN_ANNOTATIONS",@@ -9,6 +10,7 @@},{"name": "forge_free",+ "title": "Generate a 3D model from text","descHead": "dynamic","descHash": "dynamic","annotations": "ref:GEN_ANNOTATIONS",@@ -16,6 +18,7 @@},{"name": "mesh_forge",+ "title": "Generate a 3D mesh (art-directed)","descHead": "dynamic","descHash": "dynamic","annotations": "ref:GEN_ANNOTATIONS",@@ -23,6 +26,7 @@},{"name": "refine_model",+ "title": "Refine a 3D model by describing a change","descHead": "dynamic","descHash": "dynamic","annotations": "ref:GEN_ANNOTATIONS",@@ -30,6 +34,7 @@},{"name": "rig_mesh",+ "title": "Rig a 3D model for animation","descHead": "dynamic","descHash": "dynamic","annotations": "ref:GEN_ANNOTATIONS",@@ -37,6 +42,7 @@},{"name": "text_to_avatar",+ "title": "Generate a 3D avatar","descHead": "dynamic","descHash": "dynamic","annotations": "ref:GEN_ANNOTATIONS",@@ -46,6 +52,7 @@"api/_mcp/tools/agents.js": [{"name": "call_agent",+ "title": "Call agent","descHead": "Send a message to another three.ws agent and get its response. Use this ","descHash": "3d9116ed9950","annotations": {@@ -58,6 +65,7 @@},{"name": "identity_check",+ "title": "Screen an agent identity for impersonation","descHead": "dynamic","descHash": "dynamic","annotations": {@@ -70,6 +78,7 @@},{"name": "register_agent",+ "title": "Register an agent on-chain","descHead": "dynamic","descHash": "dynamic","annotations": {@@ -84,6 +93,7 @@"api/_mcp/tools/animations.js": [{"name": "apply_animation",+ "title": "Apply an animation preset to a rigged model","descHead": "Retarget a curated animation preset onto a caller-supplied rigged humano","descHash": "e42328286a5c","annotations": {@@ -96,6 +106,7 @@},{"name": "list_animations",+ "title": "List animation presets","descHead": "List the curated, retargetable animation presets in the three.ws library","descHash": "97f136897e7b","annotations": {@@ -108,6 +119,7 @@},{"name": "text_to_animation",+ "title": "Generate an animation from a text prompt and retarget it onto a model","descHead": "Generate a brand-new motion from a natural-language prompt (e.g. \"waving","descHash": "e69992039d1a","annotations": {@@ -122,6 +134,7 @@"api/_mcp/tools/avatars.js": [{"name": "delete_avatar",+ "title": "Delete avatar","descHead": "Soft-delete an avatar you own. Requires avatars:delete scope.","descHash": "7e867ad19f8c","annotations": {@@ -134,6 +147,7 @@},{"name": "get_avatar",+ "title": "Get avatar","descHead": "Fetch a single avatar by id or by owner+slug. Returns metadata and a mod","descHash": "7d13b04e4e9a","annotations": "ref:READ_ANNOTATIONS",@@ -141,6 +155,7 @@},{"name": "list_my_avatars",+ "title": "List my avatars","descHead": "List the authenticated user's avatars. Returns id, name, slug, size, vis","descHash": "63b8ad84489b","annotations": "ref:READ_ANNOTATIONS",@@ -148,6 +163,7 @@},{"name": "render_avatar",+ "title": "Render avatar","descHead": "dynamic","descHash": "dynamic","annotations": "ref:READ_ANNOTATIONS",@@ -155,6 +171,7 @@},{"name": "render_avatar_image",+ "title": "Render an avatar to an image","descHead": "dynamic","descHash": "dynamic","annotations": {@@ -167,6 +184,7 @@},{"name": "search_public_avatars",+ "title": "Search public avatars","descHead": "Search the public avatar gallery. Useful for finding characters to rende","descHash": "50269f56daf0","annotations": "ref:READ_ANNOTATIONS",@@ -176,6 +194,7 @@"api/_mcp/tools/embed.js": [{"name": "get_embed_code",+ "title": "Get embed code","descHead": "Return a ready-to-paste <iframe> embed snippet (plus shareable URL, oEmb","descHash": "757acd12b3f0","annotations": {@@ -190,6 +209,7 @@"api/_mcp/tools/memory.js": [{"name": "forget",+ "title": "Forget","descHead": "Delete a memory you own by its id.","descHash": "c7a3d36e6024","annotations": {@@ -202,6 +222,7 @@},{"name": "recall",+ "title": "Recall","descHead": "Retrieve the most relevant memories for a query from one of your agents.","descHash": "2f63c3847d9b","annotations": {@@ -214,6 +235,7 @@},{"name": "remember",+ "title": "Remember","descHead": "Store a long-term memory for one of your agents. Use for durable facts: ","descHash": "ae6892ef85bb","annotations": {@@ -228,6 +250,7 @@"api/_mcp/tools/models.js": [{"name": "inspect_model",+ "title": "Inspect glTF/GLB model","descHead": "Parse a remote GLB or glTF and return structural stats: scene/node/mesh ","descHash": "b8209ee26651","annotations": "ref:INSPECTION_ANNOTATIONS",@@ -235,6 +258,7 @@},{"name": "optimize_model",+ "title": "Suggest optimizations for a glTF/GLB model","descHead": "Inspect the model and return actionable suggestions for reducing size an","descHash": "6aae82cc8273","annotations": "ref:INSPECTION_ANNOTATIONS",@@ -242,6 +266,7 @@},{"name": "validate_model",+ "title": "Validate glTF/GLB model","descHead": "Run the Khronos glTF-Validator against a remote GLB or glTF URL. Returns","descHash": "1ad7ca463dbe","annotations": "ref:INSPECTION_ANNOTATIONS",@@ -251,6 +276,7 @@"api/_mcp/tools/oracle.js": [{"name": "oracle_arm_watch",+ "title": "Arm agent Oracle watch","descHead": "Arm your agent to automatically act on Oracle conviction signals. Once a","descHash": "d659c5146b5d","annotations": {@@ -263,6 +289,7 @@},{"name": "oracle_coin",+ "title": "Oracle verdict for one coin","descHead": "Get Oracle's full conviction verdict for a specific pump.fun coin by min","descHash": "b2e49ba1236a","annotations": "ref:LIVE_ANNOTATIONS",@@ -270,6 +297,7 @@},{"name": "oracle_top_plays",+ "title": "Oracle top conviction plays","descHead": "Get the current top pump.fun launches ranked by Oracle conviction score.","descHash": "61cecaf86ed6","annotations": "ref:LIVE_ANNOTATIONS",@@ -277,6 +305,7 @@},{"name": "oracle_watch_status",+ "title": "Oracle watch status + track record","descHead": "Check your agent's current Oracle watch configuration and its realized t","descHash": "9edf65c96476","annotations": {@@ -291,6 +320,7 @@"api/_mcp/tools/pumpfun.js": [{"name": "pumpfun_creator_intel",+ "title": "Pump.fun creator intel","descHead": "Reputation profile for a pump.fun creator wallet: prior launches, gradua","descHash": "11009779c558","annotations": "ref:LIVE_FEED_ANNOTATIONS",@@ -298,6 +328,7 @@},{"name": "pumpfun_recent_claims",+ "title": "Recent pump.fun claims","descHead": "Fetch the most recent pump.fun GitHub social-fee claim events with full ","descHash": "cb6200c9fb5a","annotations": "ref:LIVE_FEED_ANNOTATIONS",@@ -305,6 +336,7 @@},{"name": "pumpfun_recent_graduations",+ "title": "Recent pump.fun graduations","descHead": "Tokens that recently graduated from the bonding curve to PumpAMM, with c","descHash": "caf218a6cdd6","annotations": "ref:LIVE_FEED_ANNOTATIONS",@@ -312,6 +344,7 @@},{"name": "pumpfun_token_intel",+ "title": "Pump.fun token intel","descHead": "Full intel on a pump.fun token: graduation status, bonding-curve progres","descHash": "d1119e50045e","annotations": "ref:LIVE_FEED_ANNOTATIONS",@@ -321,6 +354,7 @@"api/_mcp/tools/solana.js": [{"name": "solana_agent_attestations",+ "title": "List Solana agent attestations","descHead": "List recent on-chain attestations about a Solana-registered agent (feedb","descHash": "2c83176df84d","annotations": "ref:ATTESTATION_READ_ANNOTATIONS",@@ -328,6 +362,7 @@},{"name": "solana_agent_passport",+ "title": "Get Solana agent passport","descHead": "Full discovery card for a Solana agent: identity (Metaplex Core asset), ","descHash": "6320bafe75df","annotations": "ref:ATTESTATION_READ_ANNOTATIONS",@@ -335,6 +370,7 @@},{"name": "solana_agent_reputation",+ "title": "Get Solana agent reputation","descHead": "Computed reputation summary for a Solana-registered three.ws agent. Retu","descHash": "5c3aa420b75e","annotations": "ref:ATTESTATION_READ_ANNOTATIONS",@@ -344,6 +380,7 @@"api/_mcp/tools/tokenize.js": [{"name": "get_3d_asset_onchain",+ "title": "Resolve a 3D NFT to its live asset + provenance","descHead": "dynamic","descHash": "dynamic","annotations": {@@ -356,6 +393,7 @@},{"name": "mint_3d_asset",+ "title": "Mint a 3D asset as a Solana NFT","descHead": "dynamic","descHash": "dynamic","annotations": {@@ -370,6 +408,7 @@"api/_mcp/tools/trader.js": [{"name": "copy_status",+ "title": "My copy subscriptions","descHead": "List all your active copy-trading subscriptions, with sizing config, exe","descHash": "d18378cae20d","annotations": {@@ -382,6 +421,7 @@},{"name": "copy_subscribe",+ "title": "Subscribe to copy a trader","descHead": "Set up non-custodial copy-trading: mirror a leader agent's future pump.f","descHash": "d4c0a89a60dd","annotations": "ref:WRITE",@@ -389,6 +429,7 @@},{"name": "trader_leaderboard",+ "title": "Top pump.fun traders","descHead": "Get the top pump.fun traders on three.ws ranked by composite TraderScore","descHash": "51e91774fd99","annotations": "ref:LIVE",@@ -396,6 +437,7 @@},{"name": "trader_profile",+ "title": "Full track record for one agent","descHead": "Get the full, verifiable track record for a specific pump.fun agent trad","descHash": "aaff472b3eae","annotations": "ref:LIVE",@@ -405,6 +447,7 @@"api/_mcp3d/tools/studio.js": [{"name": "auto_rig_model",+ "title": "Auto-rig a static 3D model (skeleton + skin weights)","descHead": "Turn a static GLB mesh into an animation-ready character: adds a humanoi","descHash": "832b32ab5642","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -412,6 +455,7 @@},{"name": "capture_scene",+ "title": "Reconstruct a 3D scene from a video","descHead": "dynamic","descHash": "dynamic","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -419,6 +463,7 @@},{"name": "create_agent_persona",+ "title": "Mint a persistent, living agent persona from a rigged GLB","descHead": "Turn a generated GLB into a NAMED, persistent agent body — a \"persona\" t","descHash": "716809d092b0","annotations": "ref:PERSONA_CREATE_ANNOTATIONS",@@ -426,6 +471,7 @@},{"name": "direct_prompt",+ "title": "Optimize a rough idea into a 3D-generation prompt (IBM Granite)","descHead": "Rewrite a rough idea into an optimized text_to_3d prompt using IBM Grani","descHash": "1e1c7ac5025f","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -433,6 +479,7 @@},{"name": "generate_material",+ "title": "Generate a glTF PBR material from a description (IBM Granite)","descHead": "Generate a physically-based (PBR) glTF 2.0 material from a text descript","descHash": "50c812e688fc","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -440,6 +487,7 @@},{"name": "generation_status",+ "title": "Check a 3D generation job","descHead": "Poll a text_to_3d or image_to_3d job by its job_id. While running it rep","descHash": "2fdc15375822","annotations": {@@ -452,6 +500,7 @@},{"name": "get_agent_persona",+ "title": "Reload a persisted persona by id (continuity across sessions)","descHead": "Bring back a previously minted persona by its persona_id — the SAME body","descHash": "04388b6c47b0","annotations": "ref:PERSONA_READ_ANNOTATIONS",@@ -459,6 +508,7 @@},{"name": "image_to_3d",+ "title": "Reconstruct a 3D model from one or more images","descHead": "Reconstruct a textured 3D model (GLB) from a reference image using the t","descHash": "cf4145f4d88b","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -466,6 +516,7 @@},{"name": "persona_say",+ "title": "Speak a reply through a persona — lip-sync + emotion + gesture","descHead": "Make a persona PERFORM a reply: the body lip-syncs the text and shows th","descHash": "7ce7c147f8f6","annotations": "ref:PERSONA_SAY_ANNOTATIONS",@@ -473,6 +524,7 @@},{"name": "pose_model",+ "title": "Resolve a text prompt to a pose-studio seed + joint rotations","descHead": "Map a natural-language pose description to a deterministic pose-studio s","descHash": "f90f437e72b1","annotations": {@@ -485,6 +537,7 @@},{"name": "preview_3d",+ "title": "Preview any GLB as an interactive 3D artifact","descHead": "Render any public GLB URL as an inline <model-viewer> HTML artifact — or","descHash": "ed4b123a6d3e","annotations": {@@ -497,6 +550,7 @@},{"name": "remesh_model",+ "title": "Remesh, simplify, repair, or convert a 3D model","descHead": "Process an existing GLB/OBJ/STL/PLY mesh: fix holes and degenerate geome","descHash": "47b083320257","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -504,6 +558,7 @@},{"name": "remove_background",+ "title": "Remove the background from an image","descHead": "Strip the background from a photo or illustration with the three.ws back","descHash": "3334882948e5","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -511,6 +566,7 @@},{"name": "retexture_model",+ "title": "Paint a new texture onto a 3D model from a text prompt","descHead": "Generate a fresh texture for an untextured or poorly-textured GLB with t","descHash": "6cc85e4e6fb7","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -518,6 +574,7 @@},{"name": "retexture_region",+ "title": "Repaint one masked region of a model's texture (magic brush)","descHead": "dynamic","descHash": "dynamic","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -525,6 +582,7 @@},{"name": "save_avatar",+ "title": "Save a generated GLB as a durable, named avatar","descHead": "Persist a generated GLB (e.g. the glb_url returned by generation_status)","descHash": "de0ef1a0a729","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -532,6 +590,7 @@},{"name": "segment_model",+ "title": "Split a 3D model into named, separable parts","descHead": "Segment a GLB/OBJ/STL/PLY mesh into meaningful parts with clean boundari","descHash": "be034074eec2","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -539,6 +598,7 @@},{"name": "stylize_model",+ "title": "Apply a one-click geometric stylization filter to a 3D model","descHead": "dynamic","descHash": "dynamic","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -546,6 +606,7 @@},{"name": "text_to_3d",+ "title": "Generate a 3D model from a text prompt","descHead": "Turn a text description into a textured 3D model (GLB). Runs a fast text","descHash": "8d96a3f07c0f","annotations": "ref:GENERATIVE_ANNOTATIONS",@@ -555,6 +616,7 @@"api/_mcpagent/tools.js": [{"name": "find_services",+ "title": "Find paid services the agent can call","descHead": "Search the live x402 facilitator network for paid services (HTTP APIs an","descHash": "10b9605cf0c4","annotations": {@@ -567,6 +629,7 @@},{"name": "monetize_endpoint",+ "title": "Publish a paid endpoint to earn USDC","descHead": "Put a price on an upstream API your agent already serves and publish it ","descHash": "43e54e8d4142","annotations": {@@ -579,6 +642,7 @@},{"name": "pay_and_call",+ "title": "Pay an x402 service and return its result","descHead": "Call a paid x402 endpoint and settle the USDC payment automatically from","descHash": "590dd66c69e6","annotations": {@@ -591,6 +655,7 @@},{"name": "provision_wallet",+ "title": "Create the agent's wallet","descHead": "Create (or return) the custodial Solana wallet for one of your agents so","descHash": "aea787e2cec2","annotations": {@@ -603,6 +668,7 @@},{"name": "wallet_status",+ "title": "Check the agent's wallet","descHead": "Show the signed-in user's three.ws agent wallet: address, SOL and USDC b","descHash": "e8cef61875a7","annotations": {@@ -617,6 +683,7 @@"api/_mcpbazaar/tools.js": [{"name": "bazaar_service_details",+ "title": "Live price details for one x402 service","descHead": "Resolve the current live price of a single x402 service by its resource ","descHash": "32ef6c0a06fd","annotations": "ref:DISCOVERY_ANNOTATIONS",@@ -624,6 +691,7 @@},{"name": "browse_services",+ "title": "Browse the x402 bazaar","descHead": "List paid agent services from the live x402 facilitator network without ","descHash": "5f4946b4f7d3","annotations": "ref:DISCOVERY_ANNOTATIONS",@@ -631,6 +699,7 @@},{"name": "get_service",+ "title": "Get full details for one x402 service","descHead": "Resolve a single x402 service by its resource URL (and tool_name for MCP","descHash": "b38eb5052ab1","annotations": "ref:DISCOVERY_ANNOTATIONS",@@ -638,6 +707,7 @@},{"name": "search_services",+ "title": "Search the x402 bazaar","descHead": "Ranked search across the live x402 facilitator network for paid agent se","descHash": "7e71185f12b2","annotations": "ref:DISCOVERY_ANNOTATIONS",@@ -647,6 +717,7 @@"api/_mcpibm/tools.js": [{"name": "ibm_granite_analyze",+ "title": "IBM Granite Analyze ($0.04)","descHead": "dynamic","descHash": "dynamic","annotations": "ref:generativeAnnotations",@@ -654,6 +725,7 @@},{"name": "ibm_granite_chat",+ "title": "IBM Granite Chat ($0.02)","descHead": "dynamic","descHash": "dynamic","annotations": "ref:generativeAnnotations",@@ -661,6 +733,7 @@},{"name": "ibm_granite_code",+ "title": "IBM Granite Code ($0.025)","descHead": "dynamic","descHash": "dynamic","annotations": "ref:generativeAnnotations",@@ -668,6 +741,7 @@},{"name": "ibm_granite_embed",+ "title": "IBM Granite Embed ($0.005)","descHead": "dynamic","descHash": "dynamic","annotations": "ref:deterministicAnnotations",@@ -675,6 +749,7 @@},{"name": "ibm_granite_forecast",+ "title": "IBM Granite Forecast ($0.05)","descHead": "dynamic","descHash": "dynamic","annotations": "ref:generativeAnnotations",@@ -682,10 +757,2096 @@},{"name": "ibm_granite_getting_started",+ "title": "Getting Started (free)","descHead": "dynamic","descHash": "dynamic","annotations": "dynamic","schemaHash": "77bf1a795265"}+ ],+ "packages/activity-mcp/src/tools/get-feed-events.js": [+ {+ "name": "get_feed_events",+ "title": "Site-wide activity feed",+ "descHead": "The site-wide activity ticker — recent things that just happened across ",+ "descHash": "2bdbb0bc0a3a",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "7ad8667a612c"+ }+ ],+ "packages/activity-mcp/src/tools/get-holder-leaderboard.js": [+ {+ "name": "get_holder_leaderboard",+ "title": "$THREE holder leaderboard",+ "descHead": "The public $THREE holder leaderboard, ranked by on-chain balance. $THREE",+ "descHash": "4754b044edb1",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "2efa60eac686"+ }+ ],+ "packages/activity-mcp/src/tools/get-tier-info.js": [+ {+ "name": "get_tier_info",+ "title": "$THREE holder tier ladder",+ "descHead": "The $THREE holder tier ladder — the membership bands a wallet earns pure",+ "descHash": "81281cff2892",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/activity-mcp/src/tools/get-trending-agents.js": [+ {+ "name": "get_trending_agents",+ "title": "Trending agents by activity",+ "descHead": "The agents that are hot on three.ws right now, ranked by REAL chat activ",+ "descHash": "739733564f70",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "22afc47bf6d6"+ }+ ],+ "packages/activity-mcp/src/tools/get-trending-coins.js": [+ {+ "name": "get_trending_coins",+ "title": "Trending coins by Oracle conviction",+ "descHead": "The coins three.ws's Oracle has the highest conviction in right now, ran",+ "descHash": "21babb465831",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "4358d4eb8d60"+ }+ ],+ "packages/agenc-mcp/src/tools/get-agent.js": [+ {+ "name": "get_agent",+ "title": "Get AgenC agent registry entry",+ "descHead": "Resolve an agent's on-chain identity in the AgenC registry (ERC-8004-sty",+ "descHash": "64c82fb36d18",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "2a4e4667d9f1"+ }+ ],+ "packages/agenc-mcp/src/tools/get-task.js": [+ {+ "name": "get_task",+ "title": "Get AgenC task detail + lifecycle",+ "descHead": "Fetch one AgenC task by its PDA, or by (creator + taskId). Returns the t",+ "descHash": "4319c9a90e90",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "de55358b7a95"+ }+ ],+ "packages/agenc-mcp/src/tools/link-agent.js": [+ {+ "name": "link_agent",+ "title": "Link a three.ws identity to its AgenC agent id",+ "descHead": "Resolve a three.ws identity to its canonical AgenC agent id and check wh",+ "descHash": "7b9bfd0060eb",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "1af9f71c90be"+ }+ ],+ "packages/agenc-mcp/src/tools/list-tasks.js": [+ {+ "name": "list_tasks",+ "title": "List AgenC tasks by creator",+ "descHead": "List every AgenC task created by a given Solana wallet. AgenC (agenc.tec",+ "descHash": "1cb240d0a32c",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "9409c73d56e5"+ }+ ],+ "packages/agenc-mcp/src/tools/query-x402-services.js": [+ {+ "name": "query_x402_services",+ "title": "Query x402 services as AgenC tasks",+ "descHead": "Browse the x402 service directory (the bazaar of paid HTTP endpoints and",+ "descHash": "7e00badfc0a3",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "d0493ec770a9"+ }+ ],+ "packages/agentcore-payments-mcp/src/tools/cancel-session.js": [+ {+ "name": "cancel_payment_session",+ "title": "Cancel a payment session and refund unused budget",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "schemaHash": "307b43a5a317"+ }+ ],+ "packages/agentcore-payments-mcp/src/tools/check-session.js": [+ {+ "name": "check_payment_session",+ "title": "Check a payment session's budget and status",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "schemaHash": "227cd6bd14df"+ }+ ],+ "packages/agentcore-payments-mcp/src/tools/create-session.js": [+ {+ "name": "create_payment_session",+ "title": "Create a funded agent payment session",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": false+ },+ "schemaHash": "bb222f0e8d40"+ }+ ],+ "packages/agentcore-payments-mcp/src/tools/list-sessions.js": [+ {+ "name": "list_payment_sessions",+ "title": "List payment sessions and spending stats",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": false+ },+ "schemaHash": "6c9b2b8ad2a9"+ }+ ],+ "packages/agentcore-payments-mcp/src/tools/pay-with-session.js": [+ {+ "name": "pay_with_session",+ "title": "Pay an x402 endpoint via a payment session",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "c4ae91289bf9"+ }+ ],+ "packages/agora-mcp/src/tools/board.js": [+ {+ "name": "agora_board",+ "title": "Browse the Agora job board",+ "descHead": "Browse the live Agora job board — the work an agent can claim and earn $",+ "descHash": "5dbb1bdad754",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "e829b250d792"+ }+ ],+ "packages/agora-mcp/src/tools/citizens.js": [+ {+ "name": "agora_citizens",+ "title": "List Agora citizens",+ "descHead": "List the citizens of Agora — the population of the agent + human economy",+ "descHash": "9c8f5bf601b4",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "32b58df88bce"+ }+ ],+ "packages/agora-mcp/src/tools/claim-task.js": [+ {+ "name": "agora_claim_task",+ "title": "Claim an open Agora task (on-chain)",+ "descHead": "CLAIM an open job from the Agora board — a REAL on-chain AgenC claim sig",+ "descHash": "0bb79da5c125",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "c4bee0c62ee8"+ }+ ],+ "packages/agora-mcp/src/tools/complete-task.js": [+ {+ "name": "agora_complete_task",+ "title": "Complete an Agora task with a proof (on-chain)",+ "descHead": "COMPLETE a task you claimed and GET PAID — a REAL on-chain AgenC complet",+ "descHash": "35535d8835f8",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "45b0af8af946"+ }+ ],+ "packages/agora-mcp/src/tools/passport.js": [+ {+ "name": "agora_passport",+ "title": "Get one Agora citizen passport",+ "descHead": "Fetch one citizen's living passport — the full record of a participant i",+ "descHash": "5427f717ba36",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "c38b759f216f"+ }+ ],+ "packages/agora-mcp/src/tools/post-task.js": [+ {+ "name": "agora_post_task",+ "title": "Post a bounty to the Agora board (on-chain escrow)",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "3c49ac6bbe6f"+ }+ ],+ "packages/agora-mcp/src/tools/professions.js": [+ {+ "name": "agora_professions",+ "title": "List Agora professions (the capability bit map)",+ "descHead": "List Agora's professions — the labor market's type system over AgenC's u",+ "descHash": "65a97e8f01a0",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/agora-mcp/src/tools/pulse.js": [+ {+ "name": "agora_pulse",+ "title": "Read the Agora economy pulse",+ "descHead": "Read the Agora economy ticker — a live snapshot of the agent + human eco",+ "descHash": "7b1f7e64a4a2",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/agora-mcp/src/tools/register.js": [+ {+ "name": "agora_register",+ "title": "Register as an Agora citizen (on-chain)",+ "descHead": "JOIN AGORA as a citizen — a REAL on-chain AgenC registration signed by Y",+ "descHash": "97f5aaecd553",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "9cf922945aed"+ }+ ],+ "packages/alerts-mcp/src/tools/create-alert-rule.js": [+ {+ "name": "create_alert_rule",+ "title": "Create a pump.fun alert rule",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "ea83fa92b037"+ }+ ],+ "packages/alerts-mcp/src/tools/delete-alert-rule.js": [+ {+ "name": "delete_alert_rule",+ "title": "Delete a pump.fun alert rule",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": false,+ "destructiveHint": true,+ "openWorldHint": true+ },+ "schemaHash": "674ac40b43bc"+ }+ ],+ "packages/alerts-mcp/src/tools/get-alert-history.js": [+ {+ "name": "get_alert_history",+ "title": "Read fired pump.fun alert history",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "57448d8a874a"+ }+ ],+ "packages/alerts-mcp/src/tools/list-alert-rules.js": [+ {+ "name": "list_alert_rules",+ "title": "List my pump.fun alert rules",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/alerts-mcp/src/tools/update-alert-rule.js": [+ {+ "name": "update_alert_rule",+ "title": "Update a pump.fun alert rule",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "28c55131a59d"+ }+ ],+ "packages/audio-mcp/src/tools/audio-to-face.js": [+ {+ "name": "audio_to_face",+ "title": "Audio to face (lipsync)",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "aa8913cf4163"+ }+ ],+ "packages/audio-mcp/src/tools/motion-capture-clip.js": [+ {+ "name": "motion_capture_clip",+ "title": "Get a motion-capture clip",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "7f05b7596c05"+ }+ ],+ "packages/audio-mcp/src/tools/motion-capture-clips.js": [+ {+ "name": "motion_capture_clips",+ "title": "List motion-capture clips",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "a43e9f15e147"+ }+ ],+ "packages/audio-mcp/src/tools/speech-to-text.js": [+ {+ "name": "speech_to_text",+ "title": "Speech to text",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "3fb8d1bd797a"+ }+ ],+ "packages/audio-mcp/src/tools/text-to-speech.js": [+ {+ "name": "text_to_speech",+ "title": "Text to speech",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "1ac3d0fcf564"+ }+ ],+ "packages/autopilot-mcp/src/tools/adjust-proposal.js": [+ {+ "name": "adjust_proposal",+ "title": "Adjust a pending autopilot proposal",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "e63500caff2c"+ }+ ],+ "packages/autopilot-mcp/src/tools/compute-trust.js": [+ {+ "name": "compute_trust",+ "title": "Compute autopilot trust level",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "5469b97c4de9"+ }+ ],+ "packages/autopilot-mcp/src/tools/dismiss-proposal.js": [+ {+ "name": "dismiss_proposal",+ "title": "Dismiss a pending autopilot proposal",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "5dee3b70d29f"+ }+ ],+ "packages/autopilot-mcp/src/tools/dryrun-proposal.js": [+ {+ "name": "dryrun_proposal",+ "title": "Dry-run an autopilot proposal",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "83d541cf5b8e"+ }+ ],+ "packages/autopilot-mcp/src/tools/execute-proposal.js": [+ {+ "name": "execute_proposal",+ "title": "Execute an autopilot proposal (moves real value)",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "6d98ad17b42c"+ }+ ],+ "packages/autopilot-mcp/src/tools/generate-proposals.js": [+ {+ "name": "generate_proposals",+ "title": "Generate autopilot proposals",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "13c638018a64"+ }+ ],+ "packages/autopilot-mcp/src/tools/get-config.js": [+ {+ "name": "get_autopilot_config",+ "title": "Get autopilot config",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "9299711b3c60"+ }+ ],+ "packages/autopilot-mcp/src/tools/list-activity.js": [+ {+ "name": "list_autopilot_activity",+ "title": "List autopilot activity (signed receipts)",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "602b3afad0c4"+ }+ ],+ "packages/autopilot-mcp/src/tools/list-proposals.js": [+ {+ "name": "list_proposals",+ "title": "List autopilot proposals",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "abf1a7eb99d1"+ }+ ],+ "packages/autopilot-mcp/src/tools/set-config.js": [+ {+ "name": "set_autopilot_config",+ "title": "Set autopilot config",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "98ab349ef632"+ }+ ],+ "packages/autopilot-mcp/src/tools/undo-action.js": [+ {+ "name": "undo_action",+ "title": "Undo a reversible autopilot action",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "b08ae838dfc8"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/dress-avatar.js": [+ {+ "name": "dress_avatar",+ "title": "Apply accessories + pose to a spawned avatar",+ "descHead": "Apply (or replace) accessories on a spawned avatar session and optionall",+ "descHash": "4f872f43c5de",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "28f7cec654be"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/ens-sns-resolve.js": [+ {+ "name": "ens_sns_resolve",+ "title": "Resolve ENS + SNS names to addresses",+ "descHead": "Resolve a human-readable name to addresses across ENS (Ethereum) and SNS",+ "descHash": "d21fbb09d443",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "186d1864be92"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/generate-avatar.js": [+ {+ "name": "generate_avatar",+ "title": "Generate a 3D avatar (Replicate text-to-3D)",+ "descHead": "Generate a textured GLB from a text prompt or reference image URLs via R",+ "descHash": "45560bafc5c4",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "168929e4a4ae"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/inspect-glb.js": [+ {+ "name": "inspect_glb",+ "title": "Inspect a GLB / glTF 3D model",+ "descHead": "Fetch any GLB URL (or data: URL) and return a full structural breakdown:",+ "descHash": "94974ec659b1",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "b85aabec39f9"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/list-animations.js": [+ {+ "name": "list_animations",+ "title": "List three.ws pose presets + animation slots",+ "descHead": "Return the three.ws pose preset catalog (T-pose, A-pose, wave, thinker, ",+ "descHash": "3913dc7c8b98",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/list-avatars.js": [+ {+ "name": "list_avatars",+ "title": "List three.ws default avatars + accessories",+ "descHead": "Return the catalog of default 3D avatars (default, cz) and accessories (",+ "descHash": "4a0549f53d96",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/optimize-glb.js": [+ {+ "name": "optimize_glb",+ "title": "Optimize a GLB (dedup, prune, weld, Draco)",+ "descHead": "Run a @gltf-transform/functions optimization pipeline on a GLB URL: dedu",+ "descHash": "03c3982dd91d",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "c63918aa820c"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/pump-buy.js": [+ {+ "name": "pump_buy",+ "title": "Buy a Solana token via Jupiter (direct or Jito-bundled)",+ "descHead": "Swap SOL → target mint via Jupiter aggregator. Direct mode = one tx sign",+ "descHash": "2a5ec65bb978",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "3c5c2209541c"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/pump-collect.js": [+ {+ "name": "pump_collect_fees",+ "title": "Atomic pump.fun creator-fee collection (Jito bundle)",+ "descHead": "Collect a pump.fun coin's creator-fee vault and route the SOL to a safe ",+ "descHash": "1a5094103629",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "fa11cc2059d5"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/pump-launch.js": [+ {+ "name": "pump_launch",+ "title": "Atomic pump.fun launch (Jito bundle, separate funder/creator)",+ "descHead": "Launch a pump.fun token atomically via a Jito bundle. Funder pays its ow",+ "descHash": "02787a83c6d1",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "7ccd18ae503c"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/pump-snapshot.js": [+ {+ "name": "pump_snapshot",+ "title": "Live pump.fun / Solana token snapshot",+ "descHead": "Live snapshot for a Solana token (SPL or pump.fun): USD price (Jupiter),",+ "descHash": "c4bea0baa681",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "f95ff96b154a"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/render-avatar.js": [+ {+ "name": "render_avatar",+ "title": "Render a posed avatar (pose + camera + expression)",+ "descHead": "Render an avatar GLB with a three.ws pose preset, camera orbit, and opti",+ "descHash": "7c1ec5431ed9",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "f0764b076264"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/spawn-avatar.js": [+ {+ "name": "spawn_avatar",+ "title": "Spawn a 3D avatar session",+ "descHead": "Spawn a 3D avatar from a curated default (preset=\"default\" or \"cz\") or f",+ "descHash": "c3384eaadd16",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "21935bd3d67c"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/speak.js": [+ {+ "name": "speak",+ "title": "Avatar speaks (TTS)",+ "descHead": "Synthesize speech for an avatar session and return a base64 audio data U",+ "descHash": "ac95949fb9db",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "a799d54594a0"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/thumbnail-glb.js": [+ {+ "name": "thumbnail_glb",+ "title": "Render a GLB to a PNG thumbnail",+ "descHead": "Render any public GLB URL to a PNG via three.ws's hosted three-light rig",+ "descHash": "9f954ad41b72",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "fb813c0a2ea5"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/validate-glb.js": [+ {+ "name": "validate_glb",+ "title": "Validate a GLB / glTF against the Khronos spec",+ "descHead": "Run the official Khronos gltf-validator against a GLB URL. Returns error",+ "descHash": "d50330608926",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "90ba7dda1baa"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/viewer-url.js": [+ {+ "name": "viewer_url",+ "title": "Build a three.ws viewer URL + embed snippet",+ "descHead": "Build a shareable https://three.ws/viewer?... URL that opens any GLB in ",+ "descHash": "92579a5c4dfe",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "64d3340259e8"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/wallet-balance.js": [+ {+ "name": "wallet_balance",+ "title": "Read Solana wallet balances (SOL + SPL tokens)",+ "descHead": "Return SOL balance and all SPL token balances (including Token-2022) for",+ "descHash": "dfb87c21b60a",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "6c06de5e1f9f"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/wallet-create.js": [+ {+ "name": "wallet_create",+ "title": "Create a Solana wallet (optionally vanity-grinded)",+ "descHead": "Generate a Solana keypair locally. Optionally grind for a base58 prefix/",+ "descHash": "a83887009551",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": false+ },+ "schemaHash": "1f05b8548040"+ }+ ],+ "packages/avatar-agent-mcp/src/tools/wallet-send.js": [+ {+ "name": "wallet_send",+ "title": "Send SOL on Solana mainnet",+ "descHead": "Send SOL from the configured signer to a destination pubkey. The signer ",+ "descHash": "7b8d0d5b7d25",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "355a8db8b5cd"+ }+ ],+ "packages/billing-mcp/src/tools/billing-summary.js": [+ {+ "name": "get_billing_summary",+ "title": "My plan, quotas, and current usage",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/billing-mcp/src/tools/export-billing-history.js": [+ {+ "name": "export_billing_history",+ "title": "Export my billing history as CSV",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "e2150edbc97f"+ }+ ],+ "packages/billing-mcp/src/tools/fee-info.js": [+ {+ "name": "get_fee_info",+ "title": "Current platform fee rate",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/billing-mcp/src/tools/get-receipt.js": [+ {+ "name": "get_receipt",+ "title": "Get one receipt (per-charge or per-purchase)",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "6d5d0d20e194"+ }+ ],+ "packages/billing-mcp/src/tools/get-revenue.js": [+ {+ "name": "get_revenue",+ "title": "My agents’ earnings (revenue + subscriptions)",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "3f1680deb206"+ }+ ],+ "packages/billing-mcp/src/tools/query-usage.js": [+ {+ "name": "query_usage",+ "title": "My metered usage / invoice statement for a period",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "2a36fb1e6577"+ }+ ],+ "packages/brain-mcp/src/tools/chat.js": [+ {+ "name": "chat",+ "title": "Run a chat completion",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "6abff79eeaf6"+ }+ ],+ "packages/brain-mcp/src/tools/list-providers.js": [+ {+ "name": "list_providers",+ "title": "List LLM providers and models",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/clash-mcp/src/tools/enlist-faction.js": [+ {+ "name": "enlist_faction",+ "title": "Enlist in a Coin Clash faction",+ "descHead": "Enlist the signer's wallet as a soldier in a Coin Clash faction and retu",+ "descHash": "3ed7170eeeac",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "4bb7fdcc18d0"+ }+ ],+ "packages/clash-mcp/src/tools/get-clash-leaderboard.js": [+ {+ "name": "get_clash_leaderboard",+ "title": "Coin Clash leaderboard",+ "descHead": "Rank Coin Clash factions by their all-time war record. Returns `board`: ",+ "descHash": "23cbf9d5938f",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "34a52e4809b2"+ }+ ],+ "packages/clash-mcp/src/tools/get-clash-state.js": [+ {+ "name": "get_clash_state",+ "title": "Coin Clash battle board",+ "descHead": "Read the live Coin Clash board for the current round. Coin Clash is thre",+ "descHash": "1d0ba279475f",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/clash-mcp/src/tools/rally-faction.js": [+ {+ "name": "rally_faction",+ "title": "Rally power for a Coin Clash faction",+ "descHead": "Rally for a Coin Clash faction by spending taps as battle power for the ",+ "descHash": "de08c50debca",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "646bbfff3c48"+ }+ ],+ "packages/copy-mcp/src/tools/cancel-subscription.js": [+ {+ "name": "cancel_subscription",+ "title": "Stop a copy-trade subscription",+ "descHead": "Stop following a leader: transitions the subscription to \"stopped\" so no",+ "descHash": "3c97e4e427be",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "destructiveHint": true,+ "openWorldHint": true+ },+ "schemaHash": "cd7952340b7e"+ }+ ],+ "packages/copy-mcp/src/tools/create-subscription.js": [+ {+ "name": "create_subscription",+ "title": "Follow a leader (create / update subscription)",+ "descHead": "Follow a copy-trade leader from the authenticated account, defining how ",+ "descHash": "e4803ddf0e6c",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "3f1bbe7a599a"+ }+ ],+ "packages/copy-mcp/src/tools/get-earnings.js": [+ {+ "name": "get_earnings",+ "title": "Copy-trade earnings & fees owed",+ "descHead": "Read copy-trade performance-fee accounting. Without agent_id: the authen",+ "descHash": "e002ec5962a0",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "e2205e0864b3"+ }+ ],+ "packages/copy-mcp/src/tools/get-executions.js": [+ {+ "name": "get_executions",+ "title": "List copy executions (intent inbox)",+ "descHead": "List the authenticated account's copy executions — the sized, guard-chec",+ "descHash": "cbe66041c82b",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "0a263e086d8d"+ }+ ],+ "packages/copy-mcp/src/tools/list-subscriptions.js": [+ {+ "name": "list_subscriptions",+ "title": "List my copy-trade subscriptions",+ "descHead": "List the copy-trade subscriptions belonging to the authenticated account",+ "descHash": "70f853e46f6f",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/copy-mcp/src/tools/record-execution.js": [+ {+ "name": "record_execution",+ "title": "Record acting on a copy intent",+ "descHead": "Resolve a PENDING copy intent (from get_executions) by recording how you",+ "descHash": "853880d7f5bf",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "6f078813dd93"+ }+ ],+ "packages/copy-mcp/src/tools/update-subscription.js": [+ {+ "name": "update_subscription",+ "title": "Update a copy-trade subscription",+ "descHead": "Re-tune an existing copy-trade subscription by id. Pause it (stop new co",+ "descHash": "1c612826a084",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "e1050aace9f4"+ }+ ],+ "packages/intel-mcp/src/tools/copy-smart-wallets.js": [+ {+ "name": "copy_smart_wallets",+ "title": "Copy-trade smart wallet directory",+ "descHead": "Browse the curated Smart Money directory for copy-trading: deduplicated ",+ "descHash": "aadbfee4fb5b",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "89a6557b76a5"+ }+ ],+ "packages/intel-mcp/src/tools/kol-leaderboard.js": [+ {+ "name": "kol_leaderboard",+ "title": "KOL trader leaderboard",+ "descHead": "Rank the tracked key-opinion-leader (KOL) traders by realized performanc",+ "descHash": "4eda74884ae4",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "52600bee9606"+ }+ ],+ "packages/intel-mcp/src/tools/kol-trades.js": [+ {+ "name": "kol_trades",+ "title": "Recent KOL trades on a mint",+ "descHead": "See which tracked KOL wallets have recently traded a specific mint. Retu",+ "descHash": "5aaecc107a31",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "bab7d662b54d"+ }+ ],+ "packages/intel-mcp/src/tools/signal-feed.js": [+ {+ "name": "signal_feed",+ "title": "Signal feed track record + recent signals",+ "descHead": "Read one signal feed's public detail: the publisher's verified track rec",+ "descHash": "e28d08215cd4",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "20529353514e"+ }+ ],+ "packages/intel-mcp/src/tools/smart-money-coin.js": [+ {+ "name": "smart_money_coin",+ "title": "Smart-money score for a coin",+ "descHead": "Assess a coin by WHO is net-buying it right now. Returns a 0–100 smart_m",+ "descHash": "e779edb0c8bf",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "a7357494eb41"+ }+ ],+ "packages/intel-mcp/src/tools/wallet-intel.js": [+ {+ "name": "wallet_intel",+ "title": "Wallet reputation + smart-money card",+ "descHead": "Pull one wallet's realized reputation, computed from its observed buys j",+ "descHash": "8eb086935104",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "e8343ba727ea"+ }+ ],+ "packages/kol-mcp/src/tools/get-wallet-portfolio.js": [+ {+ "name": "get_wallet_portfolio",+ "title": "KOL wallet portfolio + P&L",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "c9f7c9236088"+ }+ ],+ "packages/kol-mcp/src/tools/get-wallet-trades.js": [+ {+ "name": "get_wallet_trades",+ "title": "A KOL wallet's trades on a mint",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "efe641475e48"+ }+ ],+ "packages/loom-mcp/src/tools/get-creation.js": [+ {+ "name": "get_creation",+ "title": "Fetch one Loom creation by id",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "61edbfb1da90"+ }+ ],+ "packages/loom-mcp/src/tools/get-loom-feed.js": [+ {+ "name": "get_loom_feed",+ "title": "Browse the Loom 3D-creation gallery",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "dfbe9768f356"+ }+ ],+ "packages/loom-mcp/src/tools/submit-creation.js": [+ {+ "name": "submit_creation",+ "title": "Submit a creation to the Loom gallery",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "e39df391c034"+ }+ ],+ "packages/marketplace-mcp/src/tools/agent-categories.js": [+ {+ "name": "agent_categories",+ "title": "List agent marketplace categories",+ "descHead": "List the agent marketplace categories with the count of published agents",+ "descHash": "a80a3c66efee",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/marketplace-mcp/src/tools/agent-detail.js": [+ {+ "name": "agent_detail",+ "title": "Fetch a marketplace agent by id",+ "descHead": "Fetch one published marketplace agent by its id, including its full deta",+ "descHash": "d60282de0b42",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "307c3857ed90"+ }+ ],+ "packages/marketplace-mcp/src/tools/browse-agents.js": [+ {+ "name": "browse_agents",+ "title": "Browse the agent marketplace",+ "descHead": "Search and page the public three.ws agent marketplace. Filter by categor",+ "descHash": "5b0feeada74f",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "38c217c26128"+ }+ ],+ "packages/marketplace-mcp/src/tools/browse-skills.js": [+ {+ "name": "browse_skills",+ "title": "Browse the skills catalog",+ "descHead": "Search and page the public three.ws skills catalog — reusable tools and ",+ "descHash": "cc6bca95f4db",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "b99134895842"+ }+ ],+ "packages/marketplace-mcp/src/tools/skill-categories.js": [+ {+ "name": "skill_categories",+ "title": "List skills catalog categories",+ "descHead": "List the skills catalog categories that have at least one public skill, ",+ "descHash": "bc2eb1e5c29b",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/naming-mcp/src/tools/sns-resolve.js": [+ {+ "name": "sns_resolve",+ "title": "Resolve a .sol name to its owner wallet",+ "descHead": "Resolve a Solana Name Service (.sol) name to the base58 wallet address t",+ "descHash": "143cbd9389dd",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "665d28ca0f6a"+ }+ ],+ "packages/naming-mcp/src/tools/sns-reverse.js": [+ {+ "name": "sns_reverse",+ "title": "Reverse-lookup a wallet to its primary .sol name",+ "descHead": "Reverse-lookup a Solana wallet to the primary .sol name it has set as it",+ "descHash": "49cbdc5064c0",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "c3e3a17c0d1a"+ }+ ],+ "packages/naming-mcp/src/tools/threews-availability.js": [+ {+ "name": "threews_availability",+ "title": "Check if a *.threews.sol agent identity is available",+ "descHead": "Check whether \"<label>.threews.sol\" is available to claim as a three.ws ",+ "descHash": "98daa55f6136",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "e3adec102cf2"+ }+ ],+ "packages/notifications-mcp/src/tools/delete-notification.js": [+ {+ "name": "delete_notification",+ "title": "Delete notification",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "8b648ee02b76"+ }+ ],+ "packages/notifications-mcp/src/tools/get-preferences.js": [+ {+ "name": "get_preferences",+ "title": "Get notification preferences",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/notifications-mcp/src/tools/list-notifications.js": [+ {+ "name": "list_notifications",+ "title": "List notifications",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "0b3481f0dd21"+ }+ ],+ "packages/notifications-mcp/src/tools/mark-read.js": [+ {+ "name": "mark_read",+ "title": "Mark notifications read",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "92824b30cd7d"+ }+ ],+ "packages/notifications-mcp/src/tools/register-push-device.js": [+ {+ "name": "register_push_device",+ "title": "Register push device",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "bf52da591d2e"+ }+ ],+ "packages/notifications-mcp/src/tools/set-preferences.js": [+ {+ "name": "set_preferences",+ "title": "Set notification preferences",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "270e00b4f5aa"+ }+ ],+ "packages/notifications-mcp/src/tools/unregister-push-device.js": [+ {+ "name": "unregister_push_device",+ "title": "Unregister push device",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "dd1452495140"+ }+ ],+ "packages/portfolio-mcp/src/tools/portfolio-asset.js": [+ {+ "name": "get_portfolio_asset",+ "title": "My position in one token (holdings + market + chart)",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "b8b2b70c9e52"+ }+ ],+ "packages/portfolio-mcp/src/tools/portfolio-history.js": [+ {+ "name": "get_portfolio_history",+ "title": "My portfolio value over time",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "2447c0835603"+ }+ ],+ "packages/portfolio-mcp/src/tools/portfolio-summary.js": [+ {+ "name": "get_portfolio_summary",+ "title": "My agents’ live portfolio (holdings + USD value)",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "2774dafb1fcf"+ }+ ],+ "packages/portfolio-mcp/src/tools/send-transfer.js": [+ {+ "name": "send_transfer",+ "title": "Send SOL or an SPL token on Solana mainnet",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "6beb337c65ee"+ }+ ],+ "packages/portfolio-mcp/src/tools/trades-feed.js": [+ {+ "name": "get_trades_feed",+ "title": "Public closed-trade PnL feed",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "75391158a407"+ }+ ],+ "packages/portfolio-mcp/src/tools/wallet-balances.js": [+ {+ "name": "get_wallet_balances",+ "title": "Live on-chain balances for a Solana wallet",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "4a8838fb67ab"+ }+ ],+ "packages/provenance-mcp/src/tools/append-agent-action.js": [+ {+ "name": "append_agent_action",+ "title": "Append a signed action to the provenance ledger",+ "descHead": "Record an action in an agent's append-only provenance ledger — the perma",+ "descHash": "094f7fe192ca",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "fef696e12ba3"+ }+ ],+ "packages/provenance-mcp/src/tools/list-agent-actions.js": [+ {+ "name": "list_agent_actions",+ "title": "List an agent's action-provenance trail",+ "descHead": "Read an agent's append-only action log, newest-first, cursor-paginated. ",+ "descHash": "6590535dc231",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "d01cadbc72e4"+ }+ ],+ "packages/provenance-mcp/src/tools/query-action.js": [+ {+ "name": "query_action",+ "title": "Fetch + verify one provenance action",+ "descHead": "Fetch a single action from an agent's append-only log by its id, then ve",+ "descHash": "626838234347",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "4324bb5ace2b"+ }+ ],+ "packages/scene-mcp/src/tools/compose-scene.js": [+ {+ "name": "compose_scene",+ "title": "Compose a 3D diorama plan from one sentence",+ "descHead": "Compose a tiny 3D diorama from one short sentence. Returns a PLAN: an ev",+ "descHash": "d42bccef405d",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "cc6d79ff4756"+ }+ ],+ "packages/scene-mcp/src/tools/get-scene.js": [+ {+ "name": "get_scene",+ "title": "Fetch a saved diorama by id",+ "descHead": "Fetch one saved diorama (a fully-forged 3D world) by its id, including i",+ "descHash": "37f599d1d667",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "adacb80a1ba6"+ }+ ],+ "packages/scene-mcp/src/tools/list-scenes.js": [+ {+ "name": "list_scenes",+ "title": "List recent or featured dioramas",+ "descHead": "Browse the public diorama gallery — the most recent saved worlds, or the",+ "descHash": "79e7f4cc0eb6",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "2b69c8fade89"+ }+ ],+ "packages/signals-mcp/src/tools/get-mirror-leaderboard.js": [+ {+ "name": "get_mirror_leaderboard",+ "title": "Rank signal publishers by realized performance",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "fb9a88267798"+ }+ ],+ "packages/signals-mcp/src/tools/get-subscriptions.js": [+ {+ "name": "get_subscriptions",+ "title": "List your signal subscriptions + delivery history",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/signals-mcp/src/tools/list-signal-feeds.js": [+ {+ "name": "list_signal_feeds",+ "title": "Browse the signal-feed marketplace",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "9f9cd383a244"+ }+ ],+ "packages/signals-mcp/src/tools/set-subscription-status.js": [+ {+ "name": "set_subscription_status",+ "title": "Resume, pause, stop, or kill a subscription",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "863e00e632ae"+ }+ ],+ "packages/signals-mcp/src/tools/subscribe-signal.js": [+ {+ "name": "subscribe_signal",+ "title": "Subscribe an agent to a signal feed",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "b73a7b0f84ee"+ }+ ],+ "packages/three-token-mcp/src/tools/three-balance.js": [+ {+ "name": "three_balance",+ "title": "Read a wallet's $THREE + SOL balance",+ "descHead": "Return the $THREE and SOL balance for a Solana pubkey. If no pubkey is g",+ "descHash": "f79639fcd1d7",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "fa8695604366"+ }+ ],+ "packages/three-token-mcp/src/tools/three-burn.js": [+ {+ "name": "three_burn",+ "title": "Burn $THREE on-chain (incinerator + treasury split)",+ "descHead": "Burn a USD-denominated amount of the $THREE your wallet holds. Quotes US",+ "descHash": "31d52b60bec9",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "a36f57cc4d97"+ }+ ],+ "packages/three-token-mcp/src/tools/three-price.js": [+ {+ "name": "three_price",+ "title": "Live $THREE price (Jupiter) + USD→$THREE quote",+ "descHead": "Return the live USD price of $THREE (Jupiter primary, Birdeye fallback).",+ "descHash": "b589970ff915",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "73d2da698b68"+ }+ ],+ "packages/tutor-mcp/src/tools/close-session.js": [+ {+ "name": "close_session",+ "title": "Close a tutoring session (finalize invoice)",+ "descHead": "Finalize a Pay-As-You-Learn tutoring session and return its itemized, at",+ "descHash": "be4bf66b6acf",+ "annotations": {+ "readOnlyHint": false,+ "idempotentHint": true,+ "destructiveHint": false,+ "openWorldHint": true+ },+ "schemaHash": "c9c2f3cee9ad"+ }+ ],+ "packages/tutor-mcp/src/tools/load-session.js": [+ {+ "name": "load_session",+ "title": "Load a tutoring session ledger",+ "descHead": "Read the running tab for a Pay-As-You-Learn tutoring session by its sess",+ "descHash": "cc76a60f47f7",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "88ac16a4a3f5"+ }+ ],+ "packages/vanity-mcp/src/tools/vanity-appraise.js": [+ {+ "name": "vanity_appraise",+ "title": "Appraise the rarity of a Solana address",+ "descHead": "Appraise how rare a Solana address is: its detected vanity pattern, rari",+ "descHash": "662f9cf8747a",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "166e5158df47"+ }+ ],+ "packages/vanity-mcp/src/tools/vanity-board.js": [+ {+ "name": "vanity_board",+ "title": "Browse the vanity grind-bounty board",+ "descHead": "Browse the public grind-bounty board: vanity-address bounties requesters",+ "descHash": "478e019e2380",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "ddddfbefbd74"+ }+ ],+ "packages/vanity-mcp/src/tools/vanity-config.js": [+ {+ "name": "vanity_config",+ "title": "Bounty market config: payout + asset metadata",+ "descHead": "Read the grind-bounty market configuration: whether on-chain payouts are",+ "descHash": "f42dd6079380",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/vanity-mcp/src/tools/vanity-gallery.js": [+ {+ "name": "vanity_gallery",+ "title": "Browse the proof-of-grind rarity gallery",+ "descHead": "Browse the public proof-of-grind gallery: rare Solana addresses people h",+ "descHash": "947482b1ea36",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "055ce9dfa9d4"+ }+ ],+ "packages/vanity-mcp/src/tools/vanity-leaderboard.js": [+ {+ "name": "vanity_leaderboard",+ "title": "Top grinders by USDC earned",+ "descHead": "Rank the worker fleet: the top grinders by total USDC earned from winnin",+ "descHash": "5e03ddeb0723",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "89093629b6cc"+ }+ ],+ "packages/vanity-mcp/src/tools/vanity-open.js": [+ {+ "name": "vanity_open",+ "title": "List claimable open bounties for workers",+ "descHead": "List the open, unexpired bounties a grinding worker can race to claim — ",+ "descHash": "45f3acbc46ae",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "829a38859aa9"+ }+ ],+ "packages/vanity-mcp/src/tools/vanity-quote.js": [+ {+ "name": "vanity_quote",+ "title": "Quote the bounty price for a vanity pattern",+ "descHead": "Quote how hard a Solana vanity address is and what to escrow for it. Giv",+ "descHash": "a075580b128b",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "f0ea1a5d1d60"+ }+ ],+ "packages/vanity-mcp/src/tools/vanity-stats.js": [+ {+ "name": "vanity_stats",+ "title": "Live grind-bounty market totals",+ "descHead": "Get live totals for the grind-bounty market: how many bounties are open,",+ "descHash": "ff50c0c21880",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/vision-mcp/src/tools/analyze-image.js": [+ {+ "name": "analyze_image",+ "title": "Analyze an image against a prompt",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "6aab71ea600e"+ }+ ],+ "packages/vision-mcp/src/tools/describe-image.js": [+ {+ "name": "describe_image",+ "title": "Describe an image in natural language",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "41557805ea34"+ }+ ],+ "packages/vision-mcp/src/tools/vision-status.js": [+ {+ "name": "get_vision_status",+ "title": "Vision availability + accepted formats",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "44136fa355b3"+ }+ ],+ "packages/x402-mcp/src/tools/find-services.js": [+ {+ "name": "find_services",+ "title": "Find paid x402 services the agent can call",+ "descHead": "Search the live x402 facilitator network (PayAI + Coinbase CDP bazaar) f",+ "descHash": "244a81abb0d0",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "0ae1eb189146"+ }+ ],+ "packages/x402-mcp/src/tools/inspect-endpoint.js": [+ {+ "name": "inspect_endpoint",+ "title": "Inspect an x402 endpoint (price + requirements, no payment)",+ "descHead": "Fetch an x402 endpoint and return its 402 payment requirements — every a",+ "descHash": "278c58d6e1c4",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "771176719c9d"+ }+ ],+ "packages/x402-mcp/src/tools/pay-and-call.js": [+ {+ "name": "pay_and_call",+ "title": "Pay an x402 endpoint in USDC or $THREE and return its result",+ "descHead": "Call a paid x402 endpoint and settle the payment automatically, then ret",+ "descHash": "bcbac82f6706",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "11dd41d810ab"+ }+ ],+ "packages/x402-mcp/src/tools/x402-wallet.js": [+ {+ "name": "x402_wallet",+ "title": "The agent's x402 spending wallet (address + balance)",+ "descHead": "Show a Solana wallet's address and live SOL + USDC balance. With no `add",+ "descHash": "a9ff0cfff056",+ "annotations": {+ "readOnlyHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "1cec1d1a0dae"+ }]}diff --git a/tests/spatial-mcp.test.js b/tests/spatial-mcp.test.jsnew file mode 100644index 000000000..3ebfd1ee8--- /dev/null+++ b/tests/spatial-mcp.test.js@@ -0,0 +1,173 @@+import { describe, it, expect, vi, afterEach } from 'vitest';++import {+ SPATIAL_MCP_VERSION,+ buildSpatialArtifact,+ validateSpatialArtifact,+ isConformantSpatialArtifact,+} from '../api/_lib/spatial-mcp.js';+import { toolDefs as spatialDefs } from '../api/_mcp3d/tools/spatial.js';+import { dispatch } from '../api/_mcp-studio/dispatch.js';++const GLB = 'https://three.ws/cdn/creations/model.glb';++describe('buildSpatialArtifact', () => {+ it('produces a conformant artifact from just a glbUrl', () => {+ const a = buildSpatialArtifact({ glbUrl: GLB });+ expect(a.spatialMcpVersion).toBe(SPATIAL_MCP_VERSION);+ expect(a.kind).toBe('model');+ expect(a.scene.glbUrl).toBe(GLB);+ expect(a.scene.format).toBe('glb');+ expect(isConformantSpatialArtifact(a)).toBe(true);+ });++ it('omits optional blocks that were not provided (no empty scaffolding)', () => {+ const a = buildSpatialArtifact({ glbUrl: GLB });+ expect(a.animation).toBeUndefined();+ expect(a.persona).toBeUndefined();+ expect(a.ar).toBeUndefined();+ expect(a.meta).toBeUndefined();+ });++ it('adds animation hooks only when rigged/clips are present', () => {+ expect(buildSpatialArtifact({ glbUrl: GLB, rigged: true }).animation).toBeTruthy();+ expect(buildSpatialArtifact({ glbUrl: GLB, clips: ['idle'] }).animation.clips).toEqual(['idle']);+ });++ it('includes an AR block only when a real https AR asset is supplied', () => {+ expect(buildSpatialArtifact({ glbUrl: GLB, ar: { usdzUrl: 'http://x/m.usdz' } }).ar).toBeUndefined();+ const a = buildSpatialArtifact({ glbUrl: GLB, ar: { usdzUrl: 'https://three.ws/m.usdz' } });+ expect(a.ar.supported).toBe(true);+ expect(a.ar.usdzUrl).toBe('https://three.ws/m.usdz');+ });++ it('maps a persona id into a speakable hook', () => {+ expect(buildSpatialArtifact({ glbUrl: GLB, personaId: 'psn_1' }).persona).toEqual({ id: 'psn_1', speakable: true });+ });+});++describe('validateSpatialArtifact — rejects with actionable errors', () => {+ it('flags a non-object payload', () => {+ const r = validateSpatialArtifact('nope');+ expect(r.valid).toBe(false);+ expect(r.errors[0].message).toMatch(/JSON object/);+ });++ it('requires spatialMcpVersion, kind, and scene.glbUrl', () => {+ const r = validateSpatialArtifact({});+ expect(r.valid).toBe(false);+ const paths = r.errors.map((e) => e.path);+ expect(paths).toContain('spatialMcpVersion');+ expect(paths).toContain('kind');+ expect(paths).toContain('scene');+ });++ it('rejects a non-https glbUrl with a fix message', () => {+ const r = validateSpatialArtifact({ spatialMcpVersion: '0.1', kind: 'model', scene: { glbUrl: 'http://x/m.glb' } });+ expect(r.valid).toBe(false);+ const e = r.errors.find((x) => x.path === 'scene.glbUrl');+ expect(e.message).toMatch(/https/);+ });++ it('rejects an unknown version and unknown kind', () => {+ const rv = validateSpatialArtifact({ spatialMcpVersion: '9.9', kind: 'model', scene: { glbUrl: GLB } });+ expect(rv.errors.some((e) => e.path === 'spatialMcpVersion')).toBe(true);+ const rk = validateSpatialArtifact({ spatialMcpVersion: '0.1', kind: 'hologram', scene: { glbUrl: GLB } });+ expect(rk.errors.some((e) => e.path === 'kind')).toBe(true);+ });++ it('rejects ar.supported:true with no concrete asset', () => {+ const r = validateSpatialArtifact({ spatialMcpVersion: '0.1', kind: 'model', scene: { glbUrl: GLB, format: 'glb' }, ar: { supported: true } });+ expect(r.errors.some((e) => e.path === 'ar.supported')).toBe(true);+ });++ it('warns (not errors) on unknown top-level fields', () => {+ const r = validateSpatialArtifact({ spatialMcpVersion: '0.1', kind: 'model', scene: { glbUrl: GLB, format: 'glb' }, camera: { autoRotate: true }, wat: 1 });+ expect(r.valid).toBe(true);+ expect(r.warnings.some((w) => w.path === 'wat')).toBe(true);+ });++ it('accepts a fully-populated artifact', () => {+ const a = buildSpatialArtifact({+ glbUrl: GLB, kind: 'avatar', rigged: true, clips: ['idle', 'wave'],+ personaId: 'psn_9', ar: { usdzUrl: 'https://three.ws/m.usdz', launchUrl: 'https://three.ws/ar?x=1' },+ prompt: 'a knight', title: 'Knight', viewerUrl: 'https://three.ws/viewer?src=x',+ });+ expect(validateSpatialArtifact(a).valid).toBe(true);+ });+});++describe('validate_spatial_response tool', () => {+ const tool = spatialDefs.find((d) => d.name === 'validate_spatial_response');++ it('is a free, read-only tool with the correct annotations', () => {+ expect(tool).toBeTruthy();+ expect(tool.scope).toBeUndefined(); // free — no payment scope+ expect(tool.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false });+ });++ it('returns valid:true with the spec version for a conformant artifact', async () => {+ const r = await tool.handler({ artifact: buildSpatialArtifact({ glbUrl: GLB }) });+ expect(r.structuredContent.valid).toBe(true);+ expect(r.structuredContent.specVersion).toBe(SPATIAL_MCP_VERSION);+ expect(r.content[0].text).toMatch(/Conformant/);+ });++ it('returns valid:false with actionable errors for a broken artifact', async () => {+ const r = await tool.handler({ artifact: { kind: 'model' } });+ expect(r.structuredContent.valid).toBe(false);+ expect(r.structuredContent.errors.length).toBeGreaterThan(0);+ expect(r.content[0].text).toMatch(/Fix these/);+ });++ it('carries no payment/coin surface in its definition', () => {+ const FORBIDDEN = /x402|payment|wallet|usdc|\$three|token|coin|price|\bpaid\b|onchain|web3|mint/i;+ expect(FORBIDDEN.test(JSON.stringify({ ...tool, handler: undefined }))).toBe(false);+ });+});++// The adoption invariant: every three.ws 3D generation tool emits a conformant+// spatial artifact. We drive the free studio dispatcher with a mocked /api/forge+// (synchronous done) and validate the real structuredContent.spatial it returns.+describe('all free-studio 3D tools emit conformant spatial artifacts', () => {+ afterEach(() => vi.restoreAllMocks());++ function mockForgeDone() {+ globalThis.fetch = vi.fn(async () => ({+ ok: true,+ status: 200,+ json: async () => ({ status: 'done', glb_url: GLB, job_id: 'J', creation_id: 'C', backend: 'x' }),+ }));+ }+ const auth = { userId: null, rateKey: '127.0.0.1', scope: '' };+ const req = { headers: { host: 'three.ws', 'x-forwarded-proto': 'https' } };+ const call = (name, args) =>+ dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth, req);++ const cases = [+ ['forge_free', { prompt: 'a friendly robot mascot' }],+ ['text_to_avatar', { prompt: 'a knight in armor' }],+ ['mesh_forge', { prompt: 'a worn leather armchair' }],+ ['rig_mesh', { glb_url: GLB }],+ ['forge_avatar', { prompt: 'a wizard character' }],+ ];++ for (const [name, args] of cases) {+ it(`${name} → conformant spatial artifact`, async () => {+ mockForgeDone();+ const r = await call(name, args);+ const spatial = r.result?.structuredContent?.spatial;+ expect(spatial, `${name} must emit structuredContent.spatial`).toBeTruthy();+ const v = validateSpatialArtifact(spatial);+ expect(v.valid, `${name} spatial errors: ${JSON.stringify(v.errors)}`).toBe(true);+ });+ }++ it('refine_model → conformant spatial artifact', async () => {+ mockForgeDone();+ const r = await call('refine_model', { glb_url: GLB, instruction: 'make it gold', parent_prompt: 'a robot' });+ const spatial = r.result?.structuredContent?.spatial;+ expect(spatial).toBeTruthy();+ expect(validateSpatialArtifact(spatial).valid).toBe(true);+ });+});diff --git a/tests/src/element-brain-config.test.js b/tests/src/element-brain-config.test.jsnew file mode 100644index 000000000..08362d4ed--- /dev/null+++ b/tests/src/element-brain-config.test.js@@ -0,0 +1,136 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Same mock set as element-boot-race.test.js — only exercising manifest+// resolution here, not rendering.+vi.mock('../../src/viewer.js', () => ({+ Viewer: class {+ constructor(stage) {+ this.stage = stage;+ this.scene = { background: null };+ this.renderer = { setClearAlpha() {} };+ }+ async load() {}+ dispose() {}+ },+}));+vi.mock('../../src/runtime/index.js', () => ({+ Runtime: class extends EventTarget {+ constructor() { super(); }+ destroy() {}+ },+}));+vi.mock('../../src/runtime/scene.js', () => ({ SceneController: class {} }));+vi.mock('../../src/skills/index.js', () => ({+ SkillRegistry: class { async install() { return { name: 'x', uri: 'x' }; } all() { return []; } },+}));+vi.mock('../../src/memory/index.js', () => ({+ Memory: { async load() { return { recall() { return []; } }; } },+}));+vi.mock('../../src/manifest.js', () => ({+ loadManifest: vi.fn(async () => ({+ spec: 'agent-manifest/0.1',+ _baseURI: '',+ name: 'Test',+ body: { uri: '' },+ brain: { provider: 'none' },+ voice: {},+ skills: [],+ })),+ fetchRelative: vi.fn(async () => ''),+}));+vi.mock('../../src/ipfs.js', () => ({ resolveURI: (u) => u }));+vi.mock('../../src/agent-resolver.js', () => ({+ resolveAgentById: vi.fn(),+ resolveByAgentId: vi.fn(async () => null),+ resolveByAvatarId: vi.fn(),+ AgentResolveError: class extends Error {},+}));+vi.mock('../../src/erc8004/resolver.js', () => ({+ parseAgentRef: () => null,+ resolveOnchainAgent: vi.fn(),+ toManifest: vi.fn(),+}));+vi.mock('../../src/pump/trade-reactions.js', () => ({+ attachTradeReactions: () => () => {},+}));+vi.mock('../../src/embed-action-bridge.js', () => ({ EmbedActionBridge: class { start() {} stop() {} } }));+vi.mock('../../src/agent-protocol.js', () => ({+ protocol: { emit() {}, on() {} },+ ACTION_TYPES: {},+}));++globalThis.fetch = vi.fn(async () => ({+ ok: false,+ status: 404,+ json: async () => ({}),+}));++const FREE_MODEL = 'meta-llama/llama-3.3-70b-instruct:free';++beforeEach(async () => {+ if (!customElements.get('agent-3d')) {+ await import('../../src/element.js');+ }+ document.body.innerHTML = '';+});++describe('<agent-3d> brain resolution', () => {+ it('defaults to a silent brain when no brain attribute is set (body=)', async () => {+ const el = document.createElement('agent-3d');+ el.setAttribute('body', 'https://example.com/avatar.glb');+ const manifest = await el._resolveManifest();+ expect(manifest.brain).toEqual({ provider: 'none' });+ });++ it('resolves brain="free" to the host-paid free model (body=)', async () => {+ const el = document.createElement('agent-3d');+ el.setAttribute('body', 'https://example.com/avatar.glb');+ el.setAttribute('brain', 'free');+ const manifest = await el._resolveManifest();+ expect(manifest.brain.provider).toBe('anthropic');+ expect(manifest.brain.model).toBe(FREE_MODEL);+ });++ it('is case-insensitive and trims whitespace for the free alias', async () => {+ const el = document.createElement('agent-3d');+ el.setAttribute('body', 'https://example.com/avatar.glb');+ el.setAttribute('brain', ' FREE ');+ const manifest = await el._resolveManifest();+ expect(manifest.brain.model).toBe(FREE_MODEL);+ });++ it('passes through an explicit model id unchanged (body=)', async () => {+ const el = document.createElement('agent-3d');+ el.setAttribute('body', 'https://example.com/avatar.glb');+ el.setAttribute('brain', 'claude-sonnet-4-6');+ const manifest = await el._resolveManifest();+ expect(manifest.brain.provider).toBe('anthropic');+ expect(manifest.brain.model).toBe('claude-sonnet-4-6');+ });++ it('carries the instructions attribute into brain.instructions (body=)', async () => {+ const el = document.createElement('agent-3d');+ el.setAttribute('body', 'https://example.com/avatar.glb');+ el.setAttribute('brain', 'free');+ el.setAttribute('instructions', 'You are Maya.');+ const manifest = await el._resolveManifest();+ expect(manifest.brain.instructions).toBe('You are Maya.');+ });++ it('honors brain="free" on a bare .glb src= too', async () => {+ const el = document.createElement('agent-3d');+ el.setAttribute('src', 'https://example.com/avatar.glb');+ el.setAttribute('brain', 'free');+ const manifest = await el._resolveManifest();+ expect(manifest.brain.provider).toBe('anthropic');+ expect(manifest.brain.model).toBe(FREE_MODEL);+ });++ it('keeps a bare .glb src= silent with no brain attribute', async () => {+ const el = document.createElement('agent-3d');+ el.setAttribute('src', 'https://example.com/avatar.glb');+ const manifest = await el._resolveManifest();+ expect(manifest.brain).toEqual({ provider: 'none' });+ });+});diff --git a/vercel.json b/vercel.jsonindex e00b2f43f..1103f86a3 100644--- a/vercel.json+++ b/vercel.json@@ -56,6 +56,9 @@"{api/3d/generate,api/3d/studio}.js": {"maxDuration": 120},+ "api/x402/embody.js": {+ "maxDuration": 300+ },"api/widgets/[id]/knowledge-process.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 300@@ -930,6 +933,38 @@"src": "/compare/?","dest": "/compare.html"},+ {+ "src": "/screener/?",+ "dest": "/screener.html"+ },+ {+ "src": "/categories/?",+ "dest": "/categories.html"+ },+ {+ "src": "/exchanges/?",+ "dest": "/exchanges.html"+ },+ {+ "src": "/derivatives/?",+ "dest": "/derivatives.html"+ },+ {+ "src": "/converter/?",+ "dest": "/converter.html"+ },+ {+ "src": "/defi/?",+ "dest": "/defi.html"+ },+ {+ "src": "/chains/?",+ "dest": "/chains.html"+ },+ {+ "src": "/stablecoins/?",+ "dest": "/stablecoins.html"+ },{"src": "/coin/([a-zA-Z0-9][a-zA-Z0-9_-]{0,99})/?","dest": "/coin.html"@@ -1177,6 +1212,10 @@"src": "/pose/?","dest": "/pose.html"},+ {+ "src": "/viewer/?",+ "dest": "/viewer.html"+ },{"src": "/pose-mini/?","dest": "/pose-mini.html"diff --git a/vite.config.js b/vite.config.jsindex 486a04655..a92d3ce1b 100644--- a/vite.config.js+++ b/vite.config.js@@ -448,6 +448,14 @@ const appConfig = {heatmap: resolve(__dirname, 'pages/heatmap.html'),gas: resolve(__dirname, 'pages/gas.html'),compare: resolve(__dirname, 'pages/compare.html'),+ screener: resolve(__dirname, 'pages/screener.html'),+ categories: resolve(__dirname, 'pages/categories.html'),+ exchanges: resolve(__dirname, 'pages/exchanges.html'),+ derivatives: resolve(__dirname, 'pages/derivatives.html'),+ converter: resolve(__dirname, 'pages/converter.html'),+ defi: resolve(__dirname, 'pages/defi.html'),+ chains: resolve(__dirname, 'pages/chains.html'),+ stablecoins: resolve(__dirname, 'pages/stablecoins.html'),trending: resolve(__dirname, 'pages/trending.html'),compose: resolve(__dirname, 'pages/compose.html'),'create-next': resolve(__dirname, 'pages/create-next.html'),@@ -972,6 +980,22 @@ support: resolve(__dirname, 'pages/support.html'),'/gas/': resolve(root, 'pages/gas.html'),'/compare': resolve(root, 'pages/compare.html'),'/compare/': resolve(root, 'pages/compare.html'),+ '/screener': resolve(root, 'pages/screener.html'),+ '/screener/': resolve(root, 'pages/screener.html'),+ '/categories': resolve(root, 'pages/categories.html'),+ '/categories/': resolve(root, 'pages/categories.html'),+ '/exchanges': resolve(root, 'pages/exchanges.html'),+ '/exchanges/': resolve(root, 'pages/exchanges.html'),+ '/derivatives': resolve(root, 'pages/derivatives.html'),+ '/derivatives/': resolve(root, 'pages/derivatives.html'),+ '/converter': resolve(root, 'pages/converter.html'),+ '/converter/': resolve(root, 'pages/converter.html'),+ '/defi': resolve(root, 'pages/defi.html'),+ '/defi/': resolve(root, 'pages/defi.html'),+ '/chains': resolve(root, 'pages/chains.html'),+ '/chains/': resolve(root, 'pages/chains.html'),+ '/stablecoins': resolve(root, 'pages/stablecoins.html'),+ '/stablecoins/': resolve(root, 'pages/stablecoins.html'),'/compose': resolve(root, 'pages/compose.html'),'/compose/': resolve(root, 'pages/compose.html'),'/create/next': resolve(root, 'pages/create-next.html'),diff --git a/vitest.config.js b/vitest.config.jsindex 3da1cae50..454cbf027 100644--- a/vitest.config.js+++ b/vitest.config.js@@ -66,6 +66,7 @@ export default defineConfig({'src/**/*.test.js','api/_lib/coin/**/*.test.js','tour-sdk/test/**/*.test.mjs',+ 'packages/*/tests/**/*.test.js',],// 45s proved too tight for this environment: with every fork cold-importing// multi-thousand-module graphs concurrently, single imports have beendiff --git a/workers/agent-sniper/Dockerfile b/workers/agent-sniper/Dockerfileindex b7bab4bdd..0a1a17a94 100644--- a/workers/agent-sniper/Dockerfile+++ b/workers/agent-sniper/Dockerfile@@ -27,9 +27,14 @@ RUN npm ci --ignore-scripts || npm install --ignore-scripts# Bring in source needed at runtime, then build the SDK's dist/ explicitly# (ignore-scripts skipped the postinstall build above). src/ is required too: the# worker's first-claim path imports api/_lib/pump-claims.js → src/pump/first-claims.js.+# packages/agent-sniper/src is required too: mayhem-gate.js imports+# createMayhemFilter from packages/agent-sniper/src/mayhem-filter.js (self-contained,+# only depends on @solana/web3.js which is already a root dependency) — only src/ is+# copied, not the whole package (its own node_modules/tests/bin are unused at runtime).COPY agent-payments-sdk ./agent-payments-sdkCOPY api ./apiCOPY src ./src+COPY packages/agent-sniper/src ./packages/agent-sniper/srcCOPY workers/agent-sniper ./workers/agent-sniperRUN npm run build --prefix agent-payments-sdk