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
chore: land in-progress platform work (services, personas, restyle, docs)
nirholas10961c54a91a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5b2020d64..950974efc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 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.+- **BNB Chain — Three Genuinely-Unique Demos** (`/bnb`) — The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.- **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.@@ -16,9 +17,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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]`+- **BNB Chain hub: three uniquely-BNB demos in one place** — New /bnb landing page tells the whole BNB Chain story: gasless agent onboarding (a zero-balance wallet mints an on-chain identity, no faucet), an on-chain-gated 3D vault backed by Greenfield storage permissions, and a real-time on-chain world riding BNB's ~0.45s blocks — each claim traced to what we independently verified live, never BNB's own roadmap promises. The page embeds a live block-time widget that measures the real average off a public RPC on every load, and each feature card auto-detects whether its track has actually shipped on this deployment, showing an honest "coming soon" instead of a dead link until it has. (`/bnb`) `[feature]`+- **Give your agent a 3D body in one call — the new Embodiment endpoint** — Any AI agent can now buy itself a real presence in a single USDC payment: POST a name plus a text description (or a reference photo) to the new Embodiment endpoint and get back a rigged, animated, talking 3D avatar, a durable persona id that reloads in any future session, and a one-tag embed snippet for any website. It's the same free generate-and-rig chain that powers the 3D Studio, packaged as one paid call — no separate rigging step, no account. Generation failures never settle, so a buyer is only ever charged for a finished body. (`/docs/embody`) `[feature]`- **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 free API: check if a wallet holds a Binance Account Bound Token (BABT)** — GET /api/bnb/babt-check?address=0x... tells you whether a BSC address holds a BABT — Binance's non-transferable, KYC-backed on-chain token. It's a real, live signal (1.16M+ holders on BSC mainnet) that developers can use as a free, no-signup uniqueness check for allowlists, anti-sybil gating, or airdrop targeting on BNB Chain. `[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 free crypto API goes deeper: CoinGecko, DefiLlama, and two new DeFi price feeds** — The unified /api/v1/x crypto API grew from 4 to 12 endpoints across CoinGecko and DefiLlama, all free with zero setup. CoinGecko now answers a full per-coin snapshot (price, ATH/ATL, supply, multi-window change), trending coins and hot categories, token price by contract address, the global market snapshot, and OHLC candles — not just spot price and ranked markets. DefiLlama adds every chain ranked by TVL, one protocol's full profile with 30 days of TVL history, and 90 days of historical chain TVL. Two new providers ride DefiLlama's sibling APIs: llama-prices for any chain:address token (covers long-tail tokens CoinGecko and Jupiter don't index) and llama-stablecoins for every tracked stablecoin's peg, price, and circulating supply. (`/docs/api-reference`) `[feature]`- **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-07diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 78f83eea6..e80f782f3 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -64,6 +64,7 @@ bottom.| 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) |+| BNB Chain campaign hub | [pages/bnb.html](pages/bnb.html) + [src/bnb.js](src/bnb.js) `→ /bnb`, pure helpers [src/bnb-hub-helpers.js](src/bnb-hub-helpers.js), live block-time API [api/bnb/block-time.js](api/bnb/block-time.js) over [api/_lib/bnb/chains.js](api/_lib/bnb/chains.js) `probeBlockTime` | In-repo · hub live, tracks rolling out | The campaign's front door: three feature cards (gasless agent onboarding, on-chain-gated 3D vault, real-time on-chain world), each claim traced to `prompts/bnb-chain/00-CONTEXT.md`'s verified facts (0.45s blocks — never 20k TPS or 250ms finality). Embeds a live block-time widget (real RPC measurement on every load). Each card self-detects liveness via a real HTTP probe against its track's route/API on the running deployment — a 404 renders a designed "coming soon" state, never a dead link — so cards auto-light-up as the sibling tracks below ship: gasless registration `→ /create-agent` + `api/bnb/register-agent.js` (prompt 03), vault `→ /vault` (prompt 12), on-chain world `→ /bnb-latency` (prompt 17) + the Explore on-chain toggle (prompt 16). Campaign root: [prompts/bnb-chain/](prompts/bnb-chain) |## npm workspacesdiff --git a/api/_lib/embed-gate-token.js b/api/_lib/embed-gate-token.jsnew file mode 100644index 000000000..16704e9c0--- /dev/null+++ b/api/_lib/embed-gate-token.js@@ -0,0 +1,101 @@+// Short-lived, HMAC-signed access token for a token-gated 3D embed.+//+// Anti-abuse design: a visitor only pays the cost of a real on-chain balance+// read + wallet signature ONCE per TTL window. api/embed/gate-verify.js mints+// this token after a server-verified SPL balance check clears the gate's+// min_amount; api/embed/resolve.js accepts it in place of re-checking the+// chain on every asset fetch, and rejects it once `exp` passes — the widget+// (public/embed/v1.js) then re-runs the verify flow, so a sold-off wallet+// can't keep viewing gated content past the token's lifetime.+//+// Format mirrors api/_lib/forge-job-token.js: `eg1.<base64url(payload)>.<sig>`,+// HMAC-SHA256 over a domain-tagged payload with env.JWT_SECRET — the same+// canonical signing secret used across the platform's other short-lived+// tokens (holder-pass.js, forge-job-token.js). No new secret to provision.++import { hmacSha256, constantTimeEquals } from './crypto.js';+import { env } from './env.js';++// Long enough that a visitor isn't re-signing on every page interaction; short+// enough that a wallet that sells off its holding loses access promptly.+export const EMBED_GATE_TOKEN_TTL_S = 10 * 60;++const PREFIX = 'eg1';+const DOMAIN = 'three.ws-embed-gate-token-v1';++function b64urlEncode(str) {+ return Buffer.from(str, 'utf8').toString('base64url');+}++function b64urlDecode(str) {+ return Buffer.from(str, 'base64url').toString('utf8');+}++/**+ * Seal a verified gate check into a compact, tamper-evident token.+ * @param {{ gateId:string, assetId:string, wallet:string, mint:string, minAmount:number, amount:number }} claims+ * @returns {Promise<string>}+ */+export async function signEmbedGateToken({ gateId, assetId, wallet, mint, minAmount, amount }) {+ const now = Math.floor(Date.now() / 1000);+ const payload = {+ g: gateId,+ a: assetId,+ w: wallet,+ m: mint,+ min: Math.max(0, Number(minAmount) || 0),+ amt: Math.max(0, Number(amount) || 0),+ iat: now,+ exp: now + EMBED_GATE_TOKEN_TTL_S,+ };+ const body = b64urlEncode(JSON.stringify(payload));+ const sig = await hmacSha256(env.JWT_SECRET, `${DOMAIN}:${body}`);+ return `${PREFIX}.${body}.${sig}`;+}++/**+ * Verify a token's signature and expiry. Optionally pin it to the exact+ * gate/asset it must have been issued for — resolve.js and gate-verify.js+ * both pass `assetId` and `gateId` so a token from a superseded gate (the+ * creator changed the requirement) never verifies against the new one.+ * @returns {Promise<{gateId,assetId,wallet,mint,minAmount,amount,iat,exp}|null>}+ */+export async function verifyEmbedGateToken(token, { assetId, gateId } = {}) {+ if (typeof token !== 'string' || !token.startsWith(`${PREFIX}.`)) return null;+ const parts = token.split('.');+ if (parts.length !== 3) return null;+ const [, body, sig] = parts;+ if (!body || !sig) return null;++ let expected;+ try {+ expected = await hmacSha256(env.JWT_SECRET, `${DOMAIN}:${body}`);+ } catch {+ return null;+ }+ if (!constantTimeEquals(expected, sig)) return null;++ let payload;+ try {+ payload = JSON.parse(b64urlDecode(body));+ } catch {+ return null;+ }+ if (!payload || typeof payload !== 'object') return null;++ const now = Math.floor(Date.now() / 1000);+ if (!Number.isFinite(payload.exp) || payload.exp < now) return null;+ if (assetId && payload.a !== assetId) return null;+ if (gateId && payload.g !== gateId) return null;++ return {+ gateId: payload.g,+ assetId: payload.a,+ wallet: payload.w,+ mint: payload.m,+ minAmount: Number(payload.min) || 0,+ amount: Number(payload.amt) || 0,+ iat: payload.iat,+ exp: payload.exp,+ };+}diff --git a/api/_lib/embed-gate.js b/api/_lib/embed-gate.jsnew file mode 100644index 000000000..a05bf3c47--- /dev/null+++ b/api/_lib/embed-gate.js@@ -0,0 +1,201 @@+// Token-gated 3D embeds — gate config storage, ownership checks, and the+// server-side SPL balance read. This is the "token-gate verifier" the comment+// atop embed-asset.js and api/embed/resolve.js promises: an embed asset+// (avatar or on-chain agent) can carry a gate row here, and resolve.js only+// hands back the real glbUrl once the caller proves — with a real Solana RPC+// read, never a client-reported number — they hold at least `min_amount` of+// `mint`.+//+// Canonical use: $THREE-holder-only avatars and rooms. `mint` is a runtime+// parameter (the coin-agnostic plumbing exception in CLAUDE.md) so any+// community can gate with their own SPL token — three.ws never hardcodes,+// markets, or recommends a mint other than $THREE as the default.+//+// Split from api/embed/gate-create.js and api/embed/gate-verify.js so the+// create_gated_embed MCP tool (api/_mcp/tools/embed.js) and the REST endpoints+// share one implementation instead of drifting.++import { sql } from './db.js';+import { solanaRpcEndpoints } from './solana/connection.js';+import { ONCHAIN_RE, AVATAR_RE } from './embed-asset.js';+import { randomToken } from './crypto.js';++// The only coin three.ws promotes or ships as a default/example. Matches+// src/pump/three-token-data.js and src/three-gate.js.+export const DEFAULT_GATE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// Guard rails on a creator-set threshold — same ceiling world-gate.js uses for+// the same reason: bound a fat-fingered or hostile value to something a real+// SPL supply could plausibly hold.+const MAX_MIN_AMOUNT = 1e15;++/** Clamp an arbitrary input to a valid token threshold, or 0 when invalid. */+export function normalizeMinAmount(v) {+ const n = Number(v);+ if (!Number.isFinite(n) || n <= 0) return 0;+ return Math.min(n, MAX_MIN_AMOUNT);+}++/** A trimmed mint string, or the $THREE default when none was supplied. */+export function normalizeMint(v) {+ const s = String(v ?? '').trim();+ return s || DEFAULT_GATE_MINT;+}++/** True when `balance` clears `minAmount` — the one comparison every caller must agree on. */+export function meetsGateThreshold(balance, minAmount) {+ return Number(balance) >= Number(minAmount);+}++/**+ * The active (non-revoked) gate for an embed asset, or null when the asset is+ * ungated. Both resolve.js (deciding whether to require a token) and+ * gate-verify.js (deciding what to check against) call this.+ */+export async function readEmbedGateByAsset(assetId) {+ const id = String(assetId || '').trim();+ if (!id) return null;+ const rows = await sql`+ select id, asset_id, owner_user_id, chain, mint, min_amount, created_at+ from embed_gates+ where asset_id = ${id} and revoked_at is null+ limit 1+ `;+ return rows[0] || null;+}++/** Read a gate by its own id (used to confirm a nonce/token still points at a live gate). */+export async function readEmbedGate(gateId) {+ const id = String(gateId || '').trim();+ if (!id) return null;+ const rows = await sql`+ select id, asset_id, owner_user_id, chain, mint, min_amount, created_at+ from embed_gates+ where id = ${id} and revoked_at is null+ limit 1+ `;+ return rows[0] || null;+}++/**+ * Create (or replace) the gate on an embed asset. Revokes any existing active+ * gate on the same asset first — a creator raising/lowering the requirement+ * gets a clean row, and every access token minted against the old gate id+ * stops verifying immediately (gate-verify.js checks the token's gateId is+ * still the asset's current gate).+ */+export async function createEmbedGate({ assetId, ownerUserId, mint, minAmount, chain = 'solana' }) {+ if (chain !== 'solana') {+ throw Object.assign(new Error('only solana SPL-token gating is supported'), { status: 400 });+ }+ const amount = normalizeMinAmount(minAmount);+ if (amount <= 0) {+ throw Object.assign(new Error('minAmount must be a positive number'), { status: 400 });+ }+ const resolvedMint = normalizeMint(mint);++ let gateId = '';+ while (gateId.length < 12) gateId += randomToken(16).replace(/[^A-Za-z0-9]/g, '');+ gateId = gateId.slice(0, 12);++ await sql`update embed_gates set revoked_at = now(), updated_at = now() where asset_id = ${assetId} and revoked_at is null`;+ await sql`+ insert into embed_gates (id, asset_id, owner_user_id, chain, mint, min_amount)+ values (${gateId}, ${assetId}, ${ownerUserId}, ${chain}, ${resolvedMint}, ${amount})+ `;++ return { gateId, assetId, ownerUserId, chain, mint: resolvedMint, minAmount: amount };+}++/**+ * Does `userId` own the underlying asset well enough to gate it?+ * - avatar:<uuid> → avatars.owner_id === userId+ * - <chainId>:<agentId> → the on-chain agent's `owner` (0x address) matches+ * one of the user's linked EVM wallets+ * Returns { ok:true } or { ok:false, reason: 'not_found' | 'not_owner' | 'invalid_asset' }.+ */+export async function checkAssetOwnership(assetId, userId) {+ const spec = String(assetId || '').trim();++ const onchain = spec.match(ONCHAIN_RE);+ if (onchain) {+ const chainId = parseInt(onchain[1], 10);+ const agentId = parseInt(onchain[2], 10);+ const rows = await sql`+ select owner from erc8004_agents_index+ where active = true and chain_id = ${chainId} and agent_id = ${agentId}+ limit 1+ `;+ if (!rows.length) return { ok: false, reason: 'not_found' };+ const owner = String(rows[0].owner || '').toLowerCase();+ const linked = await sql`+ select 1 from user_wallets+ where user_id = ${userId} and chain_type = 'evm' and lower(address) = ${owner}+ limit 1+ `;+ return linked.length ? { ok: true } : { ok: false, reason: 'not_owner' };+ }++ const avatar = spec.match(AVATAR_RE);+ if (avatar) {+ const rows = await sql`+ select owner_id from avatars where id = ${avatar[1]} and deleted_at is null limit 1+ `;+ if (!rows.length) return { ok: false, reason: 'not_found' };+ return rows[0].owner_id === userId ? { ok: true } : { ok: false, reason: 'not_owner' };+ }++ return { ok: false, reason: 'invalid_asset' };+}++// ── On-chain SPL balance read ────────────────────────────────────────────────++// Solana RPC calls are cheap reads but not free — bound how many endpoints a+// single balance check will try before giving up, so a fully-down provider+// chain fails in a few seconds instead of hanging on 8+ endpoints.+const MAX_ENDPOINTS_TRIED = 4;+const RPC_TIMEOUT_MS = 8000;++/**+ * Real, server-side SPL token balance for `walletAddress` in `mint` — never+ * trust a client-reported number. Rotates across the same priority-ordered+ * endpoint list solanaConnection() uses (Helius → Alchemy → dRPC → keyless+ * public fallbacks) so a single provider outage doesn't fail the gate.+ * @returns {Promise<number>} the uiAmount balance (0 when the wallet holds none)+ */+export async function getSplTokenBalance(walletAddress, mint) {+ const endpoints = solanaRpcEndpoints('mainnet').slice(0, MAX_ENDPOINTS_TRIED);+ let lastErr = null;+ for (const url of endpoints) {+ try {+ const resp = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ signal: AbortSignal.timeout(RPC_TIMEOUT_MS),+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'getTokenAccountsByOwner',+ params: [walletAddress, { mint }, { encoding: 'jsonParsed' }],+ }),+ });+ if (!resp.ok) {+ lastErr = new Error(`solana rpc ${resp.status}`);+ continue;+ }+ const data = await resp.json();+ if (data.error) {+ lastErr = new Error(data.error.message || JSON.stringify(data.error));+ continue;+ }+ const accounts = data.result?.value || [];+ return accounts.reduce(+ (sum, a) => sum + (a.account?.data?.parsed?.info?.tokenAmount?.uiAmount || 0),+ 0,+ );+ } catch (err) {+ lastErr = err;+ }+ }+ throw lastErr || new Error('all solana rpc endpoints failed');+}diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 9ed77de44..780d33909 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -401,6 +401,18 @@ export const env = {return opt('VANITY_SERVICE_KEY');},+ // Master seed for deterministic persona↔wallet derivation+ // (api/_lib/persona-wallet.js): the same persona_id always re-derives the same+ // Solana keypair via HMAC-SHA256(secret, persona_id), so no private key is ever+ // stored — it exists only transiently in memory while signing, then is+ // discarded. Dedicated by preference; falls back to WALLET_ENCRYPTION_KEY then+ // JWT_SECRET so the feature works in dev/CI without extra config. Production+ // should set a distinct value: rotating it re-derives every persona to a NEW+ // wallet, so treat it as append-only once personas hold real funds.+ get PERSONA_WALLET_SECRET() {+ return opt('PERSONA_WALLET_SECRET') || opt('WALLET_ENCRYPTION_KEY') || this.JWT_SECRET;+ },+// ── Agent-to-agent (A2A) autonomous payments ────────────────────────────// Secret that signs Intent Mandates (AP2-style budgeted spend authorizations).// Dedicated by preference; falls back to JWT_SECRET so the feature works indiff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex ecfcbc21a..2542a3661 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -227,9 +227,18 @@ function imageExtFor(url) {// Copy a finished generation into durable storage and flip the row to 'done'.// Copies the mesh (required) and the reference image (best-effort). Returns the-// durable { id, glbUrl, previewImageUrl } or null on any failure so the caller-// can fall back to the provider URL.-export async function materializeCreation({ replicateJobId, clientKey, glbUrl }) {+// durable { id, glbUrl, previewImageUrl, quality, compression } or null on any+// failure so the caller can fall back to the provider URL.+//+// Two additive, opt-in params:+// quality — when true, scores the mesh (glb-quality.js) and returns the+// signal in `quality`. Off by default so an existing caller's+// response shape and latency are unaffected.+// compress — 'draco' | 'meshopt' to deliver a geometry-compressed variant+// (glb-compress.js) instead of the raw provider bytes. Falls back+// to uncompressed on any compression failure — never blocks+// delivery. Omitted/null preserves today's uncompressed behavior.+export async function materializeCreation({ replicateJobId, clientKey, glbUrl, quality = false, compress = null }) {if (!forgeStoreEnabled() || !replicateJobId || !glbUrl) return null;const existing = await findByJob({ replicateJobId, clientKey });if (!existing) return null;@@ -239,6 +248,8 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl })id: existing.id,glbUrl: existing.glb_url,previewImageUrl: existing.preview_image_url ?? null,+ quality: null,+ compression: null,};}@@ -249,6 +260,8 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl })key: `${keyPrefix}.glb`,fallbackContentType: 'model/gltf-binary',maxBytes: MAX_GLB_BYTES,+ computeQuality: quality,+ compress,});// Reference image is part of the training pair but never blocks the mesh.@@ -293,7 +306,13 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl })latencyMs,source: 'materialize',});- return { id: existing.id, glbUrl: glb.publicUrl, previewImageUrl: preview.url };+ return {+ id: existing.id,+ glbUrl: glb.publicUrl,+ previewImageUrl: preview.url,+ quality: glb.quality ?? null,+ compression: glb.compression ?? null,+ };} catch (err) {// A 404/410 means the provider's ephemeral asset (e.g. a HuggingFace Space's// gradio /tmp mesh) expired before we could copy it — expected and fullydiff --git a/api/_lib/migrations/20260708120000_embed_gates.sql b/api/_lib/migrations/20260708120000_embed_gates.sqlnew file mode 100644index 000000000..9e35b8d09--- /dev/null+++ b/api/_lib/migrations/20260708120000_embed_gates.sql@@ -0,0 +1,50 @@+-- Migration: token-gated 3D embeds — server-verified on-chain SPL-token-balance+-- gating for interactive <three-d> embeds (see api/_lib/embed-gate.js,+-- api/embed/gate-create.js, api/embed/gate-verify.js, api/embed/resolve.js).+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260708120000_embed_gates.sql+-- Idempotent.+--+-- One row per active gate, keyed by the SAME embed asset ref the resolver in+-- api/_lib/embed-asset.js already understands ("avatar:<uuid>" or+-- "<chainId>:<agentId>"). At most one active (non-revoked) gate per asset — a+-- creator changing the requirement revokes the old row and inserts a new one,+-- which also invalidates every access token minted against the old gate id.+--+-- embed_gate_nonces mirrors gate_nonces (scene_gates' nonce table) but scoped+-- to embed_gates so the two gating systems (chat scenes vs. embeds) never share+-- state, even though the verification flow (SIWS challenge → nonce → signature+-- → on-chain balance) is the same shape.++begin;++create table if not exists embed_gates (+ id text primary key, -- short opaque gate id+ asset_id text not null, -- "avatar:<uuid>" | "<chainId>:<agentId>"+ owner_user_id uuid references users(id) on delete set null,+ chain text not null default 'solana' check (chain in ('solana')),+ mint text not null, -- SPL mint; defaults to $THREE at the call site+ min_amount numeric not null check (min_amount > 0),+ revoked_at timestamptz,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- At most one active gate per asset — resolve.js and gate-verify.js both look+-- this up by asset_id alone and need a deterministic single row.+create unique index if not exists embed_gates_asset_active_uniq+ on embed_gates(asset_id) where revoked_at is null;++create index if not exists embed_gates_owner on embed_gates(owner_user_id);++create table if not exists embed_gate_nonces (+ nonce text primary key,+ gate_id text not null references embed_gates(id) on delete cascade,+ address text not null,+ expires_at timestamptz not null,+ consumed_at timestamptz+);++create index if not exists embed_gate_nonces_expiry on embed_gate_nonces(expires_at);+create index if not exists embed_gate_nonces_gate_id on embed_gate_nonces(gate_id);++commit;diff --git a/api/_lib/persona-spend-ledger.js b/api/_lib/persona-spend-ledger.jsnew file mode 100644index 000000000..edf1488a8--- /dev/null+++ b/api/_lib/persona-spend-ledger.js@@ -0,0 +1,183 @@+/**+ * Persona wallet spend ledger — the durable record `persona_tip` / `persona_send`+ * check BEFORE moving any USDC, so the per-call and per-session caps are real+ * limits and not just numbers in a description.+ *+ * Mirrors the storage tiering already established by persona-store.js: a+ * Postgres table in production, a JSON-on-disk fallback for local/dev/test so+ * "the cap actually blocks a second call in the same session" is provable+ * without a live database. Same shape either way.+ *+ * A "session" is caller-scoped (the `session_id` a client passes), not a+ * three.ws account — persona wallets are addressable by id alone, so the spend+ * cap follows the same no-account posture as the persona itself. Callers that+ * omit session_id are bucketed by persona_id + UTC calendar day, which still+ * bounds a runaway/looped caller even with no session id supplied.+ */++import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { sql } from './db.js';+import { databaseConfigured } from './env.js';++const dbConfigured = () => databaseConfigured();++function envNumber(key, fallback) {+ const raw = process.env[key];+ if (raw === undefined || String(raw).trim() === '') return fallback;+ const n = Number(raw);+ return Number.isFinite(n) && n >= 0 ? n : fallback;+}++// ── guardrail configuration (env-tunable, conservative defaults) ─────────────+export const PERSONA_SPEND_CAPS = Object.freeze({+ // Hard ceiling on a SINGLE persona_tip/persona_send call.+ maxPerCallUsdc: envNumber('PERSONA_MAX_TIP_USDC', 1),+ // Cumulative ceiling across every call sharing one session_id (or the daily+ // fallback bucket for callers that don't pass one).+ maxPerSessionUsdc: envNumber('PERSONA_MAX_SESSION_USDC', 5),+ // Above this amount, the tool call must carry confirm:true — the same+ // confirmation-gate shape used by the SOL wallet_send tool.+ confirmAboveUsdc: envNumber('PERSONA_CONFIRM_ABOVE_USDC', 0.25),+});++export function utcDateBucket(d = new Date()) {+ return d.toISOString().slice(0, 10); // YYYY-MM-DD+}++/** Deterministic fallback session key for callers that omit session_id. */+export function defaultSessionId(personaId) {+ return `${personaId}:${utcDateBucket()}`;+}++// ── Postgres backend ──────────────────────────────────────────────────────────++let _schemaReady = null;+async function ensureSchema() {+ if (_schemaReady) return _schemaReady;+ _schemaReady = sql`+ create table if not exists persona_wallet_spend_events (+ id bigserial primary key,+ persona_id text not null,+ session_id text not null,+ usdc numeric not null,+ tool text not null,+ to_address text,+ signature text,+ created_at timestamptz not null default now()+ )+ `.then(() => sql`+ create index if not exists persona_wallet_spend_events_session_idx+ on persona_wallet_spend_events (persona_id, session_id)+ `).then(() => true);+ return _schemaReady;+}++async function dbSessionTotal(personaId, sessionId) {+ await ensureSchema();+ const [row] = await sql`+ select coalesce(sum(usdc), 0)::float8 as total+ from persona_wallet_spend_events+ where persona_id = ${personaId} and session_id = ${sessionId}+ `;+ return Number(row?.total || 0);+}++async function dbRecordSpend({ personaId, sessionId, usdc, tool, toAddress, signature }) {+ await ensureSchema();+ await sql`+ insert into persona_wallet_spend_events (persona_id, session_id, usdc, tool, to_address, signature)+ values (${personaId}, ${sessionId}, ${usdc}, ${tool}, ${toAddress || null}, ${signature || null})+ `;+}++// ── filesystem backend (local/dev/test fallback) ──────────────────────────────++function storeDir() {+ return process.env.PERSONA_SPEND_STORE_DIR || path.join(process.cwd(), '.data', 'persona-spend');+}+async function fsDir() {+ const dir = storeDir();+ try {+ await fs.mkdir(dir, { recursive: true });+ return dir;+ } catch {+ const tmp = path.join(os.tmpdir(), 'threews-persona-spend');+ await fs.mkdir(tmp, { recursive: true });+ return tmp;+ }+}+function fsKey(personaId, sessionId) {+ // Both ids are already constrained (persona_id regex, session_id clamped+ // below), but slice+strip defensively before it touches a filename.+ const safe = (s) => String(s).replace(/[^A-Za-z0-9_.:-]/g, '_').slice(0, 120);+ return `${safe(personaId)}__${safe(sessionId)}.json`;+}+async function fsFile(personaId, sessionId) {+ return path.join(await fsDir(), fsKey(personaId, sessionId));+}++async function fsSessionEvents(personaId, sessionId) {+ try {+ const raw = await fs.readFile(await fsFile(personaId, sessionId), 'utf8');+ const parsed = JSON.parse(raw);+ return Array.isArray(parsed) ? parsed : [];+ } catch {+ return [];+ }+}++async function fsRecordSpend({ personaId, sessionId, usdc, tool, toAddress, signature }) {+ const events = await fsSessionEvents(personaId, sessionId);+ events.push({ usdc, tool, to_address: toAddress || null, signature: signature || null, created_at: new Date().toISOString() });+ await fs.writeFile(await fsFile(personaId, sessionId), JSON.stringify(events, null, 2), 'utf8');+}++// ── public API ────────────────────────────────────────────────────────────────++/** Sum of USDC already spent in this persona+session, real data either backend. */+export async function sessionSpentUsdc(personaId, sessionId) {+ if (dbConfigured()) return dbSessionTotal(personaId, sessionId);+ const events = await fsSessionEvents(personaId, sessionId);+ return events.reduce((sum, e) => sum + Number(e.usdc || 0), 0);+}++/**+ * Check every guardrail BEFORE a transfer is signed. Returns+ * `{ ok: true }` when the call may proceed, or `{ ok: false, code, message, ... }`+ * describing exactly which cap blocked it — never throws, so a handler can+ * return the refusal directly as a designed result.+ */+export async function checkPersonaSpend({ personaId, sessionId, usdc }) {+ const amount = Number(usdc);+ if (!(amount > 0)) {+ return { ok: false, code: 'invalid_amount', message: 'Amount must be a positive number of USDC.' };+ }+ if (amount > PERSONA_SPEND_CAPS.maxPerCallUsdc) {+ return {+ ok: false,+ code: 'over_call_cap',+ message: `$${amount} exceeds the per-call cap of $${PERSONA_SPEND_CAPS.maxPerCallUsdc} USDC.`,+ cap_usdc: PERSONA_SPEND_CAPS.maxPerCallUsdc,+ };+ }+ const spent = await sessionSpentUsdc(personaId, sessionId);+ if (spent + amount > PERSONA_SPEND_CAPS.maxPerSessionUsdc) {+ return {+ ok: false,+ code: 'over_session_cap',+ message: `This session has already spent $${spent.toFixed(4)} of its $${PERSONA_SPEND_CAPS.maxPerSessionUsdc} USDC cap — $${amount} would exceed it.`,+ cap_usdc: PERSONA_SPEND_CAPS.maxPerSessionUsdc,+ spent_usdc: spent,+ };+ }+ return { ok: true, spent_usdc: spent, remaining_usdc: PERSONA_SPEND_CAPS.maxPerSessionUsdc - spent - amount };+}++/** Record a SETTLED spend (call only after the on-chain transfer confirms). */+export async function recordPersonaSpend({ personaId, sessionId, usdc, tool, toAddress, signature }) {+ const row = { personaId, sessionId, usdc: Number(usdc), tool, toAddress, signature };+ if (dbConfigured()) return dbRecordSpend(row);+ return fsRecordSpend(row);+}diff --git a/api/_lib/persona-wallet.js b/api/_lib/persona-wallet.jsnew file mode 100644index 000000000..ea58734ef--- /dev/null+++ b/api/_lib/persona-wallet.js@@ -0,0 +1,325 @@+/**+ * Persona↔wallet binding — every embodied persona (api/_lib/persona-store.js)+ * carries a real, deterministic Solana wallet and an on-chain identity: balance,+ * ERC-8004-style reputation, token holdings, and a resolved SNS nameplate. The+ * SAME persona_id always re-derives the SAME wallet, on any instance, forever —+ * with NO private key ever stored anywhere and NO private key ever appearing in+ * a tool response, a log line, or an error message.+ *+ * ── Deterministic derivation (the binding scheme) ────────────────────────────+ * seed = HMAC-SHA256(PERSONA_WALLET_SECRET, "three.ws:persona-wallet:v1:" + personaId)+ * keypair = Ed25519 Keypair.fromSeed(seed) // Solana's Keypair.fromSeed takes+ * // exactly a 32-byte seed — SHA-256's+ * // digest length, no truncation needed.+ *+ * This is a stateless HD-wallet-style derivation, not a stored secret: recovery+ * needs only the persona_id (public) and the server's PERSONA_WALLET_SECRET+ * (never leaves the server). Nothing is written to disk or a database to make a+ * persona wallet "exist" — `personaWalletAddress` is a pure function of its+ * input. The keypair object itself is constructed on demand, used for exactly+ * one signature, and immediately falls out of scope — this module never returns+ * it, logs it, or stores it on any object that escapes the function that made it.+ *+ * ── Domain separation ────────────────────────────────────────────────────────+ * The HMAC "info" string embeds a fixed namespace + version, so this derivation+ * can never collide with any other HMAC/derivation elsewhere in the codebase+ * even if PERSONA_WALLET_SECRET happens to equal another module's secret (e.g.+ * the WALLET_ENCRYPTION_KEY fallback in dev).+ */++import { createHmac } from 'node:crypto';+import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync, createTransferCheckedInstruction,+ createAssociatedTokenAccountIdempotentInstruction, TOKEN_PROGRAM_ID,+} from '@solana/spl-token';++import { env } from './env.js';+import { solanaConnection } from './agent-pumpfun.js';+import { submitProtected } from './execution-engine.js';+import { USDC_MINT_BY_NETWORK, USDC_DECIMALS } from './vault-jupiter.js';+import { valuateHoldings } from './portfolio.js';+import { solUsdPrice, explorerAccountUrl, explorerTxUrl } from './avatar-wallet.js';+import { solanaReputation } from '../_mcp/tools/solana.js';+import { checkPersonaSpend, recordPersonaSpend, defaultSessionId, PERSONA_SPEND_CAPS } from './persona-spend-ledger.js';++const HMAC_DOMAIN = 'three.ws:persona-wallet:v1:';+const SNS_API = 'https://sns-api.bonfida.com';++function netOf(network) {+ return network === 'devnet' ? 'devnet' : 'mainnet';+}++/**+ * Derive the persona's 32-byte Ed25519 seed. Never exported — the seed is as+ * sensitive as the private key it produces (Keypair.fromSeed is deterministic),+ * so it stays fully inside this module's private call graph.+ */+function derivePersonaSeed(personaId) {+ const secret = env.PERSONA_WALLET_SECRET;+ if (!secret) {+ throw Object.assign(new Error('persona wallets are not configured (PERSONA_WALLET_SECRET/WALLET_ENCRYPTION_KEY/JWT_SECRET unset)'), {+ code: 'no_persona_wallet_secret',+ });+ }+ return createHmac('sha256', secret).update(HMAC_DOMAIN + personaId).digest();+}++/**+ * Construct the persona's keypair, hand it to `fn`, then let it be+ * garbage-collected. `fn` MUST NOT return the Keypair, its secretKey, or any+ * derivative of the secret bytes — only `fn`'s own return value escapes this+ * function. This is the ONLY place a persona's signing key is ever constructed.+ */+async function withPersonaKeypair(personaId, fn) {+ const seed = derivePersonaSeed(personaId);+ const keypair = Keypair.fromSeed(seed);+ return fn(keypair);+}++/** The persona's Solana address — deterministic, public, safe to log/return. */+export function personaWalletAddress(personaId) {+ const seed = derivePersonaSeed(personaId);+ // Ed25519 public key derivation from a seed touches no secret material beyond+ // what Keypair.fromSeed already computes; .publicKey is safe to expose.+ return Keypair.fromSeed(seed).publicKey.toBase58();+}++// ── on-chain reads ────────────────────────────────────────────────────────────++/** Native SOL + USDC balance for a persona's address. Never throws. */+export async function getPersonaBalances(address, network = 'mainnet') {+ const net = netOf(network);+ const conn = solanaConnection(net);+ const pk = new PublicKey(address);+ let sol = 0;+ try {+ sol = (await conn.getBalance(pk, 'confirmed')) / LAMPORTS_PER_SOL;+ } catch { /* RPC hiccup — report 0, never fabricate */ }++ let usdc = 0;+ try {+ const mint = new PublicKey(USDC_MINT_BY_NETWORK[net]);+ const ata = getAssociatedTokenAddressSync(mint, pk, false, TOKEN_PROGRAM_ID);+ const info = await conn.getTokenAccountBalance(ata, 'confirmed').catch(() => null);+ usdc = info?.value?.uiAmount || 0;+ } catch { /* no ATA yet, or RPC hiccup — 0 is honest */ }++ let solUsd = null;+ try { solUsd = await solUsdPrice(); } catch { solUsd = null; }++ return {+ sol, usdc,+ sol_usd: solUsd != null ? Number((sol * solUsd).toFixed(4)) : null,+ total_usd: solUsd != null ? Number((sol * solUsd + usdc).toFixed(4)) : null,+ };+}++/**+ * ERC-8004-style reputation, reusing the SAME computed-summary path the paid+ * `solana_agent_reputation` tool exposes (api/_mcp/tools/solana.js), keyed by+ * the persona's own wallet address as its attestation identity. A freshly+ * derived persona wallet legitimately has zero attestations until someone+ * memos one to it — that is real data, not an error.+ */+export async function getPersonaReputation(address, network = 'mainnet') {+ try {+ return await solanaReputation(address, netOf(network));+ } catch {+ // No database configured (local/dev) or an RPC hiccup — degrade to the+ // same honest zero-state shape the live path would report for a fresh+ // wallet, rather than surfacing an internal error to a chat turn.+ return {+ agent: address, network: netOf(network),+ feedback: { total: 0, verified: 0, disputed: 0, score_avg: 0, score_avg_verified: 0 },+ validation: { passed: 0, failed: 0 },+ degraded: true,+ };+ }+}++/** Live holdings (SOL + every priced SPL token) for a persona's address. */+export async function getPersonaHoldings(address, network = 'mainnet') {+ try {+ const { holdings, solUsd } = await valuateHoldings({ network: netOf(network), address });+ const priced = holdings.filter((h) => h.usd != null);+ const totalUsd = priced.reduce((sum, h) => sum + h.usd, 0);+ return {+ count: holdings.length,+ total_usd: Number(totalUsd.toFixed(4)),+ sol_usd_price: solUsd,+ top: [...holdings].sort((a, b) => (b.usd ?? -1) - (a.usd ?? -1)).slice(0, 5).map((h) => ({+ symbol: h.symbol || null, mint: h.mint || null, amount: h.amount, usd: h.usd ?? null,+ })),+ degraded: false,+ };+ } catch {+ return { count: 0, total_usd: 0, sol_usd_price: null, top: [], degraded: true };+ }+}++/**+ * A verified SNS (Solana Name Service) nameplate for the persona's address,+ * reusing the same Bonfida source `ens_sns_resolve` reads from — in reverse:+ * given the address, does it hold a favourite .sol domain? ENS reverse lookup+ * does not apply here (persona wallets are Solana addresses, not 0x EVM+ * addresses); when a persona's wallet is bridged to an EVM identity in the+ * future, the same ens_sns_resolve forward path already covers .eth names.+ * Best-effort — a Bonfida outage degrades to `{ name: null, verified: false }`,+ * never an error.+ */+export async function getPersonaNameplate(address) {+ try {+ const r = await fetch(`${SNS_API}/v2/user/fav-domains/${address}`);+ if (r.ok) {+ const body = await r.json();+ const fav = body?.[address] || body?.data?.[address] || null;+ const name = typeof fav === 'string' ? fav : fav?.domain || fav?.name || null;+ if (name) return { name: name.endsWith('.sol') ? name : `${name}.sol`, verified: true, source: 'sns' };+ }+ } catch { /* best effort */ }+ return { name: null, verified: false, source: 'sns' };+}++// ── pure visual-tier mappings (network-free, unit-testable) ──────────────────++/** Reputation → a discrete trust tier the viewer maps to an aura. */+export function reputationTierFor(reputation) {+ const fb = reputation?.feedback || {};+ const verified = Number(fb.verified || 0);+ const avg = Number(fb.score_avg_verified || 0);+ const disputed = Number(fb.disputed || 0);+ if (disputed > 0 && disputed >= verified) return 'disputed';+ if (verified >= 15 && avg >= 4.5) return 'eminent';+ if (verified >= 3 && avg >= 4) return 'trusted';+ if (Number(fb.total || 0) > 0) return 'emerging';+ return 'unranked';+}++/** Live USD holdings total → a discrete cosmetic tier. */+export function holdingsTierFor(totalUsd) {+ const usd = Number(totalUsd || 0);+ if (usd >= 1000) return 'platinum';+ if (usd >= 100) return 'gold';+ if (usd >= 10) return 'silver';+ if (usd > 0) return 'bronze';+ return 'none';+}++/** Balance floor under which the body renders in a designed "muted" state. */+export const MUTED_BALANCE_USD_FLOOR = Number(process.env.PERSONA_MUTED_USD_FLOOR || 0.05);+export function isMutedBalance(balances) {+ const total = balances?.total_usd;+ if (total == null) return balances?.sol === 0 && balances?.usdc === 0;+ return total < MUTED_BALANCE_USD_FLOOR;+}++// ── the composed identity read ────────────────────────────────────────────────++/**+ * `persona_identity` — the full read: address, live balances, reputation,+ * holdings, nameplate, plus the derived visual tiers the viewer consumes+ * directly. Every sub-read degrades independently (never throws), so a single+ * flaky upstream (Bonfida, an RPC, the attestation index) never blanks the+ * whole card — each field reports its own honest fallback.+ */+export async function getPersonaIdentity(personaId, { network = 'mainnet' } = {}) {+ const address = personaWalletAddress(personaId);+ const net = netOf(network);+ const [balances, reputation, holdings, nameplate] = await Promise.all([+ getPersonaBalances(address, net),+ getPersonaReputation(address, net),+ getPersonaHoldings(address, net),+ getPersonaNameplate(address),+ ]);++ return {+ persona_id: personaId,+ address,+ network: net,+ explorer: explorerAccountUrl(address, net),+ balances,+ reputation,+ holdings,+ nameplate,+ visual: {+ reputation_tier: reputationTierFor(reputation),+ holdings_tier: holdingsTierFor(holdings.total_usd),+ muted: isMutedBalance(balances),+ verified_name: nameplate.verified ? nameplate.name : null,+ },+ caps: PERSONA_SPEND_CAPS,+ fetched_at: new Date().toISOString(),+ };+}++// ── guarded value ops (persona_tip / persona_send) ────────────────────────────++/**+ * Send USDC from a persona's own wallet to a destination address — the shared+ * implementation behind `persona_tip` and `persona_send`. Fully guarded:+ * 1. checkPersonaSpend() enforces the per-call AND per-session USDC caps+ * BEFORE any key is touched — a breach never gets near a signature.+ * 2. Real settlement rides the SAME MEV-aware execution engine+ * (submitProtected) every other outbound transfer on the platform uses.+ * 3. recordPersonaSpend() durably logs the settled amount so the session cap+ * is enforceable across process restarts / instances.+ * Returns a structured result; only ever throws on a caller error (bad address)+ * BEFORE any spend is reserved.+ */+export async function sendPersonaUsdc({ personaId, sessionId, to, usdc, tool = 'persona_send', network = 'mainnet', memo }) {+ const net = netOf(network);+ const amount = Number(usdc);+ const session = sessionId || defaultSessionId(personaId);++ let toPk;+ try { toPk = new PublicKey(to); } catch {+ return { status: 'failed', code: 'bad_address', message: 'That does not look like a valid Solana address.' };+ }+ const fromAddress = personaWalletAddress(personaId);+ if (toPk.toBase58() === fromAddress) {+ return { status: 'failed', code: 'self_payment', message: 'A persona cannot tip itself.' };+ }++ const gate = await checkPersonaSpend({ personaId, sessionId: session, usdc: amount });+ if (!gate.ok) return { status: 'blocked', ...gate };++ const conn = solanaConnection(net);+ const mintPk = new PublicKey(USDC_MINT_BY_NETWORK[net]);+ const raw = BigInt(Math.max(0, Math.round(amount * 10 ** USDC_DECIMALS)));++ let signature;+ try {+ signature = await withPersonaKeypair(personaId, async (keypair) => {+ const fromAta = getAssociatedTokenAddressSync(mintPk, keypair.publicKey, false, TOKEN_PROGRAM_ID);+ const toAta = getAssociatedTokenAddressSync(mintPk, toPk, false, TOKEN_PROGRAM_ID);+ const instructions = [+ createAssociatedTokenAccountIdempotentInstruction(keypair.publicKey, toAta, toPk, mintPk, TOKEN_PROGRAM_ID),+ createTransferCheckedInstruction(fromAta, mintPk, toAta, keypair.publicKey, raw, USDC_DECIMALS, [], TOKEN_PROGRAM_ID),+ ];+ const result = await submitProtected({+ network: net, connection: conn, payer: keypair, instructions,+ opts: { tipMode: 'off', confirmTimeoutMs: 45_000 },+ });+ return result.signature;+ });+ } catch (e) {+ return { status: 'failed', code: e?.code || 'send_failed', message: (e?.message || 'the transfer did not settle').slice(0, 200) };+ }++ await recordPersonaSpend({ personaId, sessionId: session, usdc: amount, tool, toAddress: toPk.toBase58(), signature }).catch(() => {});++ return {+ status: 'ok',+ signature,+ explorer: explorerTxUrl(signature, net),+ from: fromAddress,+ to: toPk.toBase58(),+ usdc: amount,+ network: net,+ session_id: session,+ session_spent_usdc: Number((gate.spent_usdc + amount).toFixed(6)),+ session_cap_usdc: PERSONA_SPEND_CAPS.maxPerSessionUsdc,+ memo: memo || null,+ };+}diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex a76652cd3..209e0d799 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -613,6 +613,17 @@ export const limits = {// IPs. recall() embeds one query at a time, so a generous per-minute// ceiling still leaves headroom for interactive memory search.embedUser: (userId) => getLimiter('embed:user', { limit: 120, window: '1 m' }).limit(userId),+ // Token-gated 3D embeds (api/embed/gate-create.js, api/embed/gate-verify.js).+ // Create is an authenticated, low-frequency creator action — bound to stop a+ // compromised session from spraying gates. Verify is called by anonymous+ // visitors and drives a real Solana RPC read + signature check per attempt,+ // so it gets both a per-IP flood guard AND a per-wallet ceiling (the wallet+ // bucket is the one that actually matters — a distributed-IP attacker still+ // can't brute-force past a single wallet's budget without also owning it).+ embedGateCreateIp: (ip) => getLimiter('embed:gate:create:ip', { limit: 20, window: '10 m' }).limit(ip),+ embedGateVerifyIp: (ip) => getLimiter('embed:gate:verify:ip', { limit: 30, window: '5 m' }).limit(ip),+ embedGateVerifyWallet: (addr) =>+ getLimiter('embed:gate:verify:wallet', { limit: 10, window: '5 m' }).limit(addr),avatarRollback: (userId) =>getLimiter('avatar:rollback', { limit: 10, window: '1 h' }).limit(userId),// Chat inference spends real money on the host's LLM keys, so these are@@ -908,6 +919,13 @@ export const limits = {getLimiter('ai:tts:free:ip', { limit: 10, window: '1 d', critical: true }).limit(ip),aiAsrFreeIp: (ip) =>getLimiter('ai:asr:free:ip', { limit: 5, window: '1 d', critical: true }).limit(ip),+ // Fact Checker (api/x402/fact-check) free daily lane. Same "free tier is the+ // funnel, x402 is the metered overage" shape as the AI speech routes above —+ // each free check runs the REAL search+LLM chain (never a degraded fake), so+ // the quota is tight to bound upstream (search + LLM token) cost. Critical so+ // a Redis outage fails closed to the paid rail rather than opening the chain.+ factCheckFreeIp: (ip) =>+ getLimiter('fact-check:free:ip', { limit: 3, window: '1 d', critical: true }).limit(ip),// NVIDIA Audio2Face-3D (api/a2f) — free upstream but credit-metered, and each// call streams a full speech clip through a bidirectional gRPC stream the// server holds in memory while collecting the blendshape track. Meter perdiff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.jsindex de307e7cd..0f1be7e82 100644--- a/api/_lib/service-catalog/services/index.js+++ b/api/_lib/service-catalog/services/index.js@@ -12,8 +12,11 @@ import modelCheck from './model-check.js';import agentReputation from './agent-reputation.js';import agentBouncer from './agent-bouncer.js';import onchainIdentityVerify from './onchain-identity-verify.js';+import factCheck from './fact-check.js';import pumpLaunch from './pump-launch.js';import forge from './forge.js';+import mintToMesh from './mint-to-mesh.js';+import mintToMeshBatch from './mint-to-mesh-batch.js';import skillMarketplace from './skill-marketplace.js';import symbolAvailability from './symbol-availability.js';import vanity from './vanity.js';@@ -60,8 +63,11 @@ export const PAID_SERVICES = Object.freeze([agentReputation,agentBouncer,onchainIdentityVerify,+ factCheck,pumpLaunch,forge,+ mintToMesh,+ mintToMeshBatch,skillMarketplace,symbolAvailability,vanity,diff --git a/api/_lib/service-catalog/services/mint-to-mesh-batch.js b/api/_lib/service-catalog/services/mint-to-mesh-batch.jsnew file mode 100644index 000000000..c880fe96f--- /dev/null+++ b/api/_lib/service-catalog/services/mint-to-mesh-batch.js@@ -0,0 +1,44 @@+// 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) — batch sibling+// of mint-to-mesh, same disposition.++export default {+ slug: 'mint-to-mesh-batch',+ title: 'Mint to Mesh (Batch)',+ category: '3d',+ useCase: 'Mint to Mesh (Batch) — resolve 1–10 Solana SPL mints to themed glTF (GLB) cubes in a single paid call instead of paying for N round-trips.',+ path: '/api/x402/mint-to-mesh-batch',+ method: 'POST',+ free: false,+ status: 'live',+ priceAtomics: '50000',+ acceptsBuilder: 'standard',+ serviceName: 'three.ws Mint Mesh Batch',+ tags: ['3d', 'gltf', 'solana', 'batch', 'render'],+ description: 'Mint to Mesh (Batch) — resolve 1–10 Solana SPL mints to themed glTF (GLB) cubes in a single paid call instead of paying for N round-trips. Each mint is processed in parallel; per-mint failures (bad mint, RPC unreachable, off-chain metadata 404) report ok:false individually rather than failing the whole batch. Output is base64 JSON-safe GLB bytes ready for Three.js / Babylon.js / model-viewer. Useful for rendering a portfolio carousel or leaderboard of token-themed objects in one call.',+ input: {+ mints: [+ 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',+ 'F7kXZYXWVUTSRQPONMLKJIHGFEDCba9876543210xyz',+ ],+ },+ inputSchema: {+ type: 'object',+ required: ['mints'],+ properties: {+ mints: {+ type: 'array',+ minItems: 1,+ maxItems: 10,+ items: { type: 'string', minLength: 32, maxLength: 44 },+ },+ },+ },+ storefronts: ['x402scan'],+};diff --git a/api/_lib/service-catalog/services/mint-to-mesh.js b/api/_lib/service-catalog/services/mint-to-mesh.jsnew file mode 100644index 000000000..b0a68cd6f--- /dev/null+++ b/api/_lib/service-catalog/services/mint-to-mesh.js@@ -0,0 +1,42 @@+// 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/mint-to-mesh.js for the header note superseding the prior+// "internal-use only" de-listing.++export default {+ slug: 'mint-to-mesh',+ title: 'Mint to Mesh',+ category: '3d',+ useCase: 'Mint to Mesh — pass any Solana SPL token mint, get back a binary glTF (GLB) cube themed and colored from that token\'s own on-chain Metaplex metadata, ready to render.',+ path: '/api/x402/mint-to-mesh',+ method: 'GET',+ free: false,+ status: 'live',+ priceAtomics: '1000',+ acceptsBuilder: 'standard',+ serviceName: 'three.ws Mint to Mesh',+ tags: ['3d', 'gltf', 'solana', 'token', 'render'],+ description: 'Mint to Mesh — pass any Solana SPL token mint, get back a binary glTF (GLB) cube themed and colored from that token\'s own on-chain Metaplex metadata, ready to render. The cube carries the token image as a baseColor texture when one is exposed, and asset.extras carry the full on-chain metadata (name, symbol, description) for downstream introspection. Useful for in-game items, leaderboards, NFT-of-token, and AR previews. Pay-per-call in USDC on Base or Solana.',+ input: {+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ },+ inputSchema: {+ type: 'object',+ required: ['mint'],+ properties: {+ mint: {+ type: 'string',+ minLength: 32,+ maxLength: 44,+ description: 'Base58 SPL mint address on Solana mainnet.',+ },+ },+ },+ storefronts: ['x402scan'],+};diff --git a/api/_lib/x402-buyer-fetch.js b/api/_lib/x402-buyer-fetch.jsindex 824112294..f32e0e654 100644--- a/api/_lib/x402-buyer-fetch.js+++ b/api/_lib/x402-buyer-fetch.js@@ -194,3 +194,14 @@ function safeJson(text) {return null;}}++// ── BNB Chain (MPP / b402) buyer ────────────────────────────────────────────+// Re-exported from the same surface so an agent that already imports the x402+// buyer can also pay MPP-protected endpoints on BNB Chain (eip155:56/97) with+// the same 402 → pay → retry ergonomics. MPP is x402 v2, so the only real+// difference is the network + an EIP-3009 credential signed by @bnb-chain/mpp.+//+// import { buyerFetch, mppFetch } from './x402-buyer-fetch.js';+// // Solana/Base: await buyerFetch(url, { signPayment, caps });+// // BNB Chain: await mppFetch(url, { method: 'GET' }, { account, maxSpend: '20000' });+export { mppFetch, MPP_BUYER_NETWORKS, MppBuyerError } from './bnb/mpp-buyer.js';diff --git a/api/_lib/x402/a2a-server.js b/api/_lib/x402/a2a-server.jsindex e2cf398b6..a754212ed 100644--- a/api/_lib/x402/a2a-server.js+++ b/api/_lib/x402/a2a-server.js@@ -685,28 +685,17 @@ export function a2aPaidEndpoint(spec) {};}-function readJsonBody(req) {- return new Promise((resolve, reject) => {- const chunks = [];- let total = 0;- const limit = 1_000_000;- req.on('data', (c) => {- total += c.length;- if (total > limit) {- reject(Object.assign(new Error('payload too large'), { status: 413 }));- req.destroy();- return;- }- chunks.push(c);- });- req.on('end', () => {- if (!chunks.length) return resolve({});- try {- resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));- } catch (err) {- reject(Object.assign(new Error(`invalid JSON: ${err.message}`), { status: 400 }));- }- });- req.on('error', reject);- });+// Delegates to the shared readBody (api/_lib/http.js), which prefers the+// pre-parsed req.rawBody/req.body the Cloud Run server already captured —+// re-reading the raw stream here (as this function used to) hangs forever+// once Express has drained it. See http.js readBody for the full rationale;+// this was a live production incident on every A2A JSON-RPC POST.+async function readJsonBody(req) {+ const buf = await readBody(req, 1_000_000);+ if (!buf.length) return {};+ try {+ return JSON.parse(buf.toString('utf8'));+ } catch (err) {+ throw Object.assign(new Error(`invalid JSON: ${err.message}`), { status: 400 });+ }}diff --git a/api/_mcp/tools/solana.js b/api/_mcp/tools/solana.jsindex 781bc1d2d..ee27a09cf 100644--- a/api/_mcp/tools/solana.js+++ b/api/_mcp/tools/solana.js@@ -13,7 +13,10 @@ async function ensureWarm({ asset, network }) {catch { /* return cached (empty) */ }}-async function solanaReputation(asset, network) {+// Exported so other paid surfaces (e.g. the persona identity/wallet tools) can+// reuse the SAME ERC-8004-style reputation computation instead of re-deriving+// it against a second copy of the attestation query.+export async function solanaReputation(asset, network) {await ensureWarm({ asset, network });const [fb] = await sql`with feedback as (diff --git a/api/aws-marketplace/subscription.js b/api/aws-marketplace/subscription.jsindex 2f4dd7bc8..f7ac199df 100644--- a/api/aws-marketplace/subscription.js+++ b/api/aws-marketplace/subscription.js@@ -14,19 +14,18 @@// unsubscribe-success — customer cancelled or subscription expired// entitlement-updated — contract product entitlement changed-import { json, wrap } from '../_lib/http.js';+import { json, wrap, readBody } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { verifySnsMessage } from '../_lib/aws-marketplace.js';import { revokeSubscriptionForCustomer } from '../_lib/aws-marketplace-bridge.js';import { env } from '../_lib/env.js';+// Delegates to the shared readBody (api/_lib/http.js), which prefers the+// pre-parsed req.rawBody/req.body the Cloud Run server already captured —+// re-reading the raw stream here (as this function used to) hangs forever+// once Express has drained it.async function readRawBody(req) {- return new Promise((resolve, reject) => {- const chunks = [];- req.on('data', (c) => chunks.push(c));- req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));- req.on('error', reject);- });+ return (await readBody(req, 1_000_000)).toString('utf8');}export default wrap(async (req, res) => {diff --git a/api/forge.js b/api/forge.jsindex ea5af9ba4..05b013294 100644--- a/api/forge.js+++ b/api/forge.js@@ -293,11 +293,11 @@ function isPaidCreditFailure(err) {// Returns true once it has written a 200 response, or false when the lane is// itself unavailable (so the caller can fall through to the next lane). Prompt// is required — NVCF is text-only; photo submissions never reach here.-async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path }) {+async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opts = null, cacheKey = null }) {let submitted;try {const nv = await loadNvidiaProvider();- submitted = await nv.textTo3d({ prompt, tier });+ submitted = await nv.textTo3d({ prompt, tier, seed: opts?.seed ?? undefined });} catch (err) {// A timed-out / unreachable / throttled / 5xx NIM lane is degraded — cool it// down so the next request skips the submit-timeout gamble and fails over@@ -343,17 +343,78 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path }) {tier: tier.id,path,});- const durable = await materializeCreation({+ let durable = await materializeCreation({replicateJobId: syntheticJob,clientKey,glbUrl: submitted.resultGlbUrl,+ quality: true,+ compress: opts?.compression && opts.compression !== 'none' ? opts.compression : null,});++ // One auto-retry on a flagged low-quality/degenerate output (CLAUDE.md: no+ // silent mediocrity). Only worth attempting when the free NIM lane already+ // completed synchronously once — a second synchronous completion is the+ // common case, so this stays a bounded, in-request retry rather than a+ // background job. Best-effort: any retry failure just keeps the first result.+ let retried = false;+ if (shouldRetryForQuality(durable?.quality)) {+ try {+ const nv = await loadNvidiaProvider();+ const retry = await nv.textTo3d({ prompt, tier, seed: opts?.seed ?? undefined });+ if (!retry.taskId && retry.resultGlbUrl) {+ const retryJob = randomUUID().replace(/-/g, '');+ await createCreation({+ clientKey,+ ipHash: hashIp(ip),+ prompt,+ aspect,+ previewImageUrl: null,+ replicateJobId: retryJob,+ textToImageModel: null,+ viewsRequested: 0,+ viewsUsed: null,+ multiview: false,+ backend: backendId,+ tier: tier.id,+ path,+ });+ const retryDurable = await materializeCreation({+ replicateJobId: retryJob,+ clientKey,+ glbUrl: retry.resultGlbUrl,+ quality: true,+ compress: opts?.compression && opts.compression !== 'none' ? opts.compression : null,+ });+ if (retryDurable) {+ durable = retryDurable;+ retried = true;+ }+ }+ } catch (err) {+ console.warn(`[forge] quality auto-retry (nvidia) failed, keeping first result: ${err?.message || err}`);+ }+ }++ if (cacheKey && durable?.glbUrl) {+ await putCachedForgeResult(cacheKey, {+ glb_url: durable.glbUrl,+ backend: backendId,+ tier: tier.id,+ path,+ quality: durable.quality || null,+ });+ }+json(res, 200, {job_id: null,creation_id: durable?.id ?? creationId,status: 'done',glb_url: durable?.glbUrl ?? submitted.resultGlbUrl,durable: Boolean(durable),+ quality: durable?.quality || null,+ quality_retried: retried,+ compression: durable?.compression || null,+ options: opts?.hasOptions ? summarizeForgeOptions(opts) : undefined,...provenance,});return true;@@ -381,10 +442,13 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path }) {tier: tier.id,path,});+ if (cacheKey) await bindJobToCacheKey(token, cacheKey);+ if (opts) await bindJobToOptions(token, opts);json(res, 200, {job_id: token,creation_id: creationId,status: 'queued',+ options: opts?.hasOptions ? summarizeForgeOptions(opts) : undefined,...provenance,});return true;@@ -421,6 +485,8 @@ async function runHfImageLane({mode = 'image_to_3d',previewImageUrl = null,textToImageModel = null,+ opts = null,+ cacheKey = null,}) {let provider;try {@@ -464,7 +530,7 @@ async function runHfImageLane({const submitted = await provider.submit({mode: 'reconstruct',sourceUrl: imageUrls[0],- params: { images: imageUrls, prompt: prompt || undefined },+ params: { images: imageUrls, prompt: prompt || undefined, seed: opts?.seed ?? undefined },});// submit() blocks and packs the finished GLB into extJobId; status() echoes// it back without re-hitting the Space.@@ -500,17 +566,87 @@ async function runHfImageLane({});// Best-effort copy to R2 so the model survives the Space's ephemeral file URL;// fail-soft to the raw HF url so the client still gets a model either way.- const durable = await materializeCreation({+ const wantCompress = opts?.compression && opts.compression !== 'none' ? opts.compression : null;+ let durable = await materializeCreation({replicateJobId: syntheticJob,clientKey,glbUrl: resultGlbUrl,+ quality: true,+ compress: wantCompress,});++ // One auto-retry on a flagged low-quality/degenerate output. Only attempted+ // when a concurrency slot is free right now — the HF lane is capacity-capped,+ // so a busy fleet keeps the first (flagged) result rather than starving+ // other callers of their turn on the free Spaces.+ let retried = false;+ if (shouldRetryForQuality(durable?.quality)) {+ const retrySlot = await acquireBlockingSlot('hf', { max: SCALE_LIMITS.hfConcurrent, ttlMs: SCALE_LIMITS.hfSlotTtlMs });+ if (retrySlot.ok) {+ try {+ const retrySubmitted = await provider.submit({+ mode: 'reconstruct',+ sourceUrl: imageUrls[0],+ params: { images: imageUrls, prompt: prompt || undefined, seed: opts?.seed ?? undefined },+ });+ const retryFinished = await provider.status(retrySubmitted.extJobId);+ if (retryFinished?.resultGlbUrl) {+ const retryJob = randomUUID().replace(/-/g, '');+ await createCreation({+ clientKey,+ ipHash: hashIp(ip),+ prompt: prompt || (isImageMode ? 'image-to-3d' : ''),+ aspect,+ previewImageUrl: preview,+ replicateJobId: retryJob,+ textToImageModel: isImageMode ? null : textToImageModel,+ viewsRequested: imageUrls.length,+ viewsUsed: imageUrls.length,+ multiview: imageUrls.length > 1,+ backend: backendId,+ tier: tier.id,+ path,+ });+ const retryDurable = await materializeCreation({+ replicateJobId: retryJob,+ clientKey,+ glbUrl: retryFinished.resultGlbUrl,+ quality: true,+ compress: wantCompress,+ });+ if (retryDurable) {+ durable = retryDurable;+ retried = true;+ }+ }+ } catch (err) {+ console.warn(`[forge] quality auto-retry (huggingface) failed, keeping first result: ${err?.message || err}`);+ } finally {+ await retrySlot.release();+ }+ }+ }++ if (cacheKey && !isImageMode && durable?.glbUrl) {+ await putCachedForgeResult(cacheKey, {+ glb_url: durable.glbUrl,+ backend: backendId,+ tier: tier.id,+ path,+ quality: durable.quality || null,+ });+ }+json(res, 200, {job_id: null,creation_id: durable?.id ?? creationId,status: 'done',glb_url: durable?.glbUrl ?? resultGlbUrl,durable: Boolean(durable),+ quality: durable?.quality || null,+ quality_retried: retried,+ compression: durable?.compression || null,+ options: opts?.hasOptions ? summarizeForgeOptions(opts) : undefined,mode,path,tier: tier.id,diff --git a/api/jobs/flush-usage-events.js b/api/jobs/flush-usage-events.jsindex b050dc2d8..8f65624b4 100644--- a/api/jobs/flush-usage-events.js+++ b/api/jobs/flush-usage-events.js@@ -12,7 +12,7 @@// Security: every inbound POST must carry a valid Upstash-Signature header// signed by QStash. Requests without it are rejected 401.-import { error, json, method, wrap } from '../_lib/http.js';+import { error, json, method, wrap, readBody } from '../_lib/http.js';import { verifyQstashSignature } from '../_lib/qstash.js';import { flushUsageBuffer } from '../_lib/usage.js';import { flushAuditBuffer } from '../_lib/x402/audit-log.js';@@ -20,13 +20,11 @@ import { flushAuditBuffer } from '../_lib/x402/audit-log.js';export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;- // Collect the raw body for signature verification.- const raw = await new Promise((resolve, reject) => {- const chunks = [];- req.on('data', (c) => chunks.push(c));- req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));- req.on('error', reject);- });+ // Collect the raw body for signature verification. readBody prefers+ // req.rawBody (captured pre-parse by the Cloud Run server's express.json()+ // `verify` hook) so the QStash HMAC check below sees the exact signed bytes+ // — re-reading the raw stream here hangs forever once Express has drained it.+ const raw = (await readBody(req, 1_000_000)).toString('utf8');try {const origin = process.env.APP_ORIGIN || (process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : '');diff --git a/api/webhooks/replicate.js b/api/webhooks/replicate.jsindex 02cf3f7aa..24a3dfc53 100644--- a/api/webhooks/replicate.js+++ b/api/webhooks/replicate.js@@ -22,7 +22,7 @@import { createHmac, timingSafeEqual } from 'node:crypto';import { sql } from '../_lib/db.js';-import { json, method, wrap, error } from '../_lib/http.js';+import { json, method, wrap, error, readBody } from '../_lib/http.js';import { finalizeReconstructStage } from '../_lib/reconstruct-finalize.js';import { finalizeAutoRigStage } from '../_lib/auto-rig.js';// Provider-result URL guard, shared with the poll, cron, and rig-poller paths so@@ -75,28 +75,14 @@ function translateStatus(s) {}}-async function readRaw(req, limit = 1_000_000) {- const chunks = [];- let total = 0;- return new Promise((resolve, reject) => {- req.on('data', (c) => {- total += c.length;- if (total > limit) {- reject(Object.assign(new Error('payload too large'), { status: 413 }));- req.destroy();- return;- }- chunks.push(c);- });- req.on('end', () => resolve(Buffer.concat(chunks)));- req.on('error', reject);- });-}-export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;- const raw = await readRaw(req);+ // readBody prefers req.rawBody (captured pre-parse by the Cloud Run server's+ // express.json() `verify` hook) so the signature below checks the exact bytes+ // Replicate signed — re-reading the raw stream here would hang forever once+ // Express has already drained it (see api/_lib/http.js readBody for why).+ const raw = await readBody(req, 1_000_000);const bodyText = raw.toString('utf8');const signingKey = process.env.REPLICATE_WEBHOOK_SIGNING_KEYdiff --git a/api/widgets/[id]/knowledge-process.js b/api/widgets/[id]/knowledge-process.jsindex 825db4dca..de1ae3c97 100644--- a/api/widgets/[id]/knowledge-process.js+++ b/api/widgets/[id]/knowledge-process.js@@ -5,27 +5,18 @@// can trigger processing. Reads the queued doc by ID, embeds its chunks,// marks ready. Idempotent — safe to retry on transient failures.-import { wrap, json, error, method } from '../../_lib/http.js';+import { wrap, json, error, method, readBody } from '../../_lib/http.js';import { verifyQstashSignature, qstashEnabled } from '../../_lib/qstash.js';import { processQueuedDoc } from './_knowledge.js';import { env } from '../../_lib/env.js';-function readRawBody(req, limit = 1_000_000) {- return new Promise((resolve, reject) => {- const chunks = [];- let total = 0;- req.on('data', (c) => {- total += c.length;- if (total > limit) {- reject(Object.assign(new Error('payload too large'), { status: 413 }));- req.destroy();- return;- }- chunks.push(c);- });- req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));- req.on('error', reject);- });+// Delegates to the shared readBody (api/_lib/http.js), which prefers the+// pre-parsed req.rawBody the Cloud Run server already captured pre-parse, so+// the QStash signature below checks the exact signed bytes — re-reading the+// raw stream here (as this function used to) hangs forever once Express has+// drained it.+async function readRawBody(req, limit = 1_000_000) {+ return (await readBody(req, limit)).toString('utf8');}export default wrap(async (req, res) => {diff --git a/data/changelog.json b/data/changelog.jsonindex 3f1e77980..2fdde3dab 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,41 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-08",+ "title": "New free API: check if a wallet holds a Binance Account Bound Token (BABT)",+ "summary": "GET /api/bnb/babt-check?address=0x... tells you whether a BSC address holds a BABT — Binance's non-transferable, KYC-backed on-chain token. It's a real, live signal (1.16M+ holders on BSC mainnet) that developers can use as a free, no-signup uniqueness check for allowlists, anti-sybil gating, or airdrop targeting on BNB Chain.",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-07-08",+ "title": "The free crypto API goes deeper: CoinGecko, DefiLlama, and two new DeFi price feeds",+ "summary": "The unified /api/v1/x crypto API grew from 4 to 12 endpoints across CoinGecko and DefiLlama, all free with zero setup. CoinGecko now answers a full per-coin snapshot (price, ATH/ATL, supply, multi-window change), trending coins and hot categories, token price by contract address, the global market snapshot, and OHLC candles — not just spot price and ranked markets. DefiLlama adds every chain ranked by TVL, one protocol's full profile with 30 days of TVL history, and 90 days of historical chain TVL. Two new providers ride DefiLlama's sibling APIs: llama-prices for any chain:address token (covers long-tail tokens CoinGecko and Jupiter don't index) and llama-stablecoins for every tracked stablecoin's peg, price, and circulating supply.",+ "tags": [+ "feature"+ ],+ "link": "/docs/api-reference"+ },+ {+ "date": "2026-07-08",+ "title": "BNB Chain hub: three uniquely-BNB demos in one place",+ "summary": "New /bnb landing page tells the whole BNB Chain story: gasless agent onboarding (a zero-balance wallet mints an on-chain identity, no faucet), an on-chain-gated 3D vault backed by Greenfield storage permissions, and a real-time on-chain world riding BNB's ~0.45s blocks — each claim traced to what we independently verified live, never BNB's own roadmap promises. The page embeds a live block-time widget that measures the real average off a public RPC on every load, and each feature card auto-detects whether its track has actually shipped on this deployment, showing an honest \"coming soon\" instead of a dead link until it has.",+ "tags": [+ "feature"+ ],+ "link": "/bnb"+ },+ {+ "date": "2026-07-08",+ "title": "Give your agent a 3D body in one call — the new Embodiment endpoint",+ "summary": "Any AI agent can now buy itself a real presence in a single USDC payment: POST a name plus a text description (or a reference photo) to the new Embodiment endpoint and get back a rigged, animated, talking 3D avatar, a durable persona id that reloads in any future session, and a one-tag embed snippet for any website. It's the same free generate-and-rig chain that powers the 3D Studio, packaged as one paid call — no separate rigging step, no account. Generation failures never settle, so a buyer is only ever charged for a finished body.",+ "tags": [+ "feature"+ ],+ "link": "/docs/embody"+ },{"date": "2026-07-08","title": "Paid API endpoints now stay up through a cache-provider outage",diff --git a/data/pages.json b/data/pages.jsonindex 4dc0b48e8..66750a6eb 100644--- a/data/pages.json+++ b/data/pages.json@@ -1234,6 +1234,14 @@"changefreq": "hourly","added": "2026-07-08"},+ {+ "path": "/bnb",+ "title": "BNB Chain — Three Genuinely-Unique Demos",+ "description": "The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-07-08"+ },{"path": "/constellation","title": "watsonx Constellation",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex c3220b61f..6282b3a45 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -1723,12 +1723,16 @@ feeds directly (`source: "rss"`).One catch-all route (`api/v1/x/[...slug].js`) bundles every third-party APIthree.ws re-offers as one API, registered in `api/v1/_providers.js`. Adding anew 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`).+no new route file. Providers today: **CoinGecko** (`coingecko`, price/markets/+coin/trending/token-price/global/ohlc), **DefiLlama** (`defillama`, protocols/+tvl/chains/protocol/chain-tvl), **DefiLlama Prices** (`llama-prices`, current+price for any `chain:address` pair), **DefiLlama Stablecoins**+(`llama-stablecoins`, every tracked stablecoin ranked by circulating supply),+**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@@ -1788,13 +1792,52 @@ 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 |+| `coingecko/coin`, `/trending`, `/token-price`, `/global`, `/ohlc` | 20 | 1500 |+| `defillama/protocols`, `defillama/tvl`, `/chains`, `/protocol`, `/chain-tvl` | 30 | 2000 |+| `llama-prices/current` | 30 | 2000 |+| `llama-stablecoins/list` | 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 |+**CoinGecko** (`coingecko`) — beyond spot price and ranked markets: a full+per-coin snapshot, trending coins/categories, token price by contract address,+the global market snapshot, and OHLC candles.++```bash+curl -s "https://three.ws/api/v1/x/coingecko/coin?id=solana"+curl -s "https://three.ws/api/v1/x/coingecko/trending"+curl -s "https://three.ws/api/v1/x/coingecko/token-price?addresses=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"+curl -s "https://three.ws/api/v1/x/coingecko/global"+curl -s "https://three.ws/api/v1/x/coingecko/ohlc?id=solana&days=7"+```++**DefiLlama** (`defillama`) — every chain by TVL, one protocol's full profile+(current TVL per chain + the last 30 days of its total series), and 90 days of+historical TVL for one chain.++```bash+curl -s "https://three.ws/api/v1/x/defillama/chains"+curl -s "https://three.ws/api/v1/x/defillama/protocol?slug=uniswap"+curl -s "https://three.ws/api/v1/x/defillama/chain-tvl?chain=Solana"+```++**DefiLlama Prices** (`llama-prices`) — DefiLlama's own coin-price oracle,+covering long-tail tokens CoinGecko and Jupiter don't index yet:++```bash+curl -s "https://three.ws/api/v1/x/llama-prices/current?coins=solana:FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"+```++**DefiLlama Stablecoins** (`llama-stablecoins`) — every tracked stablecoin,+peg type, price, and circulating supply, ranked:++```bash+curl -s "https://three.ws/api/v1/x/llama-stablecoins/list"+```+**DexScreener** (`dexscreener`) — live DEX pair data for any token: price,liquidity, volume, 24h change, txns. Works for any chain DexScreener indexes,not just Solana.diff --git a/docs/bnb-payments.md b/docs/bnb-payments.mdnew file mode 100644index 000000000..be89ea73e--- /dev/null+++ b/docs/bnb-payments.md@@ -0,0 +1,157 @@+# BNB Chain payments — MPP + gasless sends++three.ws speaks two agent-payment protocols. Our catalog has always run **x402**+(the CDP wire format) on Solana and Base. It now also speaks **MPP** — BNB+Chain's Machine Payments Protocol — so agents from the BNB ecosystem can pay our+endpoints, and our agents can pay theirs. This page explains both halves plus the+gasless-send rail underneath, for a reader with zero prior context.++Everything here is real code against real endpoints. Where a capability needs a+credential we don't ship (a facilitator merchant key, a funded testnet wallet),+that is called out honestly — nothing is faked.++---++## 1. What MPP is, and how it relates to x402++MPP is BNB Chain's answer to x402. Its `b402` layer (Binance OnchainPay) is+**x402 v2, byte-for-byte** — the same `402 Payment Required` challenge, the same+base64 `X-PAYMENT` request header, the same `X-PAYMENT-RESPONSE` receipt header,+and the same EIP-3009 `transferWithAuthorization` credential our Base x402 path+already signs. The only real differences are:++| | x402 (our existing path) | MPP / b402 (new) |+|---|---|---|+| Networks | Solana, Base (`eip155:8453`) | BNB Chain (`eip155:56`, testnet `eip155:97`) |+| Settlement | our Solana/Base facilitator | the b402 facilitator (Binance OnchainPay) |+| Credential | EIP-3009 (Base), signed tx (Solana) | EIP-3009 (`buildEip3009Payment`) |++Because the wire format is shared, a single endpoint can advertise **both** and a+single buyer can pay **either** — see the [bridge spec](../specs/x402-mpp-bridge.md)+for the exact header-precedence and credential-mapping contract.++The code lives in `api/_lib/bnb/`:++- `mpp-server.js` — accept MPP payments (the merchant side).+- `mpp-buyer.js` — pay MPP endpoints (the buyer side).+- `megafuel.js` — send BNB Chain transactions with zero gas (the rail below).+- `chains.js` — chain metadata + a resilient RPC client shared by all three.++---++## 2. Pay one of our endpoints with MPP (buyer POV)++Our pilot endpoint, the **$THREE Town Oracle** (`GET /api/x402/three-intel`),+accepts MPP additively: pay it on BNB Chain and it settles through b402; pay it on+Solana/Base and the original x402 path is untouched.++A minimal buyer, using any x402/b402 client. The flow is the standard 402 dance:++```js+import { privateKeyToAccount } from 'viem/accounts';+import { buildEip3009Payment, encodeXPayment } from '@bnb-chain/mpp/b402';++const account = privateKeyToAccount(process.env.BNB_TESTNET_DEPLOYER_KEY);+const url = 'https://three.ws/api/x402/three-intel';++// 1. Probe — get the 402 menu.+const probe = await fetch(url);+const challenge = await probe.json(); // { x402Version: 2, accepts: [...] }++// 2. Pick the BNB Chain (eip155:97) eip3009 offer.+const requirement = challenge.accepts.find(+ (a) => a.network === 'eip155:97' && a.extra?.assetTransferMethod === 'eip3009',+);++// 3. Sign the EIP-3009 credential and retry with the X-PAYMENT header.+const payment = await buildEip3009Payment({ account, requirements: requirement, resourceUrl: url });+const paid = await fetch(url, { headers: { 'X-PAYMENT': encodeXPayment(payment) } });+console.log(await paid.json()); // the oracle signal+console.log(paid.headers.get('x-payment-response')); // the settlement receipt+```++## 3. Our agents paying any MPP endpoint (`mpp-buyer.js`)++Use `mppFetch` — it wraps the whole 402 → sign → retry loop, enforces a **hard+spend cap**, and matches the ergonomics of our existing `buyerFetch`:++```js+import { mppFetch } from '../api/_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', // atomic units — a quote above this is REFUSED, unpaid+ network: 'eip155:97', // BSC testnet (default target)+});++if (res.ok) {+ console.log(res.result); // the endpoint's JSON body+ console.log(res.settlement); // decoded X-PAYMENT-RESPONSE+} else if (res.abort) {+ console.log('did not pay:', res.code, res.reason); // e.g. over_budget+}+```++`maxSpend` is enforced **before any signature** — an over-quote returns+`{ ok:false, abort:true, code:'over_budget' }` with zero network payment. The same+symbol is re-exported from `api/_lib/x402-buyer-fetch.js`, so an agent that+already imports the x402 buyer gets the MPP buyer from the same module.++## 4. Gasless sends via MegaFuel (`megafuel.js`)++BNB Chain can sponsor gas at the block-building layer (BEP-414 paymaster ++BEP-322 atomic bundles), so a **plain private-key EOA** can send a transaction+that pays **zero gas** — no smart account, no EIP-7702 delegation. This is+mechanically impossible on Ethereum L1 / Base. The production implementation is+NodeReal's **MegaFuel**.++```js+import { sendGasless } from '../api/_lib/bnb/megafuel.js';+import { privateKeyToAccount } from 'viem/accounts';++const account = privateKeyToAccount(process.env.BNB_TESTNET_DEPLOYER_KEY);++const { hash, mode } = await sendGasless('bscTestnet', {+ account,+ tx: { to: '0x000000000000000000000000000000000000dEaD', value: 0n },+});+// mode === 'sponsored' → MegaFuel paid the gas (tx signed with gasPrice 0)+// mode === 'self-pay' → no sponsor policy / MegaFuel down → normal gas, still sent+```++### Honest caveats (do not oversell these)++- **MegaFuel is operated by one company** (NodeReal), and BEP-414 is still a+ *Draft* spec. `sendGasless` therefore **always** carries a self-pay fallback:+ if the sponsor declines or the endpoint is down, the same send goes through+ with normal gas rather than failing. The gasless path is an optimization, not a+ guarantee.+- Sponsorship needs a **provisioned sponsor policy** whitelisting your sender.+ Without one, `pm_isSponsorable` returns `false` and every send self-pays — the+ feature still works end-to-end. Provision a policy at+ [dashboard.nodereal.io](https://dashboard.nodereal.io) (MegaFuel product).+- BNB Chain's ~0.45s blocks are **verified live**; "20,000 TPS" and a chain-level+ "AI agent framework" are roadmap promises we do **not** claim.++### Configuration++| Env var | Purpose | Required? |+|---|---|---|+| `X402_PAY_TO_BSC` | Merchant payout address for MPP receipts | to advertise MPP |+| `B402_BASE_URL` / `B402_CLIENT_ID` / `B402_ACCESS_TOKEN` / `B402_PRIVATE_KEY` | b402 facilitator merchant creds (RSA "Tesla" signing) | to settle MPP on-chain |+| `NODEREAL_MEGAFUEL_KEY` | MegaFuel policy-management only (not the send path) | optional |+| `BNB_TESTNET_DEPLOYER_KEY` | Funded tBNB sender for live proofs | for live sends |++Without the `B402_*` merchant credentials, `mpp-server.js` still **verifies**+incoming credentials off-chain (recover payer, pin requirements, replay-guard)+and reports `mpp_not_configured` for the on-chain settle — it never fabricates a+receipt.++---++See also: the wire contract in [`specs/x402-mpp-bridge.md`](../specs/x402-mpp-bridge.md),+and the [BNB Chain campaign context](../prompts/bnb-chain/00-CONTEXT.md) for the+full verified-facts list.diff --git a/docs/index.html b/docs/index.htmlindex 0b83c045b..1f48f4907 100644--- a/docs/index.html+++ b/docs/index.html@@ -816,6 +816,7 @@{ label: 'Web component', path: 'web-component' },{ label: 'MCP', path: 'mcp' },{ label: 'MCP tools catalog', path: 'mcp-tools' },+ { label: 'Spatial MCP (3D responses)', path: 'spatial-mcp' },{ label: 'SDK', path: 'sdk' },{ label: 'Widgets', path: 'widgets' },{ label: 'Widget Studio', path: 'widget-studio' },diff --git a/docs/spatial-mcp.md b/docs/spatial-mcp.mdindex 84302c2c4..97e53c5dd 100644--- a/docs/spatial-mcp.md+++ b/docs/spatial-mcp.md@@ -2,8 +2,8 @@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()`+- **Spec:** [`specs/SPATIAL_MCP.md`](https://github.com/nirholas/three.ws/blob/main/specs/SPATIAL_MCP.md) (v0.1, CC0)+- **Validator (code):** [`api/_lib/spatial-mcp.js`](https://github.com/nirholas/three.ws/blob/main/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`@@ -97,7 +97,7 @@ Free 3D Studio (`structuredContent.spatial`): `forge_free`, `text_to_avatar`, `m## Related-- [`specs/SPATIAL_MCP.md`](../specs/SPATIAL_MCP.md) — the normative spec+- [`specs/SPATIAL_MCP.md`](https://github.com/nirholas/three.ws/blob/main/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/start-here.md b/docs/start-here.mdindex 4a98e058d..2066d2492 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -75,5 +75,6 @@ If you're here to create and share agents rather than write code, follow this pa- **Developer docs** → Read the [Introduction](./introduction.md) for the full technical picture- **Your agent needs a face?** → [OKX.AI marketplace services](./okx-marketplace.md) — the Agent Identity Studio and the pay-per-call 3D services other agents buy from us; demo identities at [/agent-identities](/agent-identities)- **Buying 3D asset work per call?** → [The 3D Asset Pipeline](./3d-pipeline.md) — pay a few cents in USDC to rig, remesh, make game-ready, stylize, or background-remove an asset; one call, one finished URL, no account or API key+- **Want your agent to have a body?** → [Embodiment](./embody.md) — one $1 USDC call turns a prompt or image into a rigged, animated, voiced 3D avatar plus a one-tag embed for any website; no account, no separate rigging step- **Building UI?** → [ui-juice](./ui-juice.md) is the shared game-feel library (count-ups, sparklines, ring gauges, live dots, the "it shipped" ripple) every surface animates with- **Teaching another AI to use three.ws?** → [The Agent Skills pack](./agent-skills.md) — portable `SKILL.md` folders that give any Claude surface (Claude Code, the Claude apps, the Agent SDK) three.ws's 3D-creation, wallet, and x402-economy skills; the 3D subset is cross-platform-safediff --git a/packages/naming-mcp/src/tools/sns-resolve.js b/packages/naming-mcp/src/tools/sns-resolve.jsindex 9cb01c02e..e46fbceb4 100644--- a/packages/naming-mcp/src/tools/sns-resolve.js+++ b/packages/naming-mcp/src/tools/sns-resolve.js@@ -1,25 +1,48 @@// `sns_resolve` — resolve a Solana .sol name to its owner wallet. Read-only.//// Wraps GET /api/sns?name=<label>[.sol].+//+// Proof-of-port for @three-ws/tool-sdk (see packages/tool-sdk/): this is the+// same tool as before (name, schema, description, behavior), now authored+// with defineTool/defineExecutor/toMcpTools instead of a hand-written `def`+// object. `apiRequest` already implements its own abort-timeout fetch (see+// ../lib/api.js), so it is kept as the transport — `guardedFetch` is not+// layered on top here, to avoid changing timeout/abort semantics for this+// port. The declared `network` permission documents the host it talks to.import { z } from 'zod';+import { defineTool, defineExecutor, toMcpTools } from '@three-ws/tool-sdk';+import { apiRequest } from '../lib/api.js';+import { THREE_WS_BASE } from '../config.js';-export const def = {- name: 'sns_resolve',+const tool = defineTool({+ id: 'naming-mcp-sns-resolve',title: 'Resolve a .sol name to its owner wallet',- annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },description:'Resolve a Solana Name Service (.sol) name to the base58 wallet address that owns it. Accepts a bare label, a subdomain, or the full name with or without the trailing ".sol". Returns the owner address, or resolved:false when the name is unregistered. Mainnet only. Read-only.',- inputSchema: {- name: z- .string()- .min(1)- .describe('A .sol label to resolve, e.g. "bonfida", "nick.threews", or "bonfida.sol" (the .sol suffix is optional).'),- },- async handler(args) {- const name = String(args?.name ?? '').trim();+ version: '1.0.0',+ permissions: { network: [new URL(THREE_WS_BASE).hostname] },+ apis: [+ {+ name: '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. Accepts a bare label, a subdomain, or the full name with or without the trailing ".sol". Returns the owner address, or resolved:false when the name is unregistered. Mainnet only. Read-only.',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ parameters: z.object({+ name: z+ .string()+ .min(1)+ .describe('A .sol label to resolve, e.g. "bonfida", "nick.threews", or "bonfida.sol" (the .sol suffix is optional).'),+ }),+ },+ ],+});++const executor = defineExecutor(tool, {+ async sns_resolve({ name }) {const data = await apiRequest('/api/sns', { query: { name } });const result = data?.data ?? {};return {@@ -29,4 +52,6 @@ export const def = {resolved: Boolean(result.resolved),};},-};+});++export const def = toMcpTools(tool, executor)[0];diff --git a/pages/coins.html b/pages/coins.htmlindex 24149c75b..0cfe1316a 100644--- a/pages/coins.html+++ b/pages/coins.html@@ -1,7 +1,21 @@<!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>+ <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>Markets · three.ws</title>@@ -17,7 +31,10 @@property="og:description"content="Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets."/>- <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Markets+%E2%80%94+Live+Crypto+Prices&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins" />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Markets+%E2%80%94+Live+Crypto+Prices&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins"+ /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" /><meta name="twitter:card" content="summary_large_image" />@@ -27,7 +44,10 @@name="twitter:description"content="Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets."/>- <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Markets+%E2%80%94+Live+Crypto+Prices&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins" />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Markets+%E2%80%94+Live+Crypto+Prices&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins"+ /><meta name="theme-color" content="#09090b" /><link rel="icon" href="/favicon.ico" sizes="any" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" />@@ -38,12 +58,30 @@<link rel="stylesheet" href="/src/coin-pages.css" /><link rel="stylesheet" href="/footer.css" /><link rel="canonical" href="https://three.ws/coins" />-- <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="Markets — Live Crypto Prices — three.ws">- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Markets — Live Crypto Prices","description":"Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.","url":"https://three.ws/coins","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&t=Markets+%E2%80%94+Live+Crypto+Prices&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins"}]}</script>-</head>++ <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="Markets — Live Crypto Prices — three.ws" />+ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Markets — Live Crypto Prices",+ "description": "Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.",+ "url": "https://three.ws/coins",+ "isPartOf": {+ "@type": "WebSite",+ "name": "three.ws",+ "url": "https://three.ws"+ },+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=Markets+%E2%80%94+Live+Crypto+Prices&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins"+ }+ ]+ }+ </script>+ </head><body><header><div id="nav-container"></div></header><script src="/nav.js"></script>@@ -51,8 +89,8 @@<main class="cv-container"><h1 class="cv-h1">Markets</h1><p class="cv-sub">- Real-time cryptocurrency market data — prices, trends, and global overview for hundreds of- digital assets.+ Real-time cryptocurrency market data — prices, trends, and global overview for+ hundreds of digital assets.</p><!-- Market tools hub: every sibling surface, discoverable from the index. -->@@ -79,7 +117,17 @@<h2 class="cv-h2" style="margin: 0">Top Cryptocurrencies</h2><div class="cv-search" id="cv-search"><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>+ <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><inputid="cv-search-input"diff --git a/prompts/bnb-chain/00-CONTEXT.md b/prompts/bnb-chain/00-CONTEXT.mdindex 63100ab78..922ad86fa 100644--- a/prompts/bnb-chain/00-CONTEXT.md+++ b/prompts/bnb-chain/00-CONTEXT.md@@ -56,8 +56,12 @@ Boundaries that still hold:**Refuted / unverified — NEVER claim these in docs, UI copy, or marketing:** "20,000 TPS"and the chain-level "AI agent framework" are roadmap promises, not shipped. Greenfield-mirror-NFTs are control handles, NOT freely composable ERC-721s. BABT sybil-gating is-unverified (prompt 20 settles it). No unique precompiles / native LST hooks substantiated.+mirror-NFTs are control handles, NOT freely composable ERC-721s. No unique precompiles /+native LST hooks substantiated. **BABT is SETTLED, not refuted:** prompt 20 confirmed it+real, live on BSC mainnet (`0x2B09d47D550061f995A3b5C6F0Fd58005215D7c8`, 1.16M+ holders)+AND testnet, and freely third-party-queryable via `balanceOf`/`tokenIdOf` — see+`docs/bnb-babt-findings.md` and `api/_lib/bnb/babt.js`. Do claim it as a real KYC-backed+signal; do NOT claim it's a permanent identity anchor (Binance can revoke/re-mint).Honest-docs rule: any "only on BNB Chain" claim you write must trace to the verified list.## Networks & endpointsdiff --git a/prompts/bnb-chain/PROGRESS.md b/prompts/bnb-chain/PROGRESS.mdindex 30a0490fc..bfd2d0b2f 100644--- a/prompts/bnb-chain/PROGRESS.md+++ b/prompts/bnb-chain/PROGRESS.md@@ -181,3 +181,62 @@ BscScan-visible tx; the faucet's reCAPTCHA remains the blocker — same gap promhit if it wants a real broadcast rather than a read-only RPC probe.**Status: DONE.** `isSponsorable`/`sendGasless` are ready for prompt 03/15 to import.++---++## 2026-07-08 — Prompt 20: BABT verification spike — VERDICT: REAL, SHIPPED++**Truth-before-code gate: PASSED.** BABT (Binance Account Bound Token) is real, live on+BSC mainnet AND testnet, and third-party-queryable today via a single free `eth_call`.+Full research writeup with sources: `docs/bnb-babt-findings.md`.++**Contract identity — real `eth_getCode` + `name()` probes, not taken on faith:**+- Mainnet `0x2B09d47D550061f995A3b5C6F0Fd58005215D7c8` — bytecode present (3622 bytes),+ `name()` = `"Binance Account Bound Token"`, `totalSupply()` = 1,164,243 (matches+ BscScan's 1.16M+ holder count). Verified contract, 1.4M+ transactions.+- Testnet `0x984E6a7b9cb73cB7884c9ca9b1Ee625546F9D0E3` — also has real bytecode,+ `name()` = same string, `totalSupply()` = 1,252. **A real testnet deployment exists**+ (contrary to 00-CONTEXT's working assumption) — real mints, but developer test+ accounts, not KYC'd Binance users, so it's useful for integration testing only.+- Both addresses sourced from Binance's own docs (`developers.binance.com/docs/babt/apis-spec`),+ never invented.++**Real holder proof — found by scanning live `Transfer` (mint) logs on the mainnet+contract, then reading the resulting address back through the real interface:**+```+mint found in blocks 108689374–108694374 → holder 0x04d1c36842430a169d132ada68006e6bb9e3808b+balanceOf(holder) = 1+tokenIdOf(holder) = 1316815+balanceOf(0x…dEaD burn address) = 0 (sanity check)+```+Interface: BEP-721-extending soulbound token — `balanceOf(address)`, `tokenIdOf(address)`,+`ownerOf(uint256)`, `totalSupply()`, all free public `view` reads, no API key/Binance+relationship needed to *read*. Non-transferable; Binance can revoke + re-mint to a new+wallet (rotates `tokenId` — don't treat it as a stable identity anchor, per Binance's own+integration warning).++**Shipped** (gate passed → build half executed):+- `api/_lib/bnb/babt.js` — `hasBabt(address, network?, opts?)`, mainnet-default,+ typed `BabtCheckError` on a real read failure, tokenIdOf failure never downgrades a+ confirmed `balanceOf>0` holder to a false negative.+- `GET /api/bnb/babt-check?address=&network=` — free, rate-limited (`limits.publicIp`),+ 400 on bad input/unknown network, 502 `contract_unreachable` on RPC failure, honest+ `note` field distinguishing the real mainnet KYC signal from the testnet+ developer-only caveat.+- `tests/bnb-babt.test.js` (10 tests, +1 live-RPC-gated) — lib-level, mocked client for+ determinism, live test re-proving the exact holder above against the real contract+ (`BNB_LIVE_RPC=1` → 10/10 passed, confirms `holdsBabt:true`, `tokenId` populated).+- `tests/bnb-babt-check-endpoint.test.js` (13 tests) — endpoint validation, success,+ upstream-failure, and rate-limit paths, mocked `hasBabt`/`limits` (kept in its own+ file — `vi.mock` hoisting would otherwise shadow the real `hasBabt` the lib suite+ exercises directly).+- `docs/bnb-babt-findings.md` — full verdict, live probe output, interface, limitations+ (KYC-not-permanent-identity, mainnet-primary, single-issuer trust), and an honest+ comparison vs. Gitcoin Passport / World ID / Coinbase attestations.+- `00-CONTEXT.md` refuted-list line updated to reflect the settled verdict.++**Gap for future prompts:** no gap — the read path needs nothing further (no key, no+funded wallet, no policy). If a future prompt wants to *gate* a three.ws feature (mint,+allowlist, etc.) on `hasBabt`, `api/_lib/bnb/babt.js` is ready to import directly.++**Status: DONE.** Open question closed; `hasBabt`/`/api/bnb/babt-check` ready to import.diff --git a/public/changelog.json b/public/changelog.jsonindex d09332f78..c5a5e37ff 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T00:51:31.607Z",+ "generated_at": "2026-07-08T00:57:16.888Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,16 @@"launch"]},+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "BNB Chain — Three Genuinely-Unique Demos",+ "summary": "The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.",+ "link": "/bnb",+ "tags": [+ "launch"+ ]+ },{"date": "2026-07-08","type": "launch",@@ -107,6 +117,26 @@"sdk"]},+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "BNB Chain hub: three uniquely-BNB demos in one place",+ "summary": "New /bnb landing page tells the whole BNB Chain story: gasless agent onboarding (a zero-balance wallet mints an on-chain identity, no faucet), an on-chain-gated 3D vault backed by Greenfield storage permissions, and a real-time on-chain world riding BNB's ~0.45s blocks — each claim traced to what we independently verified live, never BNB's own roadmap promises. The page embeds a live block-time widget that measures the real average off a public RPC on every load, and each feature card auto-detects whether its track has actually shipped on this deployment, showing an honest \"coming soon\" instead of a dead link until it has.",+ "link": "/bnb",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "Give your agent a 3D body in one call — the new Embodiment endpoint",+ "summary": "Any AI agent can now buy itself a real presence in a single USDC payment: POST a name plus a text description (or a reference photo) to the new Embodiment endpoint and get back a rigged, animated, talking 3D avatar, a durable persona id that reloads in any future session, and a one-tag embed snippet for any website. It's the same free generate-and-rig chain that powers the 3D Studio, packaged as one paid call — no separate rigging step, no account. Generation failures never settle, so a buyer is only ever charged for a finished body.",+ "link": "/docs/embody",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-08","type": "update",@@ -117,6 +147,16 @@"feature"]},+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "New free API: check if a wallet holds a Binance Account Bound Token (BABT)",+ "summary": "GET /api/bnb/babt-check?address=0x... tells you whether a BSC address holds a BABT — Binance's non-transferable, KYC-backed on-chain token. It's a real, live signal (1.16M+ holders on BSC mainnet) that developers can use as a free, no-signup uniqueness check for allowlists, anti-sybil gating, or airdrop targeting on BNB Chain.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-08","type": "update",@@ -138,6 +178,16 @@"infra"]},+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "The free crypto API goes deeper: CoinGecko, DefiLlama, and two new DeFi price feeds",+ "summary": "The unified /api/v1/x crypto API grew from 4 to 12 endpoints across CoinGecko and DefiLlama, all free with zero setup. CoinGecko now answers a full per-coin snapshot (price, ATH/ATL, supply, multi-window change), trending coins and hot categories, token price by contract address, the global market snapshot, and OHLC candles — not just spot price and ranked markets. DefiLlama adds every chain ranked by TVL, one protocol's full profile with 30 days of TVL history, and 90 days of historical chain TVL. Two new providers ride DefiLlama's sibling APIs: llama-prices for any chain:address token (covers long-tail tokens CoinGecko and Jupiter don't index) and llama-stablecoins for every tracked stablecoin's peg, price, and circulating supply.",+ "link": "/docs/api-reference",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-08","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex e233ea6c9..a4da4fa8c 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<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>BNB Chain — Three Genuinely-Unique Demos</title>+ <link>https://three.ws/bnb</link>+ <guid isPermaLink="false">2026-07-08:BNB Chain — Three Genuinely-Unique Demos</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.</description>+ </item><item><title>Crypto Categories by Market Cap</title><link>https://three.ws/categories</link>@@ -86,6 +94,22 @@<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>BNB Chain hub: three uniquely-BNB demos in one place</title>+ <link>https://three.ws/bnb</link>+ <guid isPermaLink="false">2026-07-08:BNB Chain hub: three uniquely-BNB demos in one place</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>New /bnb landing page tells the whole BNB Chain story: gasless agent onboarding (a zero-balance wallet mints an on-chain identity, no faucet), an on-chain-gated 3D vault backed by Greenfield storage permissions, and a real-time on-chain world riding BNB's ~0.45s blocks — each claim traced to what we independently verified live, never BNB's own roadmap promises. The page embeds a live block-time widget that measures the real average off a public RPC on every load, and each feature card auto-detects whether its track has actually shipped on this deployment, showing an honest "coming soon" instead of a dead link until it has.</description>+ </item>+ <item>+ <title>Give your agent a 3D body in one call — the new Embodiment endpoint</title>+ <link>https://three.ws/docs/embody</link>+ <guid isPermaLink="false">2026-07-08:Give your agent a 3D body in one call — the new Embodiment endpoint</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Any AI agent can now buy itself a real presence in a single USDC payment: POST a name plus a text description (or a reference photo) to the new Embodiment endpoint and get back a rigged, animated, talking 3D avatar, a durable persona id that reloads in any future session, and a one-tag embed snippet for any website. It's the same free generate-and-rig chain that powers the 3D Studio, packaged as one paid call — no separate rigging step, no account. Generation failures never settle, so a buyer is only ever charged for a finished body.</description>+ </item><item><title>Markets goes deep — Screener, Categories, Exchanges, Derivatives, Converter, DeFi, Chains, Stablecoins</title><link>https://three.ws/screener</link>@@ -94,6 +118,14 @@<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 free API: check if a wallet holds a Binance Account Bound Token (BABT)</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-08:New free API: check if a wallet holds a Binance Account Bound Token (BABT)</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>GET /api/bnb/babt-check?address=0x... tells you whether a BSC address holds a BABT — Binance's non-transferable, KYC-backed on-chain token. It's a real, live signal (1.16M+ holders on BSC mainnet) that developers can use as a free, no-signup uniqueness check for allowlists, anti-sybil gating, or airdrop targeting on BNB Chain.</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>@@ -110,6 +142,14 @@<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 free crypto API goes deeper: CoinGecko, DefiLlama, and two new DeFi price feeds</title>+ <link>https://three.ws/docs/api-reference</link>+ <guid isPermaLink="false">2026-07-08:The free crypto API goes deeper: CoinGecko, DefiLlama, and two new DeFi price feeds</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The unified /api/v1/x crypto API grew from 4 to 12 endpoints across CoinGecko and DefiLlama, all free with zero setup. CoinGecko now answers a full per-coin snapshot (price, ATH/ATL, supply, multi-window change), trending coins and hot categories, token price by contract address, the global market snapshot, and OHLC candles — not just spot price and ranked markets. DefiLlama adds every chain ranked by TVL, one protocol's full profile with 30 days of TVL history, and 90 days of historical chain TVL. Two new providers ride DefiLlama's sibling APIs: llama-prices for any chain:address token (covers long-tail tokens CoinGecko and Jupiter don't index) and llama-stablecoins for every tracked stablecoin's peg, price, and circulating supply.</description>+ </item><item><title>The three.ws crypto API now has a real free tier</title><link>https://three.ws/docs/api-reference</link>diff --git a/public/docs/spatial-mcp.md b/public/docs/spatial-mcp.mdnew file mode 100644index 000000000..97e53c5dd--- /dev/null+++ b/public/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`](https://github.com/nirholas/three.ws/blob/main/specs/SPATIAL_MCP.md) (v0.1, CC0)+- **Validator (code):** [`api/_lib/spatial-mcp.js`](https://github.com/nirholas/three.ws/blob/main/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`](https://github.com/nirholas/three.ws/blob/main/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/public/features.json b/public/features.jsonindex 9bd689253..7b0b17212 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T00:51:31.590Z",+ "generated_at": "2026-07-08T00:57:16.867Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1516,6 +1516,16 @@"tags": [],"showcase": false},+ {+ "path": "/bnb",+ "title": "BNB Chain — Three Genuinely-Unique Demos",+ "description": "The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.",+ "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 3a8dabbd9..576741a20 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -921,6 +921,12 @@ URL: https://three.ws/stablecoinsEvery 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.+### BNB Chain — Three Genuinely-Unique Demos++URL: https://three.ws/bnb++The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.+### watsonx ConstellationURL: https://three.ws/constellationdiff --git a/public/llms.txt b/public/llms.txtindex 755ed801b..66c0297cd 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -169,6 +169,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [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.+- [BNB Chain — Three Genuinely-Unique Demos](https://three.ws/bnb): The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.- [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 457430fb2..ae0cb72fd 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -145,6 +145,11 @@ export const NAV_GROUPS = [href: '/labs',desc: 'Hidden gems — experimental, advanced surfaces most people never find',},+ {+ title: 'BNB Chain',+ href: '/bnb',+ desc: 'Gasless agent onboarding, an on-chain vault, and a real-time on-chain world — live 0.45s block proof',+ },{title: 'All pages',href: '/sitemap',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex b5d7d854f..c250c2c62 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 401 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 402 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 401 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 402 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>@@ -704,7 +704,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>94</span></h2>+ <h2>Crypto<span class="sm-count" data-count>95</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -1163,6 +1163,13 @@<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="/bnb">+ <span class="sm-title">BNB Chain — Three Genuinely-Unique Demos</span>+ <span class="sm-path">/bnb</span>+ <span class="sm-desc">The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.</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.htmlindex eccf6cfd5..fee6ced0f 100644--- a/public/spatial-mcp/index.html+++ b/public/spatial-mcp/index.html@@ -34,7 +34,7 @@<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>.+ Spec: <a href="https://github.com/nirholas/three.ws/blob/main/specs/SPATIAL_MCP.md">SPATIAL_MCP.md</a>.</p><div class="grid">diff --git a/specs/x402-mpp-bridge.md b/specs/x402-mpp-bridge.mdnew file mode 100644index 000000000..6c2473538--- /dev/null+++ b/specs/x402-mpp-bridge.md@@ -0,0 +1,107 @@+# Spec: x402 ↔ MPP bridge++Status: **active**. Contract version: 1. Load-bearing for `api/_lib/bnb/mpp-server.js`,+`api/_lib/bnb/mpp-buyer.js`, and any endpoint that advertises both x402 and MPP.++This is a contract, not a tutorial (for a walkthrough see+[`docs/bnb-payments.md`](../docs/bnb-payments.md)). It pins the wire-level+relationship between the x402 our catalog already speaks and BNB Chain's MPP.++## 1. Protocol identity++MPP's `b402` layer is **x402 v2** (`x402Version === 2`), CDP wire-shape+compatible. There is no separate envelope: the `402` body, the `X-PAYMENT`+request header, and the `X-PAYMENT-RESPONSE` receipt header are identical to+x402 v2. A "dual-protocol" endpoint therefore does not run two payment stacks —+it advertises additional `accepts[]` entries and routes settlement by network.++## 2. Credential mapping++| Credential | x402 (Solana/Base) | MPP (BNB Chain) | Bridged by this repo |+|---|---|---|---|+| EIP-3009 `transferWithAuthorization` | Base (`eip155:8453`) | `eip155:56` / `eip155:97` | **yes** — same primitive, different network/facilitator |+| `permit2-exact` | — | b402 | parseable, not settled here (documented gap) |+| Solana signed `VersionedTransaction` | Solana | — | n/a |++The bridge is **EIP-3009-only**. A b402 `permit2` signature can never double as+an x402 EIP-3009 credential and vice-versa. `mpp-server.js` rejects any non-eip3009+payload on the MPP path with `unsupported_credential` (HTTP 400); `mpp-buyer.js`+refuses to pay a BNB offer that is not eip3009 (`code: 'unsupported_credential'`).++## 3. Network routing (the dispatch rule)++A payment is an **MPP payment** iff its `accepted.network` is a BNB network:++```+MPP_NETWORKS = { bscMainnet: 'eip155:56', bscTestnet: 'eip155:97' }+```++- Server: `looksLikeMppPayment(req)` decodes `X-PAYMENT` and returns true only for+ these networks. A dual-protocol endpoint routes true → `mpp-server.js`+ (b402 facilitator); everything else (Solana, Base, no payment) → the existing+ x402 handler, untouched.+- Buyer: `mpp-buyer.js` only selects `accepts[]` entries whose network is in+ `MPP_BUYER_NETWORKS = ['eip155:56','eip155:97']`.++## 4. Header precedence++There is exactly one `X-PAYMENT` header, so precedence is by **network**, not by+header name:++1. Decode `X-PAYMENT`. If it fails to decode → the endpoint's x402 handler owns+ the request (it may still be a valid x402 payment in another shape).+2. If it decodes to a BNB network → MPP path. The x402 handler is **not** invoked.+3. If it decodes to a non-BNB network → x402 path. The MPP path is **not** invoked.+4. No `X-PAYMENT` → x402 path emits its 402 menu. A dual-protocol endpoint MAY+ also advertise an MPP `accepts[]` entry in that menu and SHOULD set the+ `X-Accept-Payment-MPP: <route>` discovery header.++An endpoint MUST NOT settle the same request on both rails. On the MPP path the+settle order is **verify (off-chain, free) → run the resource → settle+(on-chain)**, mirroring x402, so a failed request never moves funds.++## 5. Requirement pinning (security)++`X-PAYMENT` is attacker-controlled. Before any facilitator call, `mpp-server.js`:++1. Full-shape-gates the decoded payload (`isEip3009PaymentPayload`).+2. Pins every buyer-echoed field to the server's own requirements —+ `network`, `asset`, `payTo`, `amount`, `scheme` must all match. A+ self-consistent payload naming a different recipient/asset/amount is rejected+ **locally** (`offer_mismatch`, HTTP 400), never forwarded.+3. Recovers the payer (`recoverEip3009Payer`) and requires it to equal+ `authorization.from`.++## 6. Replay guarantees++Each EIP-3009 credential carries a single-use 32-byte nonce. `mpp-server.js`+reserves `mpp:nonce:<network>:<asset>:<nonce>` in Redis with `SET NX PX` (15 min+TTL) at verify time; a second presentation returns `replay` (HTTP 409). When+Redis is unavailable it falls back to a process-local guard — defence in depth+only, because the on-chain EIP-3009 nonce is itself single-use, so a landed+transfer can never be doubled even if the off-chain guard is bypassed.++## 7. Settlement outcomes (the caller's state machine)++| Result | HTTP | Meaning |+|---|---|---|+| `ok:true` | 200 | settled; `X-PAYMENT-RESPONSE` attached |+| `no_payment` | 402 | no `X-PAYMENT`; return the challenge |+| `unsupported_credential` / `wrong_network` / `offer_mismatch` / `bad_signature` | 400 | rejected before settle; no funds moved |+| `replay` | 409 | credential already used |+| `verify_failed` / `settle_failed` | 402 | facilitator declined |+| `mpp_not_configured` | 503 | verified but `B402_*` merchant creds absent — no receipt fabricated |+| `facilitator_unreachable` | 502 | settle-phase transport error → state UNKNOWN; **reconcile on-chain** before treating as unpaid |++A 502 from the settle phase is the one non-idempotent case: b402 may already have+broadcast the transfer. The nonce is single-use, so a buyer retry is value-safe,+but the merchant MUST reconcile on-chain rather than assume the payment is absent.++## 8. Referenced code paths++- `api/_lib/bnb/mpp-server.js` — `mppRequirements`, `mppChallenge`, `mppVerify`,+ `mppSettle`, `looksLikeMppPayment`, replay guard.+- `api/_lib/bnb/mpp-buyer.js` — `mppFetch`, `selectRequirement`, cap enforcement.+- `api/x402/three-intel.js` — the reference dual-protocol endpoint.+- `@bnb-chain/mpp/b402` — the shared x402 v2 primitives (`buildEip3009Payment`,+ `decodeXPayment`, `recoverEip3009Payer`, `B402Client`).diff --git a/src/coin-pages.css b/src/coin-pages.cssindex 3cae911a2..58d512d24 100644--- a/src/coin-pages.css+++ b/src/coin-pages.css@@ -14,7 +14,9 @@font-weight: 200 900;font-display: swap;src: url('/fonts/source-serif-4-latin.woff2') format('woff2');- unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+ unicode-range:+ U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074,+ U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;}@font-face {font-family: 'Source Serif 4';@@ -22,7 +24,9 @@font-weight: 200 900;font-display: swap;src: url('/fonts/source-serif-4-latin-ext.woff2') format('woff2');- unicode-range: U+0100-02AF, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;+ unicode-range:+ U+0100-02AF, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1E00-1EFF, U+2020,+ U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;}:root {@@ -39,8 +43,16 @@--cv-max-width: 1280px;--cv-content-padding: 1rem;}-@media (min-width: 768px) { :root { --cv-content-padding: 1.5rem; } }-@media (min-width: 1024px) { :root { --cv-content-padding: 2rem; } }+@media (min-width: 768px) {+ :root {+ --cv-content-padding: 1.5rem;+ }+}+@media (min-width: 1024px) {+ :root {+ --cv-content-padding: 2rem;+ }+}/* Light — the design's default palette. */html[data-theme='light'] {@@ -61,12 +73,15 @@ html[data-theme='light'] {--cv-chart-green: #22c55e;--cv-chart-red: #ef4444;--cv-shadow-card: 0 0 0 1px rgb(0 0 0 / 0.03), 0 2px 4px 0 rgb(0 0 0 / 0.04);- --cv-shadow-card-hover: 0 0 0 1px rgb(0 0 0 / 0.04), 0 8px 16px -4px rgb(0 0 0 / 0.08), 0 2px 4px -1px rgb(0 0 0 / 0.04);+ --cv-shadow-card-hover:+ 0 0 0 1px rgb(0 0 0 / 0.04), 0 8px 16px -4px rgb(0 0 0 / 0.08),+ 0 2px 4px -1px rgb(0 0 0 / 0.04);--cv-shadow-dropdown: 0 4px 24px -4px rgb(0 0 0 / 0.12), 0 8px 16px -8px rgb(0 0 0 / 0.08);}/* Dark — the design's .dark token set. */-html[data-theme='dark'], html:not([data-theme='light']) {+html[data-theme='dark'],+html:not([data-theme='light']) {--cv-accent: #60a5fa;--cv-accent-hover: #93bbfc;--cv-surface: #09090b;@@ -88,7 +103,8 @@ html[data-theme='dark'], html:not([data-theme='light']) {--cv-shadow-dropdown: 0 4px 24px -4px rgb(0 0 0 / 0.6), 0 8px 16px -8px rgb(0 0 0 / 0.5);}-html.cv-page, .cv-page body {+html.cv-page,+.cv-page body {background: var(--cv-surface);color: var(--cv-text);}@@ -129,7 +145,11 @@ html.cv-page, .cv-page body {color: var(--cv-text);margin: 0 0 0.5rem;}-@media (min-width: 768px) { .cv-h1 { font-size: 2.25rem; } }+@media (min-width: 768px) {+ .cv-h1 {+ font-size: 2.25rem;+ }+}.cv-h2 {font-family: var(--cv-font-serif);@@ -145,7 +165,10 @@ html.cv-page, .cv-page body {margin: 0 0 2rem;}-.cv-mono { font-family: var(--cv-font-mono); font-variant-numeric: tabular-nums; }+.cv-mono {+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+}/* ── Breadcrumbs ────────────────────────────────────────────────────────── */@@ -158,10 +181,22 @@ html.cv-page, .cv-page body {margin-bottom: 1.5rem;flex-wrap: wrap;}-.cv-crumbs a { color: inherit; text-decoration: none; transition: color 0.15s; }-.cv-crumbs a:hover, .cv-crumbs a:focus-visible { color: var(--cv-accent); }-.cv-crumbs .sep { opacity: 0.7; }-.cv-crumbs .here { color: var(--cv-text); font-weight: 500; }+.cv-crumbs a {+ color: inherit;+ text-decoration: none;+ transition: color 0.15s;+}+.cv-crumbs a:hover,+.cv-crumbs a:focus-visible {+ color: var(--cv-accent);+}+.cv-crumbs .sep {+ opacity: 0.7;+}+.cv-crumbs .here {+ color: var(--cv-text);+ font-weight: 500;+}/* ── Cards ──────────────────────────────────────────────────────────────── */@@ -182,9 +217,14 @@ html.cv-page, .cv-page body {align-items: flex-start;justify-content: space-between;gap: 0.75rem;- transition: box-shadow 0.2s, border-color 0.2s;+ transition:+ box-shadow 0.2s,+ border-color 0.2s;+}+.cv-stat-card:hover {+ box-shadow: var(--cv-shadow-card-hover);+ border-color: var(--cv-border-hover);}-.cv-stat-card:hover { box-shadow: var(--cv-shadow-card-hover); border-color: var(--cv-border-hover); }.cv-stat-card .label {font-size: 0.7rem;font-weight: 500;@@ -193,13 +233,34 @@ html.cv-page, .cv-page body {color: var(--cv-text-3);margin: 0 0 0.25rem;}-.cv-stat-card .value { font-size: 1.5rem; font-weight: 700; color: var(--cv-text); margin: 0; }-.cv-stat-card .delta { margin: 0.25rem 0 0; font-size: 0.875rem; font-weight: 500; }-.cv-stat-card .icon { color: var(--cv-accent); opacity: 0.6; flex-shrink: 0; }-.cv-stat-card .icon svg { width: 1.25rem; height: 1.25rem; display: block; }+.cv-stat-card .value {+ font-size: 1.5rem;+ font-weight: 700;+ color: var(--cv-text);+ margin: 0;+}+.cv-stat-card .delta {+ margin: 0.25rem 0 0;+ font-size: 0.875rem;+ font-weight: 500;+}+.cv-stat-card .icon {+ color: var(--cv-accent);+ opacity: 0.6;+ flex-shrink: 0;+}+.cv-stat-card .icon svg {+ width: 1.25rem;+ height: 1.25rem;+ display: block;+}-.cv-up { color: var(--cv-green); }-.cv-down { color: var(--cv-red); }+.cv-up {+ color: var(--cv-green);+}+.cv-down {+ color: var(--cv-red);+}/* Smaller stat tiles on the detail page's Market Stats grid. */.cv-mini-stat {@@ -208,53 +269,130 @@ html.cv-page, .cv-page body {border-radius: var(--cv-radius-md);padding: 1rem;}-.cv-mini-stat .label { font-size: 0.75rem; color: var(--cv-text-3); margin: 0 0 0.25rem; }-.cv-mini-stat .value { font-size: 1.125rem; font-weight: 600; color: var(--cv-text); margin: 0; }-.cv-mini-stat .value.green { color: var(--cv-green); }-.cv-mini-stat .value.red { color: var(--cv-red); }-.cv-mini-stat .sub { font-size: 0.75rem; color: var(--cv-text-3); margin: 0.125rem 0 0; }+.cv-mini-stat .label {+ font-size: 0.75rem;+ color: var(--cv-text-3);+ margin: 0 0 0.25rem;+}+.cv-mini-stat .value {+ font-size: 1.125rem;+ font-weight: 600;+ color: var(--cv-text);+ margin: 0;+}+.cv-mini-stat .value.green {+ color: var(--cv-green);+}+.cv-mini-stat .value.red {+ color: var(--cv-red);+}+.cv-mini-stat .sub {+ font-size: 0.75rem;+ color: var(--cv-text-3);+ margin: 0.125rem 0 0;+}/* ── Coin header (detail page) ──────────────────────────────────────────── */-.cv-coin-head { display: flex; align-items: flex-start; gap: 1rem; margin-bottom: 2rem; }+.cv-coin-head {+ display: flex;+ align-items: flex-start;+ gap: 1rem;+ margin-bottom: 2rem;+}.cv-coin-head img.coin-icon {- width: 64px; height: 64px; border-radius: 50%; flex-shrink: 0;+ width: 64px;+ height: 64px;+ border-radius: 50%;+ flex-shrink: 0;background: var(--cv-surface-3);}-.cv-coin-head .title-row { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; }+.cv-coin-head .title-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem;+}.cv-coin-head h1 {font-family: var(--cv-font-serif);- font-size: 1.875rem; font-weight: 700; margin: 0; color: var(--cv-text);+ font-size: 1.875rem;+ font-weight: 700;+ margin: 0;+ color: var(--cv-text);+}+@media (min-width: 768px) {+ .cv-coin-head h1 {+ font-size: 2.25rem;+ }}-@media (min-width: 768px) { .cv-coin-head h1 { font-size: 2.25rem; } }.cv-coin-head .ticker {- font-size: 1.25rem; font-weight: 500; text-transform: uppercase; color: var(--cv-text-3);+ font-size: 1.25rem;+ font-weight: 500;+ text-transform: uppercase;+ color: var(--cv-text-3);+}+@media (min-width: 768px) {+ .cv-coin-head .ticker {+ font-size: 1.5rem;+ }}-@media (min-width: 768px) { .cv-coin-head .ticker { font-size: 1.5rem; } }.cv-rank-badge {- display: inline-flex; align-items: center;- background: var(--cv-accent); color: #fff;- border-radius: 999px; padding: 0.25rem 0.625rem;- font-size: 0.75rem; font-weight: 600;+ display: inline-flex;+ align-items: center;+ background: var(--cv-accent);+ color: #fff;+ border-radius: 999px;+ padding: 0.25rem 0.625rem;+ font-size: 0.75rem;+ font-weight: 600;}-.cv-price-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 1rem; margin-top: 0.75rem; }+.cv-price-row {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 1rem;+ margin-top: 0.75rem;+}.cv-price {- font-size: 2.25rem; font-weight: 700; color: var(--cv-text);+ font-size: 2.25rem;+ font-weight: 700;+ color: var(--cv-text);font-variant-numeric: tabular-nums;}-@media (min-width: 768px) { .cv-price { font-size: 3rem; } }-.cv-today { color: var(--cv-text-3); font-size: 0.875rem; margin: 0.375rem 0 0; }+@media (min-width: 768px) {+ .cv-price {+ font-size: 3rem;+ }+}+.cv-today {+ color: var(--cv-text-3);+ font-size: 0.875rem;+ margin: 0.375rem 0 0;+}.cv-chip {- display: inline-flex; align-items: center; gap: 0.25rem;- border-radius: var(--cv-radius); padding: 0.125rem 0.5rem;- font-size: 0.75rem; font-weight: 500;+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ border-radius: var(--cv-radius);+ padding: 0.125rem 0.5rem;+ font-size: 0.75rem;+ font-weight: 500;font-variant-numeric: tabular-nums;}-.cv-chip .win { font-size: 10px; opacity: 0.85; }-.cv-chip.up { background: var(--cv-green-soft); color: var(--cv-green); }-.cv-chip.down { background: var(--cv-red-soft); color: var(--cv-red); }+.cv-chip .win {+ font-size: 10px;+ opacity: 0.85;+}+.cv-chip.up {+ background: var(--cv-green-soft);+ color: var(--cv-green);+}+.cv-chip.down {+ background: var(--cv-red-soft);+ color: var(--cv-red);+}/* ── Chart panel ────────────────────────────────────────────────────────── */@@ -266,122 +404,279 @@ html.cv-page, .cv-page body {padding: 1rem;margin-bottom: 2.5rem;}-@media (min-width: 768px) { .cv-chart-panel { padding: 1.5rem; } }+@media (min-width: 768px) {+ .cv-chart-panel {+ padding: 1.5rem;+ }+}.cv-chart-bar {- display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between;- gap: 0.5rem; margin-bottom: 1rem;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ margin-bottom: 1rem;+}+.cv-chart-bar .left {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}+.cv-chart-bar .title {+ font-size: 0.875rem;+ font-weight: 500;+ color: var(--cv-text-2);+}+.cv-chart-bar .pct {+ font-size: 0.875rem;+ font-weight: 600;}-.cv-chart-bar .left { display: flex; align-items: center; gap: 0.5rem; }-.cv-chart-bar .title { font-size: 0.875rem; font-weight: 500; color: var(--cv-text-2); }-.cv-chart-bar .pct { font-size: 0.875rem; font-weight: 600; }-.cv-ranges { display: flex; gap: 0.25rem; }+.cv-ranges {+ display: flex;+ gap: 0.25rem;+}.cv-range-btn {- appearance: none; border: 0; background: transparent; cursor: pointer;- border-radius: var(--cv-radius); padding: 0.375rem 0.75rem;- font-size: 0.75rem; font-weight: 500; font-family: inherit;+ appearance: none;+ border: 0;+ background: transparent;+ cursor: pointer;+ border-radius: var(--cv-radius);+ padding: 0.375rem 0.75rem;+ font-size: 0.75rem;+ font-weight: 500;+ font-family: inherit;color: var(--cv-text-2);- transition: background 0.15s, color 0.15s;+ transition:+ background 0.15s,+ color 0.15s;+}+.cv-range-btn:hover {+ background: var(--cv-surface-2);+}+.cv-range-btn[aria-pressed='true'] {+ background: var(--cv-accent);+ color: #fff;+}+.cv-range-btn:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;}-.cv-range-btn:hover { background: var(--cv-surface-2); }-.cv-range-btn[aria-pressed='true'] { background: var(--cv-accent); color: #fff; }-.cv-range-btn:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: 2px; }-.cv-chart-area { position: relative; }-.cv-chart-area svg { width: 100%; height: auto; display: block; user-select: none; }+.cv-chart-area {+ position: relative;+}+.cv-chart-area svg {+ width: 100%;+ height: auto;+ display: block;+ user-select: none;+}.cv-chart-state {- height: 300px; display: flex; align-items: center; justify-content: center;- color: var(--cv-text-3); gap: 0.5rem; font-size: 0.875rem;+ height: 300px;+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--cv-text-3);+ gap: 0.5rem;+ font-size: 0.875rem;}.cv-spinner {- width: 1rem; height: 1rem; border-radius: 50%;- border: 2px solid currentcolor; border-top-color: transparent;+ width: 1rem;+ height: 1rem;+ border-radius: 50%;+ border: 2px solid currentcolor;+ border-top-color: transparent;animation: cvSpin 0.8s linear infinite;}-@keyframes cvSpin { to { transform: rotate(360deg); } }+@keyframes cvSpin {+ to {+ transform: rotate(360deg);+ }+}.cv-chart-tip {- position: absolute; top: 0; z-index: 10; pointer-events: none;+ position: absolute;+ top: 0;+ z-index: 10;+ pointer-events: none;transform: translateX(-50%);- background: var(--cv-surface); border: 1px solid var(--cv-border);- border-radius: var(--cv-radius-md); box-shadow: var(--cv-shadow-dropdown);- padding: 0.5rem 0.75rem; font-size: 0.75rem; white-space: nowrap;+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ box-shadow: var(--cv-shadow-dropdown);+ padding: 0.5rem 0.75rem;+ font-size: 0.75rem;+ white-space: nowrap;+}+.cv-chart-tip .p {+ font-weight: 600;+ color: var(--cv-text);+ margin: 0;+}+.cv-chart-tip .d {+ color: var(--cv-text-3);+ margin: 0;}-.cv-chart-tip .p { font-weight: 600; color: var(--cv-text); margin: 0; }-.cv-chart-tip .d { color: var(--cv-text-3); margin: 0; }/* ── Stats grid ─────────────────────────────────────────────────────────── */-.cv-stats-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 0.75rem; }-@media (min-width: 768px) { .cv-stats-grid { grid-template-columns: repeat(4, 1fr); } }+.cv-stats-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.75rem;+}+@media (min-width: 768px) {+ .cv-stats-grid {+ grid-template-columns: repeat(4, 1fr);+ }+}-.cv-section { margin-bottom: 2.5rem; }+.cv-section {+ margin-bottom: 2.5rem;+}/* ── News cards ─────────────────────────────────────────────────────────── */-.cv-news-grid { display: grid; gap: 1rem; }-@media (min-width: 640px) { .cv-news-grid { grid-template-columns: repeat(2, 1fr); } }+.cv-news-grid {+ display: grid;+ gap: 1rem;+}+@media (min-width: 640px) {+ .cv-news-grid {+ grid-template-columns: repeat(2, 1fr);+ }+}.cv-news-card {- display: flex; gap: 0.875rem; align-items: flex-start;- background: var(--cv-surface); border: 1px solid var(--cv-border);- border-radius: var(--cv-radius-lg); box-shadow: var(--cv-shadow-card);- padding: 0.875rem; text-decoration: none;- transition: box-shadow 0.2s, border-color 0.2s, transform 0.2s;-}-.cv-news-card:hover, .cv-news-card:focus-visible {+ display: flex;+ gap: 0.875rem;+ align-items: flex-start;+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ box-shadow: var(--cv-shadow-card);+ padding: 0.875rem;+ text-decoration: none;+ transition:+ box-shadow 0.2s,+ border-color 0.2s,+ transform 0.2s;+}+.cv-news-card:hover,+.cv-news-card:focus-visible {box-shadow: var(--cv-shadow-card-hover);border-color: var(--cv-border-hover);transform: translateY(-1px);}.cv-news-card img {- width: 72px; height: 72px; border-radius: var(--cv-radius-md);- object-fit: cover; flex-shrink: 0; background: var(--cv-surface-3);+ width: 72px;+ height: 72px;+ border-radius: var(--cv-radius-md);+ object-fit: cover;+ flex-shrink: 0;+ background: var(--cv-surface-3);}.cv-news-card .t {- font-weight: 600; color: var(--cv-text); font-size: 0.875rem; line-height: 1.4;+ font-weight: 600;+ color: var(--cv-text);+ font-size: 0.875rem;+ line-height: 1.4;margin: 0 0 0.25rem;- display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.cv-news-card .m {+ font-size: 0.75rem;+ color: var(--cv-text-3);+ margin: 0;+}+.cv-news-card .m .src {+ color: var(--cv-accent);+ font-weight: 500;}-.cv-news-card .m { font-size: 0.75rem; color: var(--cv-text-3); margin: 0; }-.cv-news-card .m .src { color: var(--cv-accent); font-weight: 500; }/* ── About / prose ──────────────────────────────────────────────────────── */-.cv-prose { color: var(--cv-text-2); font-size: 0.9375rem; max-width: none; }-.cv-prose p { margin: 0 0 0.875rem; }-.cv-prose p:last-child { margin-bottom: 0; }+.cv-prose {+ color: var(--cv-text-2);+ font-size: 0.9375rem;+ max-width: none;+}+.cv-prose p {+ margin: 0 0 0.875rem;+}+.cv-prose p:last-child {+ margin-bottom: 0;+}/* ── Link pills ─────────────────────────────────────────────────────────── */-.cv-pills { display: flex; flex-wrap: wrap; gap: 0.5rem; }+.cv-pills {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+}.cv-pill {- display: inline-flex; align-items: center; gap: 0.25rem;- border: 1px solid var(--cv-border); border-radius: 999px;- padding: 0.375rem 0.75rem; font-size: 0.875rem;- color: var(--cv-text-2); text-decoration: none;- transition: background 0.15s, border-color 0.15s, color 0.15s;+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ border: 1px solid var(--cv-border);+ border-radius: 999px;+ padding: 0.375rem 0.75rem;+ font-size: 0.875rem;+ color: var(--cv-text-2);+ text-decoration: none;+ transition:+ background 0.15s,+ border-color 0.15s,+ color 0.15s;+}+.cv-pill:hover,+.cv-pill:focus-visible {+ background: var(--cv-surface-2);+ border-color: var(--cv-border-hover);+ color: var(--cv-text);}-.cv-pill:hover, .cv-pill:focus-visible {- background: var(--cv-surface-2); border-color: var(--cv-border-hover); color: var(--cv-text);+.cv-pill:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;}-.cv-pill:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: 2px; }/* Contract row — mono address + copy affordance. */.cv-contract {- display: inline-flex; align-items: center; gap: 0.5rem;- border: 1px solid var(--cv-border); border-radius: var(--cv-radius-md);- background: var(--cv-surface-2); padding: 0.375rem 0.625rem;- font-family: var(--cv-font-mono); font-size: 0.8125rem; color: var(--cv-text-2);+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ background: var(--cv-surface-2);+ padding: 0.375rem 0.625rem;+ font-family: var(--cv-font-mono);+ font-size: 0.8125rem;+ color: var(--cv-text-2);}.cv-contract button {- appearance: none; border: 0; background: transparent; cursor: pointer;- color: var(--cv-accent); font-size: 0.75rem; font-family: var(--cv-font-sans);- padding: 0.125rem 0.25rem; border-radius: var(--cv-radius-sm);+ appearance: none;+ border: 0;+ background: transparent;+ cursor: pointer;+ color: var(--cv-accent);+ font-size: 0.75rem;+ font-family: var(--cv-font-sans);+ padding: 0.125rem 0.25rem;+ border-radius: var(--cv-radius-sm);+}+.cv-contract button:hover {+ color: var(--cv-accent-hover);+}+.cv-contract button:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 1px;}-.cv-contract button:hover { color: var(--cv-accent-hover); }-.cv-contract button:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: 1px; }/* ── Market table (/coins) ──────────────────────────────────────────────── */@@ -392,22 +687,46 @@ html.cv-page, .cv-page body {-webkit-overflow-scrolling: touch;background: var(--cv-surface);}-.cv-table { width: 100%; min-width: 540px; border-collapse: collapse; font-size: 0.875rem; }+.cv-table {+ width: 100%;+ min-width: 540px;+ border-collapse: collapse;+ font-size: 0.875rem;+}.cv-table th {- position: sticky; top: 0;+ position: sticky;+ top: 0;background: var(--cv-surface);border-bottom: 1px solid var(--cv-border);padding: 0.75rem 1rem;- font-weight: 500; color: var(--cv-text-2);- white-space: nowrap; cursor: pointer; user-select: none;+ font-weight: 500;+ color: var(--cv-text-2);+ white-space: nowrap;+ cursor: pointer;+ user-select: none;transition: color 0.15s;text-align: right;}-.cv-table th:hover { color: var(--cv-text); }-.cv-table th:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: -2px; }-.cv-table th.left, .cv-table td.left { text-align: left; }-.cv-table th .arrow { display: inline-block; margin-left: 0.25rem; opacity: 0.4; font-size: 0.6875rem; }-.cv-table th[aria-sort] .arrow { opacity: 1; }+.cv-table th:hover {+ color: var(--cv-text);+}+.cv-table th:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: -2px;+}+.cv-table th.left,+.cv-table td.left {+ text-align: left;+}+.cv-table th .arrow {+ display: inline-block;+ margin-left: 0.25rem;+ opacity: 0.4;+ font-size: 0.6875rem;+}+.cv-table th[aria-sort] .arrow {+ opacity: 1;+}.cv-table td {padding: 0.75rem 1rem;@@ -417,135 +736,311 @@ html.cv-page, .cv-page body {white-space: nowrap;transition: background 0.15s;}-.cv-table tbody tr { cursor: pointer; }-.cv-table tbody tr:last-child td { border-bottom: 0; }-.cv-table tbody tr:hover td, .cv-table tbody tr:focus-within td { background: var(--cv-surface-2); }+.cv-table tbody tr {+ cursor: pointer;+}+.cv-table tbody tr:last-child td {+ border-bottom: 0;+}+.cv-table tbody tr:hover td,+.cv-table tbody tr:focus-within td {+ background: var(--cv-surface-2);+}-.cv-table .rank { color: var(--cv-text-2); }-.cv-table .name-cell { position: sticky; left: 0; z-index: 5; }-.cv-table .name-cell .inner { display: flex; align-items: center; gap: 0.5rem; }-.cv-table .name-cell img { width: 24px; height: 24px; border-radius: 50%; flex-shrink: 0; background: var(--cv-surface-3); }+.cv-table .rank {+ color: var(--cv-text-2);+}+.cv-table .name-cell {+ position: sticky;+ left: 0;+ z-index: 5;+}+.cv-table .name-cell .inner {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}+.cv-table .name-cell img {+ width: 24px;+ height: 24px;+ border-radius: 50%;+ flex-shrink: 0;+ background: var(--cv-surface-3);+}.cv-table .name-cell .nm {- font-weight: 500; color: var(--cv-text);- max-width: 140px; overflow: hidden; text-overflow: ellipsis;+ font-weight: 500;+ color: var(--cv-text);+ max-width: 140px;+ overflow: hidden;+ text-overflow: ellipsis;+}+.cv-table .name-cell .sym {+ text-transform: uppercase;+ color: var(--cv-text-3);+ font-size: 0.75rem;+}+.cv-table .name-cell a {+ text-decoration: none;+ color: inherit;+ display: block;+}+.cv-table .name-cell a:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+ border-radius: var(--cv-radius-sm);+}+.cv-table .price {+ font-family: var(--cv-font-mono);+ color: var(--cv-text);+ font-variant-numeric: tabular-nums;+}+.cv-table .pct {+ font-family: var(--cv-font-mono);+ font-variant-numeric: tabular-nums;+}+.cv-table .dim {+ color: var(--cv-text-2);}-.cv-table .name-cell .sym { text-transform: uppercase; color: var(--cv-text-3); font-size: 0.75rem; }-.cv-table .name-cell a { text-decoration: none; color: inherit; display: block; }-.cv-table .name-cell a:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: 2px; border-radius: var(--cv-radius-sm); }-.cv-table .price { font-family: var(--cv-font-mono); color: var(--cv-text); font-variant-numeric: tabular-nums; }-.cv-table .pct { font-family: var(--cv-font-mono); font-variant-numeric: tabular-nums; }-.cv-table .dim { color: var(--cv-text-2); }@media (max-width: 639px) {- .cv-table .hide-sm { display: none; }- .cv-table .name-cell .sym { display: none; }+ .cv-table .hide-sm {+ display: none;+ }+ .cv-table .name-cell .sym {+ display: none;+ }+}+@media (max-width: 767px) {+ .cv-table .hide-md {+ display: none;+ }+}+@media (max-width: 1023px) {+ .cv-table .hide-lg {+ display: none;+ }+}+@media (max-width: 1279px) {+ .cv-table .hide-xl {+ display: none;+ }}-@media (max-width: 767px) { .cv-table .hide-md { display: none; } }-@media (max-width: 1023px) { .cv-table .hide-lg { display: none; } }-@media (max-width: 1279px) { .cv-table .hide-xl { display: none; } }/* ── Search (type-ahead) ────────────────────────────────────────────────── */-.cv-search { position: relative; max-width: 22rem; flex: 1 1 16rem; }+.cv-search {+ position: relative;+ max-width: 22rem;+ flex: 1 1 16rem;+}.cv-search input {width: 100%;background: var(--cv-surface);border: 1px solid var(--cv-border);border-radius: var(--cv-radius-md);color: var(--cv-text);- font: inherit; font-size: 0.875rem;+ font: inherit;+ font-size: 0.875rem;padding: 0.5rem 0.75rem 0.5rem 2.125rem;- transition: border-color 0.15s, box-shadow 0.15s;+ transition:+ border-color 0.15s,+ box-shadow 0.15s;+}+.cv-search input::placeholder {+ color: var(--cv-text-3);}-.cv-search input::placeholder { color: var(--cv-text-3); }.cv-search input:focus {- outline: none; border-color: var(--cv-accent);+ outline: none;+ border-color: var(--cv-accent);box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent) 20%, transparent);}.cv-search .mag {- position: absolute; left: 0.625rem; top: 50%; transform: translateY(-50%);- color: var(--cv-text-3); pointer-events: none;+ position: absolute;+ left: 0.625rem;+ top: 50%;+ transform: translateY(-50%);+ color: var(--cv-text-3);+ pointer-events: none;+}+.cv-search .mag svg {+ width: 1rem;+ height: 1rem;+ display: block;}-.cv-search .mag svg { width: 1rem; height: 1rem; display: block; }.cv-search-pop {- position: absolute; top: calc(100% + 0.375rem); left: 0; right: 0; z-index: 40;- background: var(--cv-surface); border: 1px solid var(--cv-border);- border-radius: var(--cv-radius-md); box-shadow: var(--cv-shadow-dropdown);+ position: absolute;+ top: calc(100% + 0.375rem);+ left: 0;+ right: 0;+ z-index: 40;+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ box-shadow: var(--cv-shadow-dropdown);overflow: hidden;}.cv-search-pop a {- display: flex; align-items: center; gap: 0.625rem;- padding: 0.5rem 0.75rem; text-decoration: none;- color: var(--cv-text); font-size: 0.875rem;+ display: flex;+ align-items: center;+ gap: 0.625rem;+ padding: 0.5rem 0.75rem;+ text-decoration: none;+ color: var(--cv-text);+ font-size: 0.875rem;+}+.cv-search-pop a:hover,+.cv-search-pop a[data-active='1'] {+ background: var(--cv-surface-2);+}+.cv-search-pop img {+ width: 20px;+ height: 20px;+ border-radius: 50%;+ background: var(--cv-surface-3);+}+.cv-search-pop .sym {+ color: var(--cv-text-3);+ text-transform: uppercase;+ font-size: 0.75rem;+}+.cv-search-pop .rk {+ margin-left: auto;+ color: var(--cv-text-3);+ font-size: 0.75rem;+}+.cv-search-pop .none {+ padding: 0.75rem;+ color: var(--cv-text-3);+ font-size: 0.875rem;}-.cv-search-pop a:hover, .cv-search-pop a[data-active='1'] { background: var(--cv-surface-2); }-.cv-search-pop img { width: 20px; height: 20px; border-radius: 50%; background: var(--cv-surface-3); }-.cv-search-pop .sym { color: var(--cv-text-3); text-transform: uppercase; font-size: 0.75rem; }-.cv-search-pop .rk { margin-left: auto; color: var(--cv-text-3); font-size: 0.75rem; }-.cv-search-pop .none { padding: 0.75rem; color: var(--cv-text-3); font-size: 0.875rem; }/* ── Toolbar row above the table ────────────────────────────────────────── */.cv-toolbar {- display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between;- gap: 0.75rem; margin-bottom: 1rem;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ margin-bottom: 1rem;}.cv-load-more {- display: block; margin: 1.25rem auto 0;- appearance: none; cursor: pointer; font: inherit; font-size: 0.875rem; font-weight: 500;- background: var(--cv-surface); color: var(--cv-text-2);- border: 1px solid var(--cv-border); border-radius: var(--cv-radius-md);+ display: block;+ margin: 1.25rem auto 0;+ appearance: none;+ cursor: pointer;+ font: inherit;+ font-size: 0.875rem;+ font-weight: 500;+ background: var(--cv-surface);+ color: var(--cv-text-2);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);padding: 0.5rem 1.25rem;- transition: background 0.15s, color 0.15s, border-color 0.15s;+ transition:+ background 0.15s,+ color 0.15s,+ border-color 0.15s;+}+.cv-load-more:hover {+ background: var(--cv-surface-2);+ color: var(--cv-text);+ border-color: var(--cv-border-hover);+}+.cv-load-more:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 2px;+}+.cv-load-more[disabled] {+ opacity: 0.5;+ cursor: default;}-.cv-load-more:hover { background: var(--cv-surface-2); color: var(--cv-text); border-color: var(--cv-border-hover); }-.cv-load-more:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: 2px; }-.cv-load-more[disabled] { opacity: 0.5; cursor: default; }/* ── States ─────────────────────────────────────────────────────────────── */.cv-empty {- border: 1px solid var(--cv-border); border-radius: var(--cv-radius-lg);- background: var(--cv-surface); color: var(--cv-text-2);- padding: 3rem 1.5rem; text-align: center;+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ background: var(--cv-surface);+ color: var(--cv-text-2);+ padding: 3rem 1.5rem;+ text-align: center;+}+.cv-empty a {+ color: var(--cv-accent);}-.cv-empty a { color: var(--cv-accent); }.cv-skel {- position: relative; overflow: hidden;- background: var(--cv-surface-3); border-radius: var(--cv-radius);+ position: relative;+ overflow: hidden;+ background: var(--cv-surface-3);+ border-radius: var(--cv-radius);}.cv-skel::after {- content: ''; position: absolute; inset: 0;+ content: '';+ position: absolute;+ inset: 0;transform: translateX(-100%);- background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--cv-text) 6%, transparent), transparent);+ background: linear-gradient(+ 90deg,+ transparent,+ color-mix(in srgb, var(--cv-text) 6%, transparent),+ transparent+ );animation: cvShimmer 2s infinite;}-@keyframes cvShimmer { 100% { transform: translateX(100%); } }+@keyframes cvShimmer {+ 100% {+ transform: translateX(100%);+ }+}-.cv-updated { color: var(--cv-text-3); font-size: 0.75rem; margin-top: 1rem; }+.cv-updated {+ color: var(--cv-text-3);+ font-size: 0.75rem;+ margin-top: 1rem;+}/* Categories row on the detail page. */-.cv-cats { display: flex; flex-wrap: wrap; gap: 0.375rem; margin-top: 0.625rem; }+.cv-cats {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+ margin-top: 0.625rem;+}.cv-cat {- font-size: 0.6875rem; color: var(--cv-text-2);- background: var(--cv-surface-2); border: 1px solid var(--cv-border);- border-radius: 999px; padding: 0.125rem 0.5rem;+ font-size: 0.6875rem;+ color: var(--cv-text-2);+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: 999px;+ padding: 0.125rem 0.5rem;}@media (prefers-reduced-motion: reduce) {- .cv-skel::after, .cv-spinner { animation: none; }- .cv-news-card, .cv-stat-card, .cv-range-btn { transition: none; }+ .cv-skel::after,+ .cv-spinner {+ animation: none;+ }+ .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;+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;margin: 0 0 2rem;}-.cv-tools .cv-pill { font-size: 0.8125rem; }+.cv-tools .cv-pill {+ font-size: 0.8125rem;+}/* ═══════════════════════════════════════════════════════════════════════════Market tools — /fear-greed, /heatmap, /gas, /compare@@ -555,137 +1050,476 @@ html.cv-page, .cv-page body {/* ── Fear & Greed ───────────────────────────────────────────────────────── */.fg-now-card {- display: flex; flex-wrap: wrap; align-items: center; gap: 2rem;- background: var(--cv-surface); border: 1px solid var(--cv-border);- border-radius: var(--cv-radius-xl); box-shadow: var(--cv-shadow-card);+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 2rem;+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-xl);+ box-shadow: var(--cv-shadow-card);padding: 1.75rem;}-.fg-gauge { position: relative; width: 320px; max-width: 100%; flex: 0 0 auto; }-.fg-gauge-svg { width: 100%; height: auto; display: block; }+.fg-gauge {+ position: relative;+ width: 320px;+ max-width: 100%;+ flex: 0 0 auto;+}+.fg-gauge-svg {+ width: 100%;+ height: auto;+ display: block;+}.fg-gauge-center {- position: absolute; left: 0; right: 0; bottom: 0.5rem;- display: flex; flex-direction: column; align-items: center; text-align: center;+ position: absolute;+ left: 0;+ right: 0;+ bottom: 0.5rem;+ display: flex;+ flex-direction: column;+ align-items: center;+ text-align: center;pointer-events: none;}-.fg-value { font-family: var(--cv-font-mono); font-size: 3rem; font-weight: 700; line-height: 1; }-.fg-label { font-size: 0.9375rem; font-weight: 600; margin-top: 0.25rem; }-.fg-now-meta { flex: 1 1 14rem; min-width: 0; }-.fg-now-title { margin: 0 0 0.5rem; font-size: 1rem; font-weight: 600; color: var(--cv-text); }-.fg-delta { margin: 0 0 0.5rem; font-size: 0.9375rem; font-weight: 500; }-.fg-delta .dim { color: var(--cv-text-3); font-weight: 400; }-.fg-cross { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-top: 1rem; }-.fg-legend-card { padding: 1.5rem; }-.fg-bands { display: grid; gap: 0.5rem; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin: 1rem 0 1.25rem; }-.fg-band { display: flex; align-items: center; gap: 0.5rem; font-size: 0.8125rem; }-.fg-band .swatch { width: 0.875rem; height: 0.875rem; border-radius: 3px; flex: 0 0 auto; }-.fg-band .range { color: var(--cv-text-3); }-.fg-band .name { color: var(--cv-text-2); }+.fg-value {+ font-family: var(--cv-font-mono);+ font-size: 3rem;+ font-weight: 700;+ line-height: 1;+}+.fg-label {+ font-size: 0.9375rem;+ font-weight: 600;+ margin-top: 0.25rem;+}+.fg-now-meta {+ flex: 1 1 14rem;+ min-width: 0;+}+.fg-now-title {+ margin: 0 0 0.5rem;+ font-size: 1rem;+ font-weight: 600;+ color: var(--cv-text);+}+.fg-delta {+ margin: 0 0 0.5rem;+ font-size: 0.9375rem;+ font-weight: 500;+}+.fg-delta .dim {+ color: var(--cv-text-3);+ font-weight: 400;+}+.fg-cross {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ margin-top: 1rem;+}+.fg-legend-card {+ padding: 1.5rem;+}+.fg-bands {+ display: grid;+ gap: 0.5rem;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ margin: 1rem 0 1.25rem;+}+.fg-band {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.8125rem;+}+.fg-band .swatch {+ width: 0.875rem;+ height: 0.875rem;+ border-radius: 3px;+ flex: 0 0 auto;+}+.fg-band .range {+ color: var(--cv-text-3);+}+.fg-band .name {+ color: var(--cv-text-2);+}/* ── Heatmap ────────────────────────────────────────────────────────────── */.hm-toolbar {- display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem;margin-bottom: 1rem;}-.hm-seg { display: inline-flex; border: 1px solid var(--cv-border); border-radius: var(--cv-radius); overflow: hidden; }+.hm-seg {+ display: inline-flex;+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius);+ overflow: hidden;+}.hm-seg button {- appearance: none; border: 0; background: var(--cv-surface); color: var(--cv-text-2);- font: inherit; font-size: 0.8125rem; padding: 0.375rem 0.75rem; cursor: pointer;- border-right: 1px solid var(--cv-border); transition: background 0.15s, color 0.15s;-}-.hm-seg button:last-child { border-right: 0; }-.hm-seg button:hover { background: var(--cv-surface-2); color: var(--cv-text); }-.hm-seg button[aria-pressed='true'] { background: var(--cv-accent); color: #fff; }-.hm-seg button:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: -2px; }-.hm-legend { display: flex; align-items: center; gap: 0.5rem; margin-left: auto; font-size: 0.75rem; color: var(--cv-text-3); }-.hm-legend .bar { width: 120px; height: 8px; border-radius: 999px; background: linear-gradient(90deg, #dc2626, #6b7280, #16a34a); }+ appearance: none;+ border: 0;+ background: var(--cv-surface);+ color: var(--cv-text-2);+ font: inherit;+ font-size: 0.8125rem;+ padding: 0.375rem 0.75rem;+ cursor: pointer;+ border-right: 1px solid var(--cv-border);+ transition:+ background 0.15s,+ color 0.15s;+}+.hm-seg button:last-child {+ border-right: 0;+}+.hm-seg button:hover {+ background: var(--cv-surface-2);+ color: var(--cv-text);+}+.hm-seg button[aria-pressed='true'] {+ background: var(--cv-accent);+ color: #fff;+}+.hm-seg button:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: -2px;+}+.hm-legend {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin-left: auto;+ font-size: 0.75rem;+ color: var(--cv-text-3);+}+.hm-legend .bar {+ width: 120px;+ height: 8px;+ border-radius: 999px;+ background: linear-gradient(90deg, #dc2626, #6b7280, #16a34a);+}.hm-grid {- position: relative; width: 100%; height: 560px;- border: 1px solid var(--cv-border); border-radius: var(--cv-radius-xl);- background: var(--cv-surface-2); overflow: hidden;+ position: relative;+ width: 100%;+ height: 560px;+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-xl);+ background: var(--cv-surface-2);+ overflow: hidden;}.hm-tile {- position: absolute; overflow: hidden; text-decoration: none;- border: 1px solid rgba(0, 0, 0, 0.28); color: #fff;- display: flex; flex-direction: column; justify-content: center; align-items: center;- padding: 2px; transition: filter 0.12s, transform 0.12s; contain: strict;-}-.hm-tile:hover, .hm-tile:focus-visible { filter: brightness(1.12); z-index: 3; outline: none; }-.hm-tile:focus-visible { box-shadow: inset 0 0 0 2px #fff; }-.hm-tile .sym { font-weight: 700; line-height: 1.05; text-shadow: 0 1px 2px rgba(0,0,0,0.4); }-.hm-tile .chg { line-height: 1.05; opacity: 0.95; text-shadow: 0 1px 2px rgba(0,0,0,0.4); font-variant-numeric: tabular-nums; }-.hm-tile.tiny .chg { display: none; }+ position: absolute;+ overflow: hidden;+ text-decoration: none;+ border: 1px solid rgba(0, 0, 0, 0.28);+ color: #fff;+ display: flex;+ flex-direction: column;+ justify-content: center;+ align-items: center;+ padding: 2px;+ transition:+ filter 0.12s,+ transform 0.12s;+ contain: strict;+}+.hm-tile:hover,+.hm-tile:focus-visible {+ filter: brightness(1.12);+ z-index: 3;+ outline: none;+}+.hm-tile:focus-visible {+ box-shadow: inset 0 0 0 2px #fff;+}+.hm-tile .sym {+ font-weight: 700;+ line-height: 1.05;+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);+}+.hm-tile .chg {+ line-height: 1.05;+ opacity: 0.95;+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);+ font-variant-numeric: tabular-nums;+}+.hm-tile.tiny .chg {+ display: none;+}.hm-tip {- position: fixed; z-index: 40; pointer-events: none;- background: var(--cv-surface); border: 1px solid var(--cv-border);- border-radius: var(--cv-radius); box-shadow: var(--cv-shadow-dropdown);- padding: 0.5rem 0.625rem; font-size: 0.75rem; color: var(--cv-text-2);+ position: fixed;+ z-index: 40;+ pointer-events: none;+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius);+ box-shadow: var(--cv-shadow-dropdown);+ padding: 0.5rem 0.625rem;+ font-size: 0.75rem;+ color: var(--cv-text-2);max-width: 220px;}-.hm-tip .t { font-weight: 600; color: var(--cv-text); margin: 0 0 0.125rem; }-.hm-tip .r { margin: 0.0625rem 0; display: flex; justify-content: space-between; gap: 1rem; }-.hm-tip .r span:last-child { font-family: var(--cv-font-mono); color: var(--cv-text); }+.hm-tip .t {+ font-weight: 600;+ color: var(--cv-text);+ margin: 0 0 0.125rem;+}+.hm-tip .r {+ margin: 0.0625rem 0;+ display: flex;+ justify-content: space-between;+ gap: 1rem;+}+.hm-tip .r span:last-child {+ font-family: var(--cv-font-mono);+ color: var(--cv-text);+}/* ── Gas tracker ────────────────────────────────────────────────────────── */-.gas-tiers { display: grid; gap: 1rem; grid-template-columns: repeat(3, 1fr); }+.gas-tiers {+ display: grid;+ gap: 1rem;+ grid-template-columns: repeat(3, 1fr);+}.gas-tier {- background: var(--cv-surface); border: 1px solid var(--cv-border);- border-radius: var(--cv-radius-xl); box-shadow: var(--cv-shadow-card);- padding: 1.25rem; text-align: center; position: relative;-}-.gas-tier.standard { border-color: var(--cv-accent); box-shadow: var(--cv-shadow-card), 0 0 0 1px var(--cv-accent); }-.gas-tier .tier-name { font-size: 0.8125rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; color: var(--cv-text-3); margin: 0; }-.gas-tier .tier-name.slow { color: var(--cv-red); }-.gas-tier .tier-name.standard { color: var(--cv-accent); }-.gas-tier .tier-name.fast { color: var(--cv-green); }-.gas-tier .gwei { font-family: var(--cv-font-mono); font-size: 2.25rem; font-weight: 700; color: var(--cv-text); line-height: 1; margin: 0.5rem 0 0.125rem; }-.gas-tier .gwei .unit { font-size: 0.875rem; color: var(--cv-text-3); font-weight: 500; }-.gas-tier .tier-sub { font-size: 0.75rem; color: var(--cv-text-3); margin: 0; }-.gas-tier .tier-cost { margin: 0.75rem 0 0; font-size: 0.9375rem; font-weight: 600; color: var(--cv-text); font-family: var(--cv-font-mono); }-.gas-actions-card { padding: 1.25rem 1.5rem; }-.gas-actions-table { width: 100%; border-collapse: collapse; font-size: 0.875rem; }-.gas-actions-table th, .gas-actions-table td { padding: 0.5rem 0.5rem; border-bottom: 1px solid var(--cv-border); text-align: right; }-.gas-actions-table th:first-child, .gas-actions-table td:first-child { text-align: left; }-.gas-actions-table th { font-size: 0.6875rem; text-transform: uppercase; letter-spacing: 0.04em; color: var(--cv-text-3); font-weight: 600; }-.gas-actions-table td { font-family: var(--cv-font-mono); color: var(--cv-text-2); }-.gas-actions-table td:first-child { font-family: var(--cv-font-sans); color: var(--cv-text); }-.gas-actions-table tbody tr:last-child td { border-bottom: 0; }-.gas-base { display: flex; flex-wrap: wrap; gap: 1.5rem; align-items: baseline; margin: 0 0 1.25rem; }-.gas-base .k { font-size: 0.75rem; color: var(--cv-text-3); }-.gas-base .v { font-family: var(--cv-font-mono); font-weight: 600; color: var(--cv-text); }+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-xl);+ box-shadow: var(--cv-shadow-card);+ padding: 1.25rem;+ text-align: center;+ position: relative;+}+.gas-tier.standard {+ border-color: var(--cv-accent);+ box-shadow:+ var(--cv-shadow-card),+ 0 0 0 1px var(--cv-accent);+}+.gas-tier .tier-name {+ font-size: 0.8125rem;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--cv-text-3);+ margin: 0;+}+.gas-tier .tier-name.slow {+ color: var(--cv-red);+}+.gas-tier .tier-name.standard {+ color: var(--cv-accent);+}+.gas-tier .tier-name.fast {+ color: var(--cv-green);+}+.gas-tier .gwei {+ font-family: var(--cv-font-mono);+ font-size: 2.25rem;+ font-weight: 700;+ color: var(--cv-text);+ line-height: 1;+ margin: 0.5rem 0 0.125rem;+}+.gas-tier .gwei .unit {+ font-size: 0.875rem;+ color: var(--cv-text-3);+ font-weight: 500;+}+.gas-tier .tier-sub {+ font-size: 0.75rem;+ color: var(--cv-text-3);+ margin: 0;+}+.gas-tier .tier-cost {+ margin: 0.75rem 0 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--cv-text);+ font-family: var(--cv-font-mono);+}+.gas-actions-card {+ padding: 1.25rem 1.5rem;+}+.gas-actions-table {+ width: 100%;+ border-collapse: collapse;+ font-size: 0.875rem;+}+.gas-actions-table th,+.gas-actions-table td {+ padding: 0.5rem 0.5rem;+ border-bottom: 1px solid var(--cv-border);+ text-align: right;+}+.gas-actions-table th:first-child,+.gas-actions-table td:first-child {+ text-align: left;+}+.gas-actions-table th {+ font-size: 0.6875rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--cv-text-3);+ font-weight: 600;+}+.gas-actions-table td {+ font-family: var(--cv-font-mono);+ color: var(--cv-text-2);+}+.gas-actions-table td:first-child {+ font-family: var(--cv-font-sans);+ color: var(--cv-text);+}+.gas-actions-table tbody tr:last-child td {+ border-bottom: 0;+}+.gas-base {+ display: flex;+ flex-wrap: wrap;+ gap: 1.5rem;+ align-items: baseline;+ margin: 0 0 1.25rem;+}+.gas-base .k {+ font-size: 0.75rem;+ color: var(--cv-text-3);+}+.gas-base .v {+ font-family: var(--cv-font-mono);+ font-weight: 600;+ color: var(--cv-text);+}@media (max-width: 720px) {- .gas-tiers { grid-template-columns: 1fr; }- .hm-grid { height: 460px; }+ .gas-tiers {+ grid-template-columns: 1fr;+ }+ .hm-grid {+ height: 460px;+ }}/* ── Compare ────────────────────────────────────────────────────────────── */-.cmp-picker { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: flex-start; margin-bottom: 1.5rem; }-.cmp-chips { display: flex; flex-wrap: wrap; gap: 0.5rem; }+.cmp-picker {+ display: flex;+ flex-wrap: wrap;+ gap: 0.75rem;+ align-items: flex-start;+ margin-bottom: 1.5rem;+}+.cmp-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+}.cmp-chip {- display: inline-flex; align-items: center; gap: 0.5rem;- background: var(--cv-surface-2); border: 1px solid var(--cv-border);- border-radius: 999px; padding: 0.3125rem 0.375rem 0.3125rem 0.625rem; font-size: 0.8125rem;+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ border-radius: 999px;+ padding: 0.3125rem 0.375rem 0.3125rem 0.625rem;+ font-size: 0.8125rem;+}+.cmp-chip img {+ width: 18px;+ height: 18px;+ border-radius: 50%;+}+.cmp-chip .dot {+ width: 10px;+ height: 10px;+ border-radius: 50%;+ flex: 0 0 auto;}-.cmp-chip img { width: 18px; height: 18px; border-radius: 50%; }-.cmp-chip .dot { width: 10px; height: 10px; border-radius: 50%; flex: 0 0 auto; }.cmp-chip button {- appearance: none; border: 0; background: transparent; color: var(--cv-text-3);- cursor: pointer; font-size: 1rem; line-height: 1; padding: 0 0.25rem; border-radius: 50%;-}-.cmp-chip button:hover { color: var(--cv-red); }-.cmp-table-wrap { overflow-x: auto; border: 1px solid var(--cv-border); border-radius: var(--cv-radius-xl); background: var(--cv-surface); }-.cmp-table { width: 100%; border-collapse: collapse; font-size: 0.875rem; min-width: 480px; }-.cmp-table th, .cmp-table td { padding: 0.75rem 0.875rem; border-bottom: 1px solid var(--cv-border); text-align: right; }-.cmp-table th:first-child, .cmp-table td:first-child { text-align: left; color: var(--cv-text-3); font-weight: 500; }-.cmp-table thead th { font-size: 0.8125rem; }-.cmp-table thead th .coin { display: inline-flex; align-items: center; gap: 0.375rem; }-.cmp-table thead th img { width: 20px; height: 20px; border-radius: 50%; }-.cmp-table td { font-family: var(--cv-font-mono); color: var(--cv-text); font-variant-numeric: tabular-nums; }-.cmp-table tbody tr:last-child td { border-bottom: 0; }-.cmp-table td.best { color: var(--cv-green); font-weight: 600; }-.cmp-legend { display: flex; flex-wrap: wrap; gap: 1rem; margin-top: 0.75rem; font-size: 0.8125rem; }-.cmp-legend .li { display: inline-flex; align-items: center; gap: 0.375rem; color: var(--cv-text-2); }-.cmp-legend .dot { width: 12px; height: 3px; border-radius: 2px; }+ appearance: none;+ border: 0;+ background: transparent;+ color: var(--cv-text-3);+ cursor: pointer;+ font-size: 1rem;+ line-height: 1;+ padding: 0 0.25rem;+ border-radius: 50%;+}+.cmp-chip button:hover {+ color: var(--cv-red);+}+.cmp-table-wrap {+ overflow-x: auto;+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-xl);+ background: var(--cv-surface);+}+.cmp-table {+ width: 100%;+ border-collapse: collapse;+ font-size: 0.875rem;+ min-width: 480px;+}+.cmp-table th,+.cmp-table td {+ padding: 0.75rem 0.875rem;+ border-bottom: 1px solid var(--cv-border);+ text-align: right;+}+.cmp-table th:first-child,+.cmp-table td:first-child {+ text-align: left;+ color: var(--cv-text-3);+ font-weight: 500;+}+.cmp-table thead th {+ font-size: 0.8125rem;+}+.cmp-table thead th .coin {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+}+.cmp-table thead th img {+ width: 20px;+ height: 20px;+ border-radius: 50%;+}+.cmp-table td {+ font-family: var(--cv-font-mono);+ color: var(--cv-text);+ font-variant-numeric: tabular-nums;+}+.cmp-table tbody tr:last-child td {+ border-bottom: 0;+}+.cmp-table td.best {+ color: var(--cv-green);+ font-weight: 600;+}+.cmp-legend {+ display: flex;+ flex-wrap: wrap;+ gap: 1rem;+ margin-top: 0.75rem;+ font-size: 0.8125rem;+}+.cmp-legend .li {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ color: var(--cv-text-2);+}+.cmp-legend .dot {+ width: 12px;+ height: 3px;+ border-radius: 2px;+}diff --git a/src/restyle.js b/src/restyle.jsnew file mode 100644index 000000000..91c03b55b--- /dev/null+++ b/src/restyle.js@@ -0,0 +1,439 @@+// restyle.js — Restyle Studio: apply PBR material presets and seeded colorway+// variants to any GLB, fine-tune metalness/roughness/color/emissive live, and+// export a validated GLB — non-destructively (the original is always one click+// away). Consumes the framework-agnostic PBR preset library shipped in+// @three-ws/viewer-presets and the shared GLB optimize/validate path used by+// Avatar Studio, so it reuses the platform's material vocabulary rather than+// inventing a parallel one.+//+// Roadmap prompt 06 (material, restyle & variant tools), client surface.++import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';+import {+ MATERIAL_PRESETS,+ MATERIAL_PRESET_NAMES,+ applyMaterialPreset,+ materialVariants,+} from '../packages/viewer-presets/src/materials.js';+import { optimizeAndValidateGlb } from './avatar-studio-optimize.js';++// A small, always-present local sample so the page is never an empty void — the+// platform's default humanoid, served from /avatars.+const DEFAULT_MODEL = '/avatars/realistic-female.glb';++const state = {+ renderer: null,+ scene: null,+ camera: null,+ controls: null,+ root: null, // the loaded glTF scene graph+ originals: new Map(), // material → captured original PBR params (for Reset)+ lineage: [], // ordered list of applied steps, for the history strip+ baseName: 'chrome', // which preset variants fan out from+ manual: { metalness: null, roughness: null, emissiveIntensity: 0 },+ sourceLabel: '',+ raf: 0,+};++const el = {};++document.addEventListener('DOMContentLoaded', init);++function init() {+ cache();+ buildScene();+ buildPresetButtons();+ wireControls();+ const url = new URL(location.href).searchParams.get('url');+ loadModel(url || DEFAULT_MODEL, url ? 'from URL' : 'sample');+ window.addEventListener('resize', onResize);+}++function cache() {+ for (const id of [+ 'stage', 'canvas-wrap', 'presets', 'variants', 'variant-strip', 'history',+ 'metalness', 'roughness', 'emissive', 'basecolor', 'emissivecolor',+ 'seed', 'variant-count', 'gen-variants', 'reset', 'export', 'export-note',+ 'file', 'url-input', 'load-url', 'status', 'empty', 'error', 'error-msg', 'retry',+ ]) {+ el[id] = document.getElementById(id);+ }+}++// ── scene ────────────────────────────────────────────────────────────────────+function buildScene() {+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.05;+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ el['canvas-wrap'].appendChild(renderer.domElement);+ state.renderer = renderer;++ const scene = new THREE.Scene();+ state.scene = scene;+ // RoomEnvironment gives metals/glass something real to reflect — chrome and+ // gold read as metal, not flat grey, without shipping an HDRI asset.+ const pmrem = new THREE.PMREMGenerator(renderer);+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;++ const key = new THREE.DirectionalLight(0xffffff, 2.2);+ key.position.set(3, 5, 4);+ scene.add(key);+ const rim = new THREE.DirectionalLight(0x99bbff, 0.8);+ rim.position.set(-4, 2, -3);+ scene.add(rim);+ scene.add(new THREE.AmbientLight(0xffffff, 0.4));++ const camera = new THREE.PerspectiveCamera(35, 1, 0.05, 200);+ camera.position.set(0, 1.4, 4);+ state.camera = camera;++ const controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.08;+ controls.target.set(0, 1, 0);+ state.controls = controls;++ onResize();+ const tick = () => {+ state.raf = requestAnimationFrame(tick);+ controls.update();+ renderer.render(scene, camera);+ };+ tick();+}++function onResize() {+ const wrap = el['canvas-wrap'];+ if (!wrap || !state.renderer) return;+ const w = wrap.clientWidth || 640;+ const h = wrap.clientHeight || 480;+ state.renderer.setSize(w, h, false);+ state.renderer.domElement.style.width = '100%';+ state.renderer.domElement.style.height = '100%';+ state.camera.aspect = w / h;+ state.camera.updateProjectionMatrix();+}++// ── model loading ──────────────────────────────────────────────────────────────+function makeLoader() {+ const loader = new GLTFLoader();+ loader.setMeshoptDecoder(MeshoptDecoder); // platform GLBs are often meshopt-packed+ return loader;+}++function loadModel(src, label) {+ showState('loading');+ const onLoaded = (gltf) => {+ try {+ mountModel(gltf.scene, label);+ showState('ready');+ } catch (err) {+ fail(err);+ }+ };+ const onError = (err) => fail(err);+ const loader = makeLoader();+ if (src instanceof File) {+ const reader = new FileReader();+ reader.onload = () => loader.parse(reader.result, '', onLoaded, onError);+ reader.onerror = () => fail(new Error('could not read the file'));+ reader.readAsArrayBuffer(src);+ } else {+ loader.load(src, onLoaded, undefined, onError);+ }+}++function mountModel(newRoot, label) {+ if (state.root) {+ state.scene.remove(state.root);+ disposeTree(state.root);+ }+ state.root = newRoot;+ state.originals.clear();+ state.lineage = [];+ state.manual = { metalness: null, roughness: null, emissiveIntensity: 0 };+ state.sourceLabel = label || '';+ captureOriginals(newRoot);+ frameModel(newRoot);+ state.scene.add(newRoot);+ pushHistory('Original');+ syncSlidersFromModel();+}++function captureOriginals(root) {+ root.traverse((n) => {+ for (const m of materialsOf(n)) {+ if (!isStandardLike(m) || state.originals.has(m)) continue;+ state.originals.set(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 frameModel(root) {+ const box = new THREE.Box3().setFromObject(root);+ const size = box.getSize(new THREE.Vector3());+ const center = box.getCenter(new THREE.Vector3());+ root.position.sub(center);+ root.position.y += size.y / 2; // rest feet near y=0+ const radius = Math.max(size.x, size.y, size.z) * 0.5 || 1;+ const dist = radius / Math.sin((state.camera.fov * Math.PI) / 180 / 2) * 1.3;+ state.camera.position.set(0, size.y * 0.55, dist);+ state.controls.target.set(0, size.y * 0.5, 0);+ state.controls.update();+}++// ── material operations ────────────────────────────────────────────────────────+function applyPreset(name) {+ if (!state.root) return;+ applyMaterialPreset(THREE, state.root, name);+ state.baseName = name;+ state.manual = {+ metalness: MATERIAL_PRESETS[name].metalness ?? null,+ roughness: MATERIAL_PRESETS[name].roughness ?? null,+ emissiveIntensity: MATERIAL_PRESETS[name].emissiveIntensity ?? 0,+ };+ markPresetActive(name);+ pushHistory(MATERIAL_PRESETS[name].label || name);+ syncSlidersFromModel();+}++function applyVariant(config, label) {+ if (!state.root) return;+ applyMaterialPreset(THREE, state.root, config);+ pushHistory(label);+ syncSlidersFromModel();+}++// Live manual overrides — set the same property across every standard material.+function setManual(prop, value) {+ if (!state.root) return;+ state.manual[prop] = value;+ state.root.traverse((n) => {+ for (const m of materialsOf(n)) {+ if (!isStandardLike(m)) continue;+ if (prop === 'metalness') m.metalness = value;+ else if (prop === 'roughness') m.roughness = value;+ else if (prop === 'emissiveIntensity') {+ if (m.emissive) m.emissiveIntensity = value;+ } else if (prop === 'color') m.color.set(value);+ else if (prop === 'emissive' && m.emissive) m.emissive.set(value);+ m.needsUpdate = true;+ }+ });+}++function resetModel() {+ if (!state.root) return;+ for (const [m, o] of state.originals) {+ m.color.setHex(o.color);+ m.metalness = o.metalness;+ m.roughness = o.roughness;+ if (m.emissive && o.emissive != null) m.emissive.setHex(o.emissive);+ m.emissiveIntensity = o.emissiveIntensity;+ m.envMapIntensity = o.envMapIntensity;+ m.transparent = o.transparent;+ m.opacity = o.opacity;+ m.needsUpdate = true;+ }+ state.lineage = [];+ state.manual = { metalness: null, roughness: null, emissiveIntensity: 0 };+ markPresetActive(null);+ pushHistory('Original');+ syncSlidersFromModel();+}++// ── variants ─────────────────────────────────────────────────────────────────+function generateVariants() {+ if (!state.root) return;+ const seed = parseInt(el.seed.value, 10) || 0;+ const count = clampInt(parseInt(el['variant-count'].value, 10) || 6, 1, 12);+ const variants = materialVariants(state.baseName, { seed, count });+ el['variant-strip'].innerHTML = '';+ for (const v of variants) {+ const b = document.createElement('button');+ b.className = 'rs-swatch';+ b.style.background = v.config.color;+ b.title = `${v.label} · seed ${v.seed}`;+ b.setAttribute('aria-label', `Apply ${v.label}`);+ b.addEventListener('click', () => applyVariant(v.config, v.label));+ el['variant-strip'].appendChild(b);+ }+ el.variants.hidden = false;+}++// ── export ─────────────────────────────────────────────────────────────────────+async function exportModel() {+ if (!state.root) return;+ el.export.disabled = true;+ setNote(el['export-note'], 'Exporting…');+ try {+ const exporter = new GLTFExporter();+ const glb = await new Promise((res, rej) => {+ exporter.parse(state.root, (result) => res(result), (err) => rej(err), { binary: true });+ });+ const rawBlob = new Blob([glb], { type: 'model/gltf-binary' });+ const { blob, optimized, outputBytes, report } = await optimizeAndValidateGlb(rawBlob, {+ onStatus: (s) => setNote(el['export-note'], s),+ });+ const valid = !report || report.issues?.numErrors === 0;+ download(blob, 'restyled.glb');+ setNote(+ el['export-note'],+ `Saved restyled.glb · ${fmtBytes(outputBytes)}${optimized ? ' · optimized' : ''}${valid ? ' · valid glTF ✓' : ' · exported'}`,+ );+ } catch (err) {+ setNote(el['export-note'], `Export failed: ${err?.message || err}`);+ } finally {+ el.export.disabled = false;+ }+}++// ── UI wiring ───────────────────────────────────────────────────────────────────+function buildPresetButtons() {+ el.presets.innerHTML = '';+ for (const name of MATERIAL_PRESET_NAMES) {+ const preset = MATERIAL_PRESETS[name];+ const b = document.createElement('button');+ b.className = 'rs-preset';+ b.dataset.preset = name;+ b.innerHTML = `<span class="rs-preset__swatch" style="background:${swatchCss(preset)}"></span><span>${preset.label || name}</span>`;+ b.addEventListener('click', () => applyPreset(name));+ el.presets.appendChild(b);+ }+}++function wireControls() {+ el.metalness.addEventListener('input', () => setManual('metalness', +el.metalness.value));+ el.roughness.addEventListener('input', () => setManual('roughness', +el.roughness.value));+ el.emissive.addEventListener('input', () => setManual('emissiveIntensity', +el.emissive.value));+ el.basecolor.addEventListener('input', () => setManual('color', el.basecolor.value));+ el.emissivecolor.addEventListener('input', () => setManual('emissive', el.emissivecolor.value));+ el['gen-variants'].addEventListener('click', generateVariants);+ el.reset.addEventListener('click', resetModel);+ el.export.addEventListener('click', exportModel);+ el['ai-run'].addEventListener('click', aiRestyle);+ el.retry.addEventListener('click', () => loadModel(DEFAULT_MODEL, 'sample'));++ el.file.addEventListener('change', (e) => {+ const f = e.target.files?.[0];+ if (f) loadModel(f, f.name);+ });+ el['load-url'].addEventListener('click', () => {+ const u = (el['url-input'].value || '').trim();+ if (!u) return;+ const next = new URL(location.href);+ next.searchParams.set('url', u);+ location.href = next.toString();+ });+ // Drag & drop onto the stage.+ const stage = el.stage;+ ['dragover', 'drop'].forEach((ev) =>+ stage.addEventListener(ev, (e) => {+ e.preventDefault();+ if (ev === 'drop') {+ const f = e.dataTransfer?.files?.[0];+ if (f && /\.(glb|gltf)$/i.test(f.name)) loadModel(f, f.name);+ }+ }),+ );+}++function syncSlidersFromModel() {+ // Reflect the first standard material's values back into the sliders.+ let first = null;+ state.root?.traverse((n) => {+ if (first) return;+ for (const m of materialsOf(n)) if (isStandardLike(m)) { first = m; break; }+ });+ if (!first) return;+ el.metalness.value = first.metalness;+ el.roughness.value = first.roughness;+ el.emissive.value = first.emissiveIntensity || 0;+ el.basecolor.value = '#' + first.color.getHexString();+ if (first.emissive) el.emissivecolor.value = '#' + first.emissive.getHexString();+}++function markPresetActive(name) {+ el.presets.querySelectorAll('.rs-preset').forEach((b) => {+ b.classList.toggle('is-active', b.dataset.preset === name);+ });+}++function pushHistory(label) {+ state.lineage.push(label);+ el.history.innerHTML = state.lineage+ .map((s, i) => `<span class="rs-step${i === state.lineage.length - 1 ? ' is-current' : ''}">${escapeHtml(s)}</span>`)+ .join('<span class="rs-arrow">→</span>');+}++function showState(kind) {+ el.status.hidden = kind !== 'loading';+ el.empty.hidden = true;+ el.error.hidden = kind !== 'error';+ el['canvas-wrap'].classList.toggle('is-hidden', kind === 'error');+}++function fail(err) {+ console.warn('[restyle] load failed:', err?.message || err);+ el['error-msg'].textContent =+ 'That model could not be loaded. Check the URL is a public .glb/.gltf, or upload a file.';+ showState('error');+}++// ── small helpers ────────────────────────────────────────────────────────────+function materialsOf(node) {+ if (!node || !node.material) return [];+ return Array.isArray(node.material) ? node.material.filter(Boolean) : [node.material];+}+function isStandardLike(m) {+ return !!m && 'metalness' in m && 'roughness' in m && !!m.color && typeof m.color.getHex === 'function';+}+function disposeTree(root) {+ root.traverse((n) => {+ if (n.geometry) n.geometry.dispose?.();+ for (const m of materialsOf(n)) {+ for (const v of Object.values(m)) if (v && v.isTexture) v.dispose?.();+ m.dispose?.();+ }+ });+}+function swatchCss(p) {+ if (p.emissive && (p.emissiveIntensity || 0) > 0.5) return p.emissive;+ if (p.transparent) return `${p.color}88`;+ return p.color || '#888';+}+function download(blob, name) {+ const a = document.createElement('a');+ a.href = URL.createObjectURL(blob);+ a.download = name;+ a.click();+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);+}+function setNote(node, text) {+ if (node) node.textContent = text;+}+function fmtBytes(n) {+ return n > 1e6 ? (n / 1e6).toFixed(1) + ' MB' : Math.round(n / 1024) + ' KB';+}+function clampInt(n, lo, hi) {+ return Math.min(hi, Math.max(lo, Math.round(n)));+}+function escapeHtml(s) {+ return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));+}diff --git a/tests/api/v1-ai-image.test.js b/tests/api/v1-ai-image.test.jsindex 1d5c14934..8432cc8e3 100644--- a/tests/api/v1-ai-image.test.js+++ b/tests/api/v1-ai-image.test.js@@ -12,6 +12,7 @@*/import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';+import { Readable } from 'node:stream';beforeAll(() => {Object.assign(process.env, {@@ -81,14 +82,17 @@ function makeRes() {};}+// A real Readable stream (not a plain async-iterable object) so it matches+// production `req` semantics — the shared readBody() helper (api/_lib/http.js)+// reads via `.on('data'/'end')`, which only a real stream implements.function makeReq({ method = 'POST', url = '/api/v1/ai/image', headers = {}, body = null } = {}) {const payload = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);- return {- method,- url,- headers: { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9', ...headers },- async *[Symbol.asyncIterator]() { if (payload) yield Buffer.from(payload, 'utf8'); },- };+ const buf = Buffer.from(payload, 'utf8');+ const req = Readable.from(buf.length ? [buf] : []);+ req.method = method;+ req.url = url;+ req.headers = { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9', 'content-length': String(buf.length), ...headers };+ return req;}const LANE_ENV = ['NVIDIA_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON', 'REPLICATE_API_TOKEN', 'VERTEX_IMAGEN_ENABLED', 'X402_PRICE_AI_IMAGE'];diff --git a/tests/api/x402-discovery-parity.test.js b/tests/api/x402-discovery-parity.test.jsindex d91bb5eca..7b6a0e1b0 100644--- a/tests/api/x402-discovery-parity.test.js+++ b/tests/api/x402-discovery-parity.test.js@@ -56,11 +56,6 @@ const EXCLUSIONS = new Map(['Internal: the paid intel kiosk in the /play town buys from it. The ' +'agent-facing market read is the free /api/crypto bundle.',],- [- '/api/x402/fact-check',- 'Internal: the fact-checker app and the /play Sheriff NPC buy through it. ' +- 'Me-too LLM wrapper as an agent product; kept only for the in-product flows.',- ],['/api/x402/tutor','Internal: the /tutor page and the /play Schoolmarm NPC buy through it. ' +@@ -71,22 +66,18 @@ const EXCLUSIONS = new Map(['Internal: the agent-exchange demo and the /play trading-desk NPC buy ' +'through it. Agent-facing market intel is the free /api/crypto bundle.',],- [- '/api/x402/mint-to-mesh',- 'Internal: the /play foundry NPC sells it. Cube novelty — the real ' +- 'agent-facing 3D product is Forge (/api/x402/forge).',- ],- [- '/api/x402/mint-to-mesh-batch',- 'Internal: batch sibling of mint-to-mesh, same disposition — the real ' +- 'agent-facing 3D product is Forge.',- ],['/api/x402/pump-agent-audit',- 'Internal: the /play town NPC sells it. The agent-facing reads are the ' +- 'free /api/crypto/whales and /api/crypto/security.',+ 'De-listed per the 2026-07-08 storefront cleanup (prompt 18): the paid ' ++ '"oracle" framing over-claims what a payments-history audit is. The free ' ++ '/api/crypto/whales surface replaces it as the agent product; the /play ' ++ 'town NPC still buys through this route.',],]);+// fact-check, mint-to-mesh, and mint-to-mesh-batch were re-listed per the+// 2026-07-08 storefront cleanup (prompt 18) — they now carry real+// service-catalog descriptors (api/_lib/service-catalog/services/) and are+// expected to appear in the discovery doc like any other paid product.function paidRoutesFromFiles() {const routes = [];diff --git a/vercel.json b/vercel.jsonindex 1103f86a3..b04a88439 100644--- a/vercel.json+++ b/vercel.json@@ -965,6 +965,10 @@"src": "/stablecoins/?","dest": "/stablecoins.html"},+ {+ "src": "/bnb/?",+ "dest": "/bnb.html"+ },{"src": "/coin/([a-zA-Z0-9][a-zA-Z0-9_-]{0,99})/?","dest": "/coin.html"@@ -1216,6 +1220,10 @@"src": "/viewer/?","dest": "/viewer.html"},+ {+ "src": "/spatial-mcp/?",+ "dest": "/spatial-mcp/index.html"+ },{"src": "/pose-mini/?","dest": "/pose-mini.html"diff --git a/vite.config.js b/vite.config.jsindex a92d3ce1b..c870e8eef 100644--- a/vite.config.js+++ b/vite.config.js@@ -456,6 +456,7 @@ const appConfig = {defi: resolve(__dirname, 'pages/defi.html'),chains: resolve(__dirname, 'pages/chains.html'),stablecoins: resolve(__dirname, 'pages/stablecoins.html'),+ bnb: resolve(__dirname, 'pages/bnb.html'),trending: resolve(__dirname, 'pages/trending.html'),compose: resolve(__dirname, 'pages/compose.html'),'create-next': resolve(__dirname, 'pages/create-next.html'),@@ -996,6 +997,8 @@ support: resolve(__dirname, 'pages/support.html'),'/chains/': resolve(root, 'pages/chains.html'),'/stablecoins': resolve(root, 'pages/stablecoins.html'),'/stablecoins/': resolve(root, 'pages/stablecoins.html'),+ '/bnb': resolve(root, 'pages/bnb.html'),+ '/bnb/': resolve(root, 'pages/bnb.html'),'/compose': resolve(root, 'pages/compose.html'),'/compose/': resolve(root, 'pages/compose.html'),'/create/next': resolve(root, 'pages/create-next.html'),