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 further in-progress platform work (concurrent session snapshot)
nirholas277791660293
diff --git a/.agents/.claude-plugin/plugin.json b/.agents/.claude-plugin/plugin.jsonindex 0fbea566b..957dd50ac 100644--- a/.agents/.claude-plugin/plugin.json+++ b/.agents/.claude-plugin/plugin.json@@ -17,6 +17,5 @@"base","solana","polygon"- ],- "category": "payments"+ ]}diff --git a/.claude/settings.json b/.claude/settings.jsonindex ed8ad3b94..5f86e96f5 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -6,6 +6,12 @@"Bash(npx prettier --check *)"]},+ "enabledPlugins": {+ "three-ws-core@three-ws": true,+ "three-ws-developer@three-ws": true,+ "three-ws-pump-fun@three-ws": true,+ "three-ws-3d@three-ws": true+ },"extraKnownMarketplaces": {"three-ws": {"source": {@@ -13,10 +19,5 @@"repo": "nirholas/three.ws"}}- },- "enabledPlugins": {- "three-ws-core@three-ws": true,- "three-ws-developer@three-ws": true,- "three-ws-pump-fun@three-ws": true}}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 10287f33c..456f97214 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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.- **BNB Chain Live Block Race — 0.45s vs Base, Ethereum, Solana** (`/bnb-latency`) — A live, honest race: BNB Chain, Base, Ethereum, and Solana block times measured fresh off real public RPCs every few seconds, with a rolling sparkline per lane. No wallet, no payment, no hardcoded numbers — a lane that goes quiet shows 'reconnecting' while the others keep racing.+- **Crypto API** (`/crypto-api`) — One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.- **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.@@ -42,8 +43,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **New tool-authoring SDK: define an agent tool once — typed params, permissions, and rate limits included** — Internal SDK release for developers extending three.ws's 38 MCP servers: @three-ws/tool-sdk lets a tool be declared once with defineTool (Zod parameter schemas, auto-derived JSON Schema, a per-tool permission manifest for network access/rate limits/wallet use) and wired up with defineExecutor (typed handlers, automatic validation, uniform error wrapping) — then adapted into a live MCP server registration with a single toMcpTools() call. Proven by refactoring the naming MCP server's sns_resolve tool onto it with byte-identical behavior. `[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]`- **Restyle Studio — re-skin any 3D model with PBR presets and seeded variants** — A new browser tool re-skins any GLB without regenerating it. Apply a physically-based material preset — chrome, gold, copper, glass, wood, neon and more — fan out reproducible colorway variants from a seed, fine-tune metalness/roughness/emissive live, then export a validated GLB. Your original is never touched; one click resets it. The preset library also ships in the @three-ws/viewer-presets SDK for anyone building their own viewer. (`/restyle`) `[feature, sdk]`+- **Restyle Studio can now AI-restyle any model and remembers every version** — Restyle Studio (/restyle) now takes a plain-language instruction — "make it chrome", "worn copper", "cyberpunk neon" — and asks IBM Granite for a real PBR material plus a generated seamless texture, applied live to any GLB. Seeded colorway variants can now be saved as real, separately downloadable models instead of just a browser preview: one click mints all N as durable, glTF-validated GLBs. Every AI restyle and every saved variant is recorded in an immutable parent → child version lineage — the same versioning refine_model uses — so you can click back to any earlier look without losing your place; the original is never touched. The restyle_material MCP tool exposes the same engine to agents. (`/restyle`) `[feature]`- **Sentiment and narrative intel are now part of the free API** — POST /api/v1/sentiment (deterministic text classification), GET /api/v1/market/intel, and GET /api/v1/market/projects (aixbt-backed narrative + momentum intelligence) are now documented, publicly readable with no API key, and degrade honestly with a real 503 when the deployment's aixbt key isn't set — instead of a silent internal error. (`/docs/api-reference`) `[improvement, docs]`- **Spatial MCP: 3D models are now a native, interactive response type** — We published an open standard — Spatial MCP — for returning a live, interactive 3D scene as a first-class AI tool result instead of a link in text. Every three.ws 3D tool now emits a conformant artifact (camera, lighting, animation, AR handoff), a public validator checks conformance with actionable errors, and a framework-free reference renderer displays any conformant payload — including ones transformed from other tools. It carries no wallet or token surface, so it works everywhere. Try the reference renderer. (`/spatial-mcp`) `[feature, docs]`+- **Talk to your model, and remix the bazaar — right in Forge Studio** — Conversational iteration and the remix economy are now live in the Forge Studio UI, not just over the API and MCP tools. After any generation, an Iterate panel lets you describe a change — "make it metallic", "bigger helmet" — and Apply regenerates a new version anchored to the one you see, with a version-strip you can click to revert instantly or branch a new line of changes from any earlier point; the viewer cross-fades in the new version, never a pop or a frozen frame. A new Remix economy panel lets you publish a model you made as remixable — pick a license, a royalty rate up to 20%, and the Solana wallet that collects it — and browse everyone else's published, remixable models with their provenance and royalty terms shown up front. Remixing one is a real $0.25 USDC payment; the platform generates the new version and automatically routes the source creator's royalty on-chain, with the settlement receipt shown inline. Iteration stays free and payment-free on every track; publishing and remixing are Claude/paid-track only. (`/forge-studio`) `[feature]`- **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 free crypto API is now callable as an MCP tool** — Two new MCP tools on the three.ws server: crypto_data calls any endpoint of the free Crypto Data API (DEX pairs, CoinGecko/DefiLlama market data, Jupiter Solana prices and swap quotes, Solana RPC reads) directly from an MCP client, generated live from the same registry that powers GET /api/v1/x/*; token_snapshot fans out to whichever of those providers are registered to build a one-call market snapshot for any Solana token mint, degrading gracefully around any provider that's absent or down. (`/docs/mcp`) `[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]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex ce4a27256..e159ac9b5 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -27,6 +27,7 @@ bottom.| OKX.AI marketplace services | [api/okx/3d/[service].js](api/okx/3d/%5Bservice%5D.js) `→ /api/okx/3d/*` | Live | 3D services sold to other agents on OKX.AI (agent #2632): Agent Identity Studio flagship + decomposed studio services. Catalog source of truth: [api/_lib/okx-catalog.js](api/_lib/okx-catalog.js); pipeline: [api/_okx3d/](api/_okx3d); showcase: [pages/agent-identities.html](pages/agent-identities.html) `→ /agent-identities`; docs: [docs/okx-marketplace.md](docs/okx-marketplace.md) || Crypto Data API docs / landing | [pages/crypto.html](pages/crypto.html) `→ /crypto` | In-repo · docs surface | Screenshot-worthy public docs + funnel-top for the free, keyless Crypto Data API (`/api/crypto/*` — token snapshot, security, holders, launches, bonding, whales, symbol, wallet, trending). Renders hero, endpoint table, tabbed quickstart (curl/JS/Python), per-endpoint request/response reference and a live "Try it" console. Probes production at runtime and marks each endpoint Live vs Coming soon (degrades gracefully while sibling endpoints roll out). CTAs funnel to paid uniques: [/launcher](pages/launcher.html), [/vanity-wallet](public/vanity-wallet.html), [/forge](pages/forge.html). Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) || Free Crypto Data API + discovery | [api/crypto/index.js](api/crypto/index.js) `→ /api/crypto`, [api/crypto/openapi.js](api/crypto/openapi.js) `→ /api/crypto/openapi.json`, docs [docs/crypto-api.md](docs/crypto-api.md) `→ /docs/crypto-api` | Live · docs surface | Front door + OpenAPI 3.1 for the free, keyless Crypto Data API. Catalog assembler [api/_lib/crypto-catalog/index.js](api/_lib/crypto-catalog/index.js) merges `api/_lib/crypto-catalog/*.js` self-describing descriptors (currently `bonding`, `launches`, `symbol`, `token`, `trending`, `wallet`, `whales`) via a static import barrel — the production source of truth, since Vercel's bundler only ships what static imports reach — plus an additive dev-time directory glob; skips malformed/throwing entries, never throws, valid-empty when zero. New descriptor = drop the file AND add its import line to the barrel. OpenAPI built from the same catalog via [api/_lib/crypto-catalog/openapi.js](api/_lib/crypto-catalog/openapi.js). Index does HTML/JSON content negotiation. Endpoint handlers live in `api/crypto/*.js`. Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) |+| Unified Crypto API aggregator — storefront + OpenAPI | Registry [api/v1/_providers.js](api/v1/_providers.js) (`providerCatalog()`), front door [api/v1/x/[...slug].js](api/v1/x/%5B...slug%5D.js) `→ /api/v1/x/<provider>/<endpoint>`, discovery `→ GET /api/v1/x`, storefront [pages/crypto-api.html](pages/crypto-api.html) `→ /crypto-api`, OpenAPI 3.1 [api/openapi-json.js](api/openapi-json.js) `→ /openapi.json`, docs § in [docs/api-reference.md](docs/api-reference.md#unified-api--apiv1x-aggregator), dir guide [api/v1/README.md](api/v1/README.md) | Live | Third-party crypto/DeFi/on-chain APIs (CoinGecko, DefiLlama × 2, Jupiter, DexScreener, Solana RPC, OpenAI-compatible) re-offered as one bill: free per-IP tier → BYOK pass-through → three.ws plan → x402 pay-per-call, in that order. Everything (OpenAPI paths, the `/crypto-api` live table, the docs quota table) renders from `providerCatalog()` at request/page-load time — no hand-enumeration, so a new provider descriptor shows up everywhere with zero page edits. Test: [tests/openapi-aggregator.test.js](tests/openapi-aggregator.test.js). Not to be confused with the separate `/api/crypto/*` bundle below (different campaign, different registry). Spec: [prompts/x402-catalog/](prompts/x402-catalog) || Free 3D API + docs | [api/3d/index.js](api/3d/index.js) `→ /api/3d`, [api/3d/openapi.js](api/3d/openapi.js) `→ /api/3d/openapi.json`, docs [public/3d.html](public/3d.html) `→ /3d` (alias `/docs/3d-api`) | Live · docs surface | Front door + OpenAPI 3.1 for the free, keyless 3D API. Catalog assembler [api/_lib/3d-catalog/index.js](api/_lib/3d-catalog/index.js) merges `api/_lib/3d-catalog/*.js` descriptors (currently `generate`, `inspect`) via a static import barrel (production source of truth) plus an additive dev-time directory glob; new descriptor = drop the file AND add its barrel import line; skips malformed, never throws; OpenAPI built from the same catalog via [api/_lib/3d-catalog/openapi.js](api/_lib/3d-catalog/openapi.js). Index does HTML/JSON content negotiation and advertises the paid ladder (Forge Pro, Rigged Avatars). Docs page: hero, live endpoint table, runnable quickstart with a live "Run inspect" console, embedded `<model-viewer>` GLB preview, and the free→paid ladder. Free endpoints: [api/3d/generate.js](api/3d/generate.js) (prompt 12), [api/3d/inspect.js](api/3d/inspect.js) (prompt 13). GPT Store Actions surface: [api/3d/studio.js](api/3d/studio.js) `→ /api/3d/studio` — a store-compliant twin of `generate` that strips the x402/upgrade block, drops internal ids, and runs the [api/_mcp-studio/safety.js](api/_mcp-studio/safety.js) age-13+ content gate before any GPU work; backs the "three.ws 3D Studio" custom GPT ([prompts/store-submissions/_generated/openai-actions.yaml](prompts/store-submissions/_generated/openai-actions.yaml) + [openai-gpt-config.md](prompts/store-submissions/_generated/openai-gpt-config.md), store-submission prompt 12). Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) || Unified service catalog (one source, two storefronts) | [api/_lib/service-catalog/index.js](api/_lib/service-catalog/index.js), descriptors [api/_lib/service-catalog/services/](api/_lib/service-catalog/services/index.js) | Live | The canonical written-once record of every service (paid x402 + free crypto/3D bundles + OKX.AI rows). `toBazaarDiscovery()` generates every static `/api/x402/*` entry in the [api/wk.js](api/wk.js) discovery doc (replacing ~1,400 lines of hand-mirrored blocks); `toOkxCatalog()` reproduces the OKX `catalogIndex()` payload exactly, with an `include:'all'` projection ready for listing expansion. New paid service = drop `services/<slug>.js` + add its barrel import row. No-drift guards: [tests/service-catalog.test.js](tests/service-catalog.test.js). Spec: [specs/SERVICE_CATALOG.md](specs/SERVICE_CATALOG.md) || Conversational refinement + remix economy | Iterate: [api/_mcp-studio/tools.js](api/_mcp-studio/tools.js) `refine_model` (free, on `/api/mcp-studio`) + [mcp-server/src/tools/refine-model.js](mcp-server/src/tools/refine-model.js) (paid stdio, $0.25); shared lineage core [mcp-server/src/tools/_lineage.js](mcp-server/src/tools/_lineage.js). Remix (paid track): feed [api/remix-feed.js](api/remix-feed.js) `→ /api/remix-feed` (free browse/publish/lineage), settlement [api/x402/remix-asset.js](api/x402/remix-asset.js) `→ /api/x402/remix-asset` + core [api/_lib/remix-settlement.js](api/_lib/remix-settlement.js) + split math [api/_lib/remix-royalty.js](api/_lib/remix-royalty.js). Docs [docs/remix.md](docs/remix.md), [docs/mcp-studio.md](docs/mcp-studio.md). | Live | Talk to a model to iterate it ("make it metallic") — real anchored re-generation with a revertable/branchable version lineage rendered as a viewer version strip; free on both the OpenAI 3D Studio and the paid MCP server. Creators publish a finished model as remixable (provenance + license + royalty on the existing `forge_creations` rows — no parallel store); another agent pays $0.25 USDC to remix it and a creator-set royalty (≤20%, capped) routes on-chain to the original creator via the audited `transferSolanaUSDC` rail. Split/caps/payout unit-tested ([tests/remix-settlement.test.js](tests/remix-settlement.test.js), [tests/remix-royalty.test.js](tests/remix-royalty.test.js), [tests/refine-lineage.test.js](tests/refine-lineage.test.js)). Free track stays crypto-free. Prompt 09. |@@ -56,7 +57,7 @@ bottom.| Avatar Seeder control room | [pages/admin/seeder.html](pages/admin/seeder.html) + [src/admin-seeder.js](src/admin-seeder.js) `→ /admin/seeder`, backend [api/admin/seeder.js](api/admin/seeder.js) | In-repo (admin, noindex) | Arm/disarm the headless [Avaturn seed cron](api/cron/avaturn-seed-cron.js), watch live throughput + rig rate, and preview freshly-forged rigged avatars in 3D. Toggles the `avaturn_seed` runtime flag. Flags: [api/_lib/flags.js](api/_lib/flags.js) + [api/admin/flags.js](api/admin/flags.js). Docs: [docs/ops/runtime-flags.md](docs/ops/runtime-flags.md) || On-chain agent invocation | [contracts/agent-invocation/](contracts/agent-invocation) | In-repo | Anchor program: verifiable agent-to-agent skill invocation events. SDK: [agent-protocol-sdk/](agent-protocol-sdk) || Cross-chain SDKs | [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk) | Published | Cross-chain agent SDKs |-| MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge), [packages/*-mcp/](packages) | 32 npm servers + 6 hosted remote (38 total), all in the [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas) | Model Context Protocol surface — full server list in [docs/mcp.md](docs/mcp.md) |+| MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge), [packages/*-mcp/](packages) | 35 npm servers + 7 hosted remote (42 total, incl. the free `/api/mcp-studio` 3D Studio), all in the [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas) — canonical metadata: [prompts/store-submissions/_generated/mcp-listing-source.json](prompts/store-submissions/_generated/mcp-listing-source.json) | Model Context Protocol surface — full server list in [docs/mcp.md](docs/mcp.md) || Agent Skills pack | [.agents/skills/](.agents/skills) → manifest [.agents/skills/SKILLS.md](.agents/skills/SKILLS.md), [.agents/skills/skills-pack.json](.agents/skills/skills-pack.json) | In-repo; bundled in the `three-ws-core` [plugin](.claude-plugin/marketplace.json) | 40 portable `SKILL.md` folders (Agent Skills open standard) for any Claude surface — 3d/creative (cross-platform-safe), wallet/payments, intel/trading. Regenerate manifest: `node scripts/build-skills-pack.mjs`. Docs: [docs/agent-skills.md](docs/agent-skills.md) || SNS naming + pay-by-name | [api/sns.js](api/sns.js), [api/sns-subdomain.js](api/sns-subdomain.js), [api/threews/subdomain.js](api/threews/subdomain.js), [api/x402/pay-by-name.js](api/x402/pay-by-name.js), [src/solana/sns-subdomain.js](src/solana/sns-subdomain.js), [pages/threews-claim.html](pages/threews-claim.html) | In-repo | `*.threews.sol` subdomain mint, x402 payments addressed by name. Env: `THREEWS_SOL_PARENT_SECRET_BASE58` || Self-hosted x402 facilitator + ring economy | [api/x402-facilitator/[action].js](api/x402-facilitator/[action].js), [api/_lib/x402/self-facilitator.js](api/_lib/x402/self-facilitator.js), [api/x402/ring-settle.js](api/x402/ring-settle.js), [api/_lib/x402/pipelines/ring-rebalance.js](api/_lib/x402/pipelines/ring-rebalance.js), [api/x402-ring.js](api/x402-ring.js), [scripts/x402-ring-setup.mjs](scripts/x402-ring-setup.mjs) | In-repo (off by default) | Closed-loop agent-to-agent x402: platform wallets pay platform endpoints, settled in-house (no external facilitator). Fee-minimized, SOL-floor guarded, internal-labeled. Env: `X402_SELF_FACILITATOR_ENABLED`, `X402_FEE_PAYER_SECRET_BASE58`, `X402_TREASURY_SECRET_BASE58`. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md) |@@ -71,6 +72,7 @@ bottom.| 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) || BABT holder check (BNB Chain) | Lib [api/_lib/bnb/babt.js](api/_lib/bnb/babt.js) `hasBabt()`, free API [api/bnb/babt-check.js](api/bnb/babt-check.js) `→ GET /api/bnb/babt-check?address=` | In-repo · shipped | Free, rate-limited on-chain check for whether a BSC address holds a Binance Account Bound Token (BABT) — a real, live, KYC-backed soulbound token (1.16M+ mainnet holders, verified via `eth_getCode`/`balanceOf` against the real contract `0x2B09d47D...5215D7c8`). Verification writeup + honest comparison vs. Gitcoin Passport/World ID/Coinbase attestations: [docs/bnb-babt-findings.md](docs/bnb-babt-findings.md). Spike prompt: `prompts/bnb-chain/20-babt-verification-spike.md`. |+| BNB Chain live block race | [pages/bnb-latency.html](pages/bnb-latency.html) + [src/bnb-latency.js](src/bnb-latency.js) `→ /bnb-latency`, pure helpers [src/bnb-latency-helpers.js](src/bnb-latency-helpers.js), live multi-chain API [api/bnb/latency.js](api/bnb/latency.js) over [api/_lib/bnb/latency-lanes.js](api/_lib/bnb/latency-lanes.js) (reuses `probeBlockTime` from [api/_lib/bnb/chains.js](api/_lib/bnb/chains.js) for BNB, adds Base/Ethereum/Solana lanes) | In-repo · shipped | Standalone, shareable proof page: four lanes (BNB Chain, Base, Ethereum, Solana) polled every 5s, each showing a freshly measured average block/slot time and a rolling sparkline — no hardcoded numbers, a down RPC shows "reconnecting" on just that lane. Headline strip shows BNB's live average plus its honest measured-vs-measured speedup over Base/Ethereum. Linked from the [/bnb](pages/bnb.html) hub's "real-time on-chain world" card, which auto-lights-up now that this route resolves. |## npm workspacesdiff --git a/agents/fact-checker/src/search-sources.js b/agents/fact-checker/src/search-sources.jsindex 015277d0f..58c684a97 100644--- a/agents/fact-checker/src/search-sources.js+++ b/agents/fact-checker/src/search-sources.js@@ -1,5 +1,6 @@// Multi-source web search with fallback chain.-// Priority: Brave → Tavily → Exa → Serper → DuckDuckGo instant answer.+// Priority: Brave → Tavily → Exa → Serper → Wikipedia full-text search →+// DuckDuckGo instant answer.// At least 3 results are always returned (or a descriptive error thrown).const TIMEOUT_MS = 10_000;@@ -131,6 +132,44 @@ async function searchSerper(query) {}));}+// ── Wikipedia full-text search (free, keyless fallback) ───────────────────────+//+// No BRAVE_API_KEY/TAVILY_API_KEY/EXA_API_KEY/SERPER_API_KEY is configured+// anywhere in this deployment (verified against the production Cloud Run env+// on 2026-07-08), so DuckDuckGo's Instant Answer API — which only resolves a+// near-exact entity name to a single Wikipedia abstract, not general full-text+// search — was the ONLY source, and it returns nothing for most LLM-generated,+// full-sentence search queries ("Does cracking your knuckles cause arthritis"+// finds no Instant Answer, even though English Wikipedia has directly relevant+// coverage). Wikipedia's own search API (`list=search`) does real full-text+// ranking over sentence-shaped queries and needs no API key or account, so it+// sits ahead of the DDG fallback: strictly more capable, same zero-config cost.+async function searchWikipedia(query) {+ const url = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(query)}&srlimit=5&format=json&origin=*`;+ const res = await withTimeout(+ fetch(url, { headers: { accept: 'application/json', 'user-agent': 'three.ws-fact-checker/1.0 (+https://three.ws)' } }),+ TIMEOUT_MS,+ );+ if (!res.ok) {+ throw new Error(`Wikipedia search HTTP ${res.status}`);+ }+ const data = await res.json();+ const results = data?.query?.search || [];+ return results.map((r) => ({+ url: `https://en.wikipedia.org/wiki/${encodeURIComponent(String(r.title || '').replace(/ /g, '_'))}`,+ title: r.title || '',+ // Strip the <span class="searchmatch"> highlight markup and decode the+ // standard XML-safe entities MediaWiki escapes snippets with.+ snippet: decodeXmlEntities(String(r.snippet || '').replace(/<[^>]+>/g, '')),+ }));+}++function decodeXmlEntities(s) {+ return s.replace(/&(amp|lt|gt|quot|#0?39);/g, (_, e) =>+ ({ amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'", '#039': "'" })[e],+ );+}+// ── DuckDuckGo instant answer (fallback) ──────────────────────────────────────async function searchDuckDuckGo(query) {@@ -234,7 +273,18 @@ export async function searchWeb(query) {}}- // Final fallback: DuckDuckGo.+ // Free, keyless fallback #1: Wikipedia full-text search — tried whenever the+ // configured (or absent) paid providers haven't reached 3 results yet.+ if (deduplicate(combined).length < 3) {+ try {+ const wiki = await searchWikipedia(query);+ combined.push(...wiki);+ } catch (err) {+ errors.push(err.message);+ }+ }++ // Free, keyless fallback #2: DuckDuckGo Instant Answer.if (deduplicate(combined).length < 3) {try {const ddg = await searchDuckDuckGo(query);diff --git a/api/_lib/forge-health.js b/api/_lib/forge-health.jsindex 34aafa7fb..91a93b597 100644--- a/api/_lib/forge-health.js+++ b/api/_lib/forge-health.js@@ -29,7 +29,13 @@ import { providersInCooldown } from './provider-health.js';const PROBE_TIMEOUT_MS = 4_000;const CACHE_TTL_MS = 60_000;-const REPLICATE_PREDICTIONS_URL = 'https://api.replicate.com/v1/predictions';+// A real, stable, cheap model — this pipeline's own default text→image model+// (see text-to-image.js DEFAULT_TXT2IMG_MODEL) — used to probe Replicate's+// actual billing/quota gate. See the long comment on probeReplicate() below+// for why a real model is required here (a fake version/model short-circuits+// on request-shape or version-lookup validation before billing is ever+// checked, hiding a real out-of-credit account behind a false "ok").+const REPLICATE_PROBE_MODEL_URL = 'https://api.replicate.com/v1/models/black-forest-labs/flux-schnell/predictions';const NVCF_STATUS_URL = 'https://api.nvcf.nvidia.com/v2/nvcf/pexec/status';// Valid UUID shape that no real NVCF request will ever have — auth is checked// before the id is resolved, so 404 proves the key works.@@ -59,17 +65,35 @@ async function probeFetch(url, options = {}) {}// Replicate (the `trellis` lane): an invalid-version prediction submit clears-// the auth and account-quota gates without creating billable work — 4xx-// validation means a real submit would have been accepted.+// the auth and account-quota gates without creating billable work — a REAL+// model reference rejected on its input schema (422) means a real submit+// would have been accepted; that same rejection arrives instead as 402 when+// the account is out of credit, which is the signal this probe is for.+//+// Bug fixed 2026-07-08 (found live during a forge_free outage investigation):+// the previous probe posted `{ version: 'forge-health-probe-invalid-version' }`+// with NO `model`/`input` — Replicate's own request-shape validation ("input is+// required") rejects that with 422 BEFORE the billing/quota gate is ever+// reached, so a genuinely out-of-credit account still probed `ok`. Verified+// live against the real (currently out-of-credit) production token: the old+// probe body returned 422 "input is required"; the SAME token against a real+// model (`black-forest-labs/flux-schnell`, this pipeline's own default+// text→image model — see text-to-image.js DEFAULT_TXT2IMG_MODEL) with a+// deliberately-empty `input: {}` returned 402 "Insufficient credit" instantly,+// with no prediction id in the body — i.e. billing IS checked before input+// validation for a real model, and rejection there creates no billable work+// (confirmed: neither response contains a prediction id). So probing a real+// model with empty input reaches the actual gate this health check exists to+// verify, at zero cost either way.async function probeReplicate() {const id = 'trellis';const token = readEnv('REPLICATE_API_TOKEN');if (!token) return result(id, 'unconfigured', 'REPLICATE_API_TOKEN is not set on this deployment.');const started = Date.now();- const res = await probeFetch(REPLICATE_PREDICTIONS_URL, {+ const res = await probeFetch(REPLICATE_PROBE_MODEL_URL, {method: 'POST',headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },- body: JSON.stringify({ version: 'forge-health-probe-invalid-version' }),+ body: JSON.stringify({ input: {} }),});const latency = Date.now() - started;if (!res) return result(id, 'down', 'Replicate is unreachable.', { latency_ms: latency });@@ -82,8 +106,8 @@ async function probeReplicate() {if (res.status === 429) {return result(id, 'degraded', 'Replicate is throttling this account — generations will be rejected until the quota clears (check billing).', { http_status: res.status, latency_ms: latency });}- // 400/404/422 — the fake version was rejected AFTER auth and quota, which is- // exactly what the probe wants to see.+ // 400/404/422 — the empty input was rejected on schema AFTER auth and+ // billing/quota, which is exactly what the probe wants to see.if (res.status >= 400 && res.status < 500) {return result(id, 'ok', 'Replicate accepted authentication; generations should start.', { latency_ms: latency });}diff --git a/api/_lib/llm.js b/api/_lib/llm.jsindex ddc4fcf05..158d38a88 100644--- a/api/_lib/llm.js+++ b/api/_lib/llm.js@@ -155,7 +155,13 @@ function openaiCompatProvider({ name, key, url, model, extraHeaders = {} }) {model,max_tokens: maxTokens,messages: [- { role: 'system', content: system },+ // A system message with `content: undefined` is rejected outright by+ // Groq ("'content' is missing", HTTP 400) — this was a live bug: every+ // llmComplete() caller that omits `system` (e.g. the fact-checker's+ // generateSearchQueries/analyzeResults) 400'd on the Groq lane instead+ // of falling through cleanly. Only emit the system message when one was+ // actually supplied.+ ...(system ? [{ role: 'system', content: system }] : []),{ role: 'user', content: user },],}),diff --git a/api/_lib/pump-launch.js b/api/_lib/pump-launch.jsindex 2dcd3091e..1c3b38e9d 100644--- a/api/_lib/pump-launch.js+++ b/api/_lib/pump-launch.js@@ -19,6 +19,14 @@ import { solanaConnection } from './agent-pumpfun.js';import { submitProtected } from './execution-engine.js';import { grindMintKeypair } from './pump-vanity.js';import { fetchSafePublicUrlPinned, SsrfBlockedError } from './ssrf-guard.js';+import {+ claimMatchingPattern,+ peekReservedSecret,+ releaseReservation,+ reserveAndReveal,+ isDbUnavailableError,+} from './vanity-inventory-store.js';+import { openSecret } from './vanity-vault.js';const PUMP_IPFS_ENDPOINT = 'https://pump.fun/api/ipfs';@@ -176,9 +184,13 @@ export async function uploadPumpMetadata({* @param {string} [opts.vanityPrefix]* @param {string} [opts.vanitySuffix]* @param {boolean} [opts.vanityIgnoreCase]+ * @param {Keypair} [opts.mintKeypair] pre-resolved mint (e.g. claimed from+ * inventory) — skips grinding entirely+ * when supplied.* @param {('mainnet'|'devnet')} [opts.network]* @returns {Promise<{ mint:string, signature:string, creator:string,- * vanityIterations:number, vanityDurationMs:number }>}+ * vanityIterations:number, vanityDurationMs:number,+ * vanitySource:('inventory'|'ground'|null) }>}*/export async function launchPumpToken({launcher,@@ -189,6 +201,7 @@ export async function launchPumpToken({vanityPrefix,vanitySuffix,vanityIgnoreCase = false,+ mintKeypair = null,network = 'mainnet',}) {let creatorPk;@@ -202,12 +215,23 @@ export async function launchPumpToken({creatorPk = launcher.publicKey;}- const { keypair: mint, iterations: vanityIterations, durationMs: vanityDurationMs } =- await grindMintKeypair({- prefix: vanityPrefix,- suffix: vanitySuffix,- ignoreCase: vanityIgnoreCase,- });+ let mint, vanityIterations, vanityDurationMs, vanitySource;+ if (mintKeypair) {+ // Instant path: a pre-ground address from vanity inventory already+ // matches the requested pattern — no grinding needed.+ mint = mintKeypair;+ vanityIterations = 0;+ vanityDurationMs = 0;+ vanitySource = 'inventory';+ } else {+ ({ keypair: mint, iterations: vanityIterations, durationMs: vanityDurationMs } =+ await grindMintKeypair({+ prefix: vanityPrefix,+ suffix: vanitySuffix,+ ignoreCase: vanityIgnoreCase,+ }));+ vanitySource = vanityPrefix || vanitySuffix ? 'ground' : null;+ }const { PumpSdk } = await import('@pump-fun/pump-sdk');const sdk = new PumpSdk();@@ -250,5 +274,71 @@ export async function launchPumpToken({creator: creatorPk.toBase58(),vanityIterations,vanityDurationMs,+ vanitySource,};}++/**+ * Instant vanity-mint upsell: try to fulfill a vanityPrefix/vanitySuffix+ * request for pump-launch from the pre-ground inventory instead of grinding+ * live. Shares the exact same atomic claim + single-use reveal path premium+ * buys use (api/_lib/vanity-inventory-store.js) — a hit is reserved,+ * decrypted, and (once the caller has actually used the key to launch the+ * token — i.e. it's committed on-chain no matter what) revealed and+ * destroyed so it can never be handed out again. No price ceiling is applied+ * here (unlike vanity.js's live-grind tier): pump-launch already charges one+ * flat fee regardless of how hard the requested vanity pattern is to grind,+ * so serving from inventory is strictly cheaper for the server and no worse+ * for the buyer than the live grind it replaces.+ *+ * Returns null on any miss or failure — DB down, no match, decrypt error —+ * so the caller falls straight through to launchPumpToken()'s live grind,+ * unchanged.+ *+ * @param {object} opts+ * @param {string} [opts.prefix]+ * @param {string} [opts.suffix]+ * @param {boolean} [opts.ignoreCase]+ * @param {string} opts.paymentId unique per launch attempt (any locally+ * unique string — only used to correlate this+ * claim's reserve → decrypt → reveal steps).+ * @param {string} [opts.purchaser]+ * @returns {Promise<{ mintKeypair:Keypair, address:string, reveal:Function, release:Function } | null>}+ */+export async function claimVanityMintFromInventory({ prefix, suffix, ignoreCase = false, paymentId, purchaser }) {+ if ((!prefix && !suffix) || !paymentId) return null;++ let claim;+ try {+ claim = await claimMatchingPattern({ prefix, suffix, ignoreCase, format: 'keypair', paymentId, purchaser });+ } catch (err) {+ if (!isDbUnavailableError(err)) {+ console.error('[pump-launch] inventory claim lookup failed; falling back to grind', err?.message || err);+ }+ return null;+ }+ if (!claim.ok) return null;++ const item = claim.item;+ try {+ const peek = await peekReservedSecret(item.address, { paymentId });+ if (!peek.ok) throw new Error(peek.reason);+ const bundle = JSON.parse(await openSecret(peek.ciphertext, peek.scheme));+ const mintKeypair = Keypair.fromSecretKey(Uint8Array.from(bundle.secretKey));+ if (mintKeypair.publicKey.toBase58() !== item.address) {+ throw new Error('decrypted key does not match the claimed inventory address');+ }+ return {+ mintKeypair,+ address: item.address,+ // The caller invokes these AFTER using (or failing to use) the key,+ // so the reservation is only ever finalized once the outcome is known.+ reveal: () => reserveAndReveal(item.address, { paymentId }),+ release: () => releaseReservation(item.address, { paymentId }),+ };+ } catch (err) {+ console.error('[pump-launch] inventory decrypt failed; releasing + falling back to grind', err?.message || err);+ await releaseReservation(item.address, { paymentId }).catch(() => {});+ return null;+ }+}diff --git a/api/_lib/scene-graph-compose.js b/api/_lib/scene-graph-compose.jsnew file mode 100644index 000000000..3c8d52e8c--- /dev/null+++ b/api/_lib/scene-graph-compose.js@@ -0,0 +1,379 @@+// Scene-graph composer — merges a forged Diorama (objects + ground + lighting)+// into ONE glTF 2.0 binary using @gltf-transform, so a text-composed world+// exports as a single GLB with every object as a named, selectable node —+// ready to drop into Scene Studio (/scene?model=…) or any other glTF-aware app.+//+// Reuses the same NodeIO + mergeDocuments pattern as api/_lib/bake.js (avatar+// appearance baking), but for a whole scene instead of a rig: each forged+// object's GLB is merged in and re-parented under a named group node at its+// diorama position/rotation/scale (mirroring src/diorama/renderer.js's+// fitGltfScene footprint-normalization so the exported file matches what the+// live diorama shows), plus a real ground disc (tinted per the diorama's+// ground/palette) and a KHR_lights_punctual sun + fill light tuned to the+// diorama's mood. The output needs no viewer-side reconstruction: open it+// anywhere and the world reads the same.+//+// Partial failure is a first-class outcome, not an error path: objects that+// never forged (still 'pending'/'forging') or failed are reported back in+// `skipped` and simply omitted from the graph — the export always returns the+// best real scene it can build from what exists.++import { Document, NodeIO } from '@gltf-transform/core';+import { ALL_EXTENSIONS, KHRLightsPunctual } from '@gltf-transform/extensions';+import { mergeDocuments, prune, dedup, unpartition } from '@gltf-transform/functions';+import * as THREE from 'three';+import { MOOD_LIGHT, ISLAND_RADIUS, normalizeDiorama } from '../../src/diorama/schema.js';++// Matches TARGET_FOOTPRINT in src/diorama/renderer.js — keeps a forged object's+// on-screen size in the exported GLB identical to the live diorama stage.+const TARGET_FOOTPRINT = 1.4;+const FETCH_TIMEOUT_MS = 30_000;+const MAX_SOURCE_GLB_BYTES = 64 * 1024 * 1024;++let _ioPromise = null;+async function sharedIO() {+ if (_ioPromise) return _ioPromise;+ _ioPromise = (async () => {+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);+ // Forged GLBs are plain (uncompressed) by default, but a saved diorama may+ // reference a caller-requested draco/meshopt variant or a user-uploaded+ // asset — register both decoders so every real-world source reads cleanly.+ try {+ const { MeshoptDecoder, MeshoptEncoder } = await import('meshoptimizer');+ await Promise.all([MeshoptDecoder.ready, MeshoptEncoder.ready]);+ io.registerDependencies({ 'meshopt.decoder': MeshoptDecoder, 'meshopt.encoder': MeshoptEncoder });+ } catch (err) {+ console.warn('[scene-graph-compose] meshopt dependency unavailable:', err?.message);+ }+ try {+ const d = await import('draco3dgltf');+ const draco3d = d.default ?? d;+ io.registerDependencies({+ 'draco3d.decoder': await draco3d.createDecoderModule(),+ 'draco3d.encoder': await draco3d.createEncoderModule(),+ });+ } catch (err) {+ console.warn('[scene-graph-compose] draco dependency unavailable:', err?.message);+ }+ return io;+ })();+ return _ioPromise;+}++/**+ * Compose a diorama's forged objects + ground + lighting into one GLB.+ *+ * @param {object} dioramaInput — an untrusted Diorama-shaped object (see+ * src/diorama/schema.js). Only objects with status:'ready' and a glbUrl are+ * placed; the rest are reported in `skipped` for a graceful partial export.+ * @returns {Promise<{+ * bytes: Uint8Array,+ * exportedCount: number,+ * totalCount: number,+ * skipped: {id:string, label:string, reason:string}[],+ * }>}+ */+export async function composeSceneGlb(dioramaInput) {+ const { ok, diorama, errors } = normalizeDiorama(dioramaInput);+ if (!ok) {+ throw Object.assign(new Error(`invalid diorama: ${errors.join(', ')}`), { code: 'invalid_diorama' });+ }++ const ready = diorama.objects.filter((o) => o.status === 'ready' && o.glbUrl);+ const skipped = diorama.objects+ .filter((o) => !(o.status === 'ready' && o.glbUrl))+ .map((o) => ({ id: o.id, label: o.label, reason: o.status === 'failed' ? 'forge_failed' : 'not_forged' }));++ if (ready.length === 0) {+ throw Object.assign(+ new Error('No forged objects to export — every object failed or is still pending.'),+ { code: 'nothing_to_export' },+ );+ }++ const io = await sharedIO();+ const doc = new Document();+ const buffer = doc.createBuffer('scene');+ const root = doc.getRoot();+ const asset = root.getAsset();+ asset.generator = `${asset.generator || ''} / three.ws diorama scene-composer @gltf-transform`.trim();+ asset.extras = {+ title: diorama.title,+ prompt: diorama.prompt,+ mood: diorama.mood,+ ground: diorama.ground,+ island: diorama.island,+ palette: diorama.palette,+ source: 'https://three.ws/diorama',+ exportedAt: new Date().toISOString(),+ };++ const scene = doc.createScene(diorama.title || 'Diorama');+ doc.setDefaultScene(scene);++ scene.addChild(buildGroundNode(doc, buffer, diorama));+ for (const light of buildLightNodes(doc, diorama)) scene.addChild(light);++ const objectsGroup = doc.createNode('Objects');+ scene.addChild(objectsGroup);++ let exportedCount = 0;+ for (const obj of ready) {+ try {+ const objBytes = await fetchGlb(obj.glbUrl);+ const objDoc = await io.readBinary(objBytes);+ const objScene = objDoc.getRoot().getDefaultScene() || objDoc.getRoot().listScenes()[0] || null;+ const rootSources = objScene+ ? objScene.listChildren()+ : objDoc.getRoot().listNodes().filter((n) => !n.getParentNode());+ if (!rootSources.length) {+ skipped.push({ id: obj.id, label: obj.label, reason: 'empty_glb' });+ continue;+ }++ const map = mergeDocuments(doc, objDoc);+ const mergedRoots = rootSources.map((n) => map.get(n)).filter(Boolean);+ if (!mergedRoots.length) {+ skipped.push({ id: obj.id, label: obj.label, reason: 'merge_failed' });+ continue;+ }++ const raw = doc.createNode(`${obj.label} (source)`);+ for (const n of mergedRoots) raw.addChild(n);++ const { min, max } = safeBounds(raw);+ const size = [max[0] - min[0], max[1] - min[1], max[2] - min[2]];+ const footprint = Math.max(size[0], size[2]) || Math.max(size[0], size[1], size[2]) || 1;+ const norm = (TARGET_FOOTPRINT / footprint) * (obj.scale || 1);+ const center = [(min[0] + max[0]) / 2, min[1], (min[2] + max[2]) / 2];+ raw.setTranslation([-center[0], -center[1], -center[2]]);++ const wrapper = doc+ .createNode(obj.label || obj.prompt || `Object ${exportedCount + 1}`)+ .setTranslation([obj.position[0], obj.position[1] || 0, obj.position[2]])+ .setRotation(yawQuaternion(obj.rotationY || 0))+ .setScale([norm, norm, norm]);+ wrapper.addChild(raw);+ wrapper.setExtras({ objectId: obj.id, prompt: obj.prompt, sourceGlb: obj.glbUrl });++ objectsGroup.addChild(wrapper);+ exportedCount++;+ } catch (err) {+ console.warn(`[scene-graph-compose] object "${obj.id}" failed to merge:`, err?.message);+ skipped.push({ id: obj.id, label: obj.label, reason: 'fetch_or_merge_error' });+ }+ }++ if (exportedCount === 0) {+ throw Object.assign(new Error('Every forged object failed to merge into the scene.'), {+ code: 'nothing_to_export',+ });+ }++ try {+ await doc.transform(unpartition(), prune(), dedup());+ } catch (err) {+ console.warn('[scene-graph-compose] cleanup transform failed, writing unoptimized:', err?.message);+ await doc.transform(unpartition());+ }++ const bytes = await io.writeBinary(doc);+ return { bytes, exportedCount, totalCount: diorama.objects.length, skipped };+}++// ── Ground ───────────────────────────────────────────────────────────────++function buildGroundNode(doc, buffer, diorama) {+ const segments = 48;+ const radius = ISLAND_RADIUS;+ const vertCount = segments + 2;+ const positions = new Float32Array(vertCount * 3);+ const normals = new Float32Array(vertCount * 3);+ const uvs = new Float32Array(vertCount * 2);++ normals[1] = 1;+ uvs[0] = 0.5;+ uvs[1] = 0.5;+ for (let i = 0; i <= segments; i++) {+ const a = (i / segments) * Math.PI * 2;+ const x = Math.cos(a) * radius;+ const z = Math.sin(a) * radius;+ const vi = (i + 1) * 3;+ positions[vi] = x;+ positions[vi + 1] = 0;+ positions[vi + 2] = z;+ normals[vi + 1] = 1;+ const ui = (i + 1) * 2;+ uvs[ui] = 0.5 + Math.cos(a) * 0.5;+ uvs[ui + 1] = 0.5 + Math.sin(a) * 0.5;+ }+ const indices = new Uint16Array(segments * 3);+ for (let i = 0; i < segments; i++) {+ indices[i * 3] = 0;+ indices[i * 3 + 1] = i + 1;+ indices[i * 3 + 2] = i + 2;+ }++ const position = doc.createAccessor('ground-position').setType('VEC3').setArray(positions).setBuffer(buffer);+ const normal = doc.createAccessor('ground-normal').setType('VEC3').setArray(normals).setBuffer(buffer);+ const uv = doc.createAccessor('ground-uv').setType('VEC2').setArray(uvs).setBuffer(buffer);+ const index = doc.createAccessor('ground-index').setType('SCALAR').setArray(indices).setBuffer(buffer);++ const rgb = hexToLinearRgb(diorama.palette.ground) || [0.5, 0.6, 0.4];+ const material = doc+ .createMaterial('Ground')+ .setBaseColorFactor([rgb[0], rgb[1], rgb[2], 1])+ .setRoughnessFactor(diorama.ground === 'water' ? 0.15 : diorama.ground === 'snow' ? 0.7 : 0.95)+ .setMetallicFactor(0);++ const primitive = doc+ .createPrimitive()+ .setAttribute('POSITION', position)+ .setAttribute('NORMAL', normal)+ .setAttribute('TEXCOORD_0', uv)+ .setIndices(index)+ .setMaterial(material);++ const mesh = doc.createMesh('Ground').addPrimitive(primitive);+ return doc.createNode('Ground').setMesh(mesh);+}++// ── Lighting ─────────────────────────────────────────────────────────────++function buildLightNodes(doc, diorama) {+ const ext = doc.createExtension(KHRLightsPunctual);+ const moodKey = MOOD_LIGHT[diorama.mood] ? diorama.mood : 'day';+ const ml = MOOD_LIGHT[moodKey];+ const accent = hexToLinearRgb(diorama.palette.accent) || [1, 0.9, 0.7];+ const white = [1, 1, 1];++ const elev = clamp(ml.sunElevation, -0.2, 1) * (Math.PI / 2);+ const az = Math.PI * 0.25;+ const dist = 14;+ const sunPos = [Math.cos(elev) * Math.cos(az) * dist, Math.max(3, Math.sin(elev) * dist + 6), Math.cos(elev) * Math.sin(az) * dist];++ const sun = ext+ .createLight('Sun')+ .setType('directional')+ .setIntensity(Math.max(0.4, ml.sunIntensity) * 2.5)+ .setColor(lerpRgb(white, accent, 0.35));+ const sunNode = doc+ .createNode('Sun')+ .setExtension('KHR_lights_punctual', sun)+ .setTranslation(sunPos)+ .setRotation(directionQuaternion(sunPos));++ const fill = ext+ .createLight('Fill Light')+ .setType('point')+ .setIntensity(Math.max(0.15, ml.ambient) * 6)+ .setColor(accent)+ .setRange(ISLAND_RADIUS * 3.2);+ const fillNode = doc+ .createNode('Fill Light')+ .setExtension('KHR_lights_punctual', fill)+ .setTranslation([-ISLAND_RADIUS * 0.6, 3, ISLAND_RADIUS * 0.6]);++ return [sunNode, fillNode];+}++// ── Fetch ────────────────────────────────────────────────────────────────++async function fetchGlb(url) {+ if (!/^https?:\/\//i.test(url)) {+ throw new Error(`refusing non-http glbUrl: ${url}`);+ }+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);+ try {+ const res = await fetch(url, { signal: controller.signal });+ if (!res.ok) throw new Error(`GLB fetch failed: HTTP ${res.status}`);+ const buf = new Uint8Array(await res.arrayBuffer());+ if (buf.byteLength > MAX_SOURCE_GLB_BYTES) {+ throw new Error(`GLB too large (${buf.byteLength} bytes)`);+ }+ return buf;+ } finally {+ clearTimeout(timer);+ }+}++// ── Math helpers ─────────────────────────────────────────────────────────++function yawQuaternion(rotationY) {+ const half = rotationY / 2;+ return [0, Math.sin(half), 0, Math.cos(half)];+}++// Orients a node so its local -Z axis (the KHR_lights_punctual directional+// convention) points from `pos` toward the scene origin.+function directionQuaternion(pos) {+ const from = new THREE.Vector3(0, 0, -1);+ const to = new THREE.Vector3(-pos[0], -pos[1], -pos[2]).normalize();+ const q = new THREE.Quaternion().setFromUnitVectors(from, to);+ return [q.x, q.y, q.z, q.w];+}++function safeBounds(node) {+ // getBounds walks meshes only; a node with non-mesh children (e.g. an+ // avatar's skeleton-only subtree) can legitimately report an empty box.+ // Fall back to a unit cube around the origin so normalization never divides+ // by zero for a pathological source GLB.+ try {+ const box = new THREE.Box3();+ accumulateBounds(node, new THREE.Matrix4(), box);+ if (box.isEmpty()) throw new Error('empty bounds');+ return { min: [box.min.x, box.min.y, box.min.z], max: [box.max.x, box.max.y, box.max.z] };+ } catch {+ return { min: [-0.5, -0.5, -0.5], max: [0.5, 0.5, 0.5] };+ }+}++// Minimal recursive AABB accumulation over a gltf-transform Node's mesh+// primitives, purely from POSITION accessor bounds — avoids pulling the full+// `getBounds` world-space machinery (which expects a Document attached to a+// Scene) for a node we're deliberately keeping detached during normalization.+function accumulateBounds(node, matrix, box) {+ const t = node.getTranslation();+ const r = node.getRotation();+ const s = node.getScale();+ const local = new THREE.Matrix4().compose(+ new THREE.Vector3(...t),+ new THREE.Quaternion(...r),+ new THREE.Vector3(...s),+ );+ const world = matrix.clone().multiply(local);++ const mesh = node.getMesh();+ if (mesh) {+ for (const prim of mesh.listPrimitives()) {+ const pos = prim.getAttribute('POSITION');+ if (!pos) continue;+ const arr = pos.getArray();+ const v = new THREE.Vector3();+ for (let i = 0; i < arr.length; i += 3) {+ v.set(arr[i], arr[i + 1], arr[i + 2]).applyMatrix4(world);+ box.expandByPoint(v);+ }+ }+ }+ for (const child of node.listChildren()) accumulateBounds(child, world, box);+}++function hexToLinearRgb(hex) {+ if (typeof hex !== 'string' || !/^#[0-9a-f]{6}$/i.test(hex)) return null;+ const n = parseInt(hex.slice(1), 16);+ return [srgbToLinear(((n >> 16) & 0xff) / 255), srgbToLinear(((n >> 8) & 0xff) / 255), srgbToLinear((n & 0xff) / 255)];+}++function srgbToLinear(c) {+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);+}++function lerpRgb(a, b, t) {+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];+}++function clamp(v, lo, hi) {+ return Math.min(hi, Math.max(lo, v));+}diff --git a/api/_lib/vanity-inventory-store.js b/api/_lib/vanity-inventory-store.jsindex 7211f9e24..1c431e267 100644--- a/api/_lib/vanity-inventory-store.js+++ b/api/_lib/vanity-inventory-store.js@@ -351,6 +351,41 @@ export async function claimMatchingPattern({return { ok: true, item: shapePublic(row) };}+/**+ * Read-only stock check: does an AVAILABLE item exist whose real address+ * satisfies this prefix/suffix pattern? Never reserves — used to quote the+ * premium long-pattern tier in api/x402/vanity.js honestly BEFORE issuing a+ * 402 (so a buyer is never asked to pay for a pattern that isn't in stock).+ * The actual claim (with claimMatchingPattern's FOR UPDATE SKIP LOCKED race+ * safety) only happens after payment verifies.+ *+ * @param {object} opts+ * @param {string} [opts.prefix]+ * @param {string} [opts.suffix]+ * @param {boolean} [opts.ignoreCase]+ * @param {string} [opts.format='keypair']+ * @returns {Promise<boolean>}+ */+export async function hasAvailableMatch({ prefix = '', suffix = '', ignoreCase = false, format = 'keypair' }) {+ const pfx = String(prefix || '');+ const sfx = String(suffix || '');+ if (!pfx && !sfx) return false;++ let where = sql`status = 'available' AND format = ${format}`;+ if (pfx) {+ where = ignoreCase+ ? sql`${where} AND lower(left(address, ${pfx.length})) = ${pfx.toLowerCase()}`+ : sql`${where} AND left(address, ${pfx.length}) = ${pfx}`;+ }+ if (sfx) {+ where = ignoreCase+ ? sql`${where} AND lower(right(address, ${sfx.length})) = ${sfx.toLowerCase()}`+ : sql`${where} AND right(address, ${sfx.length}) = ${sfx}`;+ }+ const [row] = await sql`SELECT 1 FROM vanity_inventory WHERE ${where} LIMIT 1`;+ return Boolean(row);+}+/*** Non-destructive read of the sealed ciphertext for a row reserved by THIS* payment. The delivery endpoint calls this AFTER reserve but BEFORE settle todiff --git a/api/cron/vanity-inventory-replenish.js b/api/cron/vanity-inventory-replenish.jsnew file mode 100644index 000000000..5061f54e3--- /dev/null+++ b/api/cron/vanity-inventory-replenish.js@@ -0,0 +1,135 @@+// @ts-check+// GET /api/cron/vanity-inventory-replenish — keep the premium vanity shelf stocked.+//+// The instant-delivery tiers (api/x402/vanity-premium.js, the inventory fast path+// in api/x402/vanity.js and api/_lib/pump-launch.js) can only serve from stock —+// they never grind inline. This tick is the demand side of that contract:+//+// 1. LOW-STOCK TRIGGER. Reads inventoryStats(). When available stock (or the+// distinct-tier count) drops below a watermark, it fires the batch grinder+// AHEAD OF running out — never grinds inline itself (a 4–5 char batch run+// takes minutes-to-hours on spot CPU, far past any request's budget). The+// real trigger is a Cloud Run Jobs `run` execution (workers/vanity-grinder,+// deployed by scripts/gcp/vanity-grind-deploy.sh) using the same GCP OAuth+// token machinery Vertex/KMS already use (api/_lib/gcp-auth.js) — a real+// API call, not a stub. Deduped so a sustained low-stock window fires the+// job once, not every tick.+// 2. SWEEP. Runs sweepExpiredSecrets() (api/_lib/vanity-inventory-store.js) so+// any retention_days > 0 rows past their window get their ciphertext+// destroyed — the delete-after-reveal default (retention_days = 0) already+// does this at reveal time, so this is a backstop for the opt-in retention+// path, not the common case.+//+// Graceful degradation (per repo rules — never a mock, never a silent no-op):+// when the job trigger isn't configured (no GOOGLE_CLOUD_PROJECT or GCP auth),+// this pages ops with the exact manual command instead of pretending to have+// replenished anything.++import { error, json, method, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { inventoryStats, sweepExpiredSecrets, isDbUnavailableError } from '../_lib/vanity-inventory-store.js';+import { getGcpAccessToken, gcpAuthConfigured } from '../_lib/gcp-auth.js';++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ error(res, 503, 'not_configured', 'CRON_SECRET unset');+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}++// Below this many available items platform-wide, fire a replenishment run.+// Overridable so ops can tune the shelf depth without a redeploy.+const LOW_WATERMARK = Number(process.env.VANITY_INVENTORY_LOW_WATERMARK || 25);++const PROJECT = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCP_PROJECT_ID || '';+const REGION = process.env.VANITY_GRIND_REGION || 'us-central1';+const JOB = process.env.VANITY_GRIND_JOB || 'vanity-grinder';++function jobConfigured() {+ return Boolean(PROJECT) && gcpAuthConfigured();+}++// Fire the Cloud Run Job execution — the exact same job+// scripts/gcp/vanity-grind-deploy.sh provisions. Real REST call against the+// Cloud Run Admin API v2 (`jobs.run`), authenticated with the platform's shared+// GCP service-account token. Returns the execution name on success.+async function triggerGrindJob() {+ const token = await getGcpAccessToken();+ const url = `https://run.googleapis.com/v2/projects/${PROJECT}/locations/${REGION}/jobs/${JOB}:run`;+ const res = await fetch(url, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({}),+ });+ if (!res.ok) {+ const detail = await res.text().catch(() => res.status);+ throw new Error(`Cloud Run Jobs run failed (${res.status}): ${String(detail).slice(0, 300)}`);+ }+ const data = await res.json();+ return data?.metadata?.name || data?.name || null;+}++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET'])) return;+ if (!requireCron(req, res)) return;++ let stats;+ try {+ stats = await inventoryStats();+ } catch (err) {+ if (isDbUnavailableError(err)) {+ return json(res, 200, { ok: true, skipped: 'db_unavailable' });+ }+ await sendOpsAlert('Vanity inventory replenish — stats query failed', err.message, { signature: 'vanity-replenish-stats-failed' });+ return json(res, 200, { ok: false, error: err.message });+ }++ let swept = 0;+ try {+ ({ destroyed: swept } = await sweepExpiredSecrets());+ } catch (err) {+ // Non-fatal — the low-stock check below still matters even if the sweep+ // fails on this tick; it will retry next tick.+ console.error('[vanity-inventory-replenish] sweep failed', err?.message || err);+ }++ const low = stats.available < LOW_WATERMARK;+ if (!low) {+ return json(res, 200, { ok: true, low_stock: false, stats, swept });+ }++ if (!jobConfigured()) {+ await sendOpsAlert(+ 'Vanity inventory low — replenishment job not configured',+ `Available: ${stats.available} (watermark ${LOW_WATERMARK}). Run manually: ` ++ `PROJECT_ID=<gcp-project> ./scripts/gcp/vanity-grind-deploy.sh --run — or set ` ++ `GOOGLE_CLOUD_PROJECT (+ GCP auth) so this cron can trigger the Cloud Run Job itself.`,+ { signature: 'vanity-replenish-not-configured' },+ );+ return json(res, 200, { ok: true, low_stock: true, configured: false, stats, swept });+ }++ try {+ const execution = await triggerGrindJob();+ await sendOpsAlert(+ '🟡 Vanity inventory low — replenishment grind triggered',+ `Available: ${stats.available} (watermark ${LOW_WATERMARK}). Fired Cloud Run Job ` ++ `${JOB} in ${REGION}. Execution: ${execution || '(unnamed)'}.`,+ { signature: `vanity-replenish-fired:${new Date().toISOString().slice(0, 13)}` },+ );+ return json(res, 200, { ok: true, low_stock: true, configured: true, triggered: true, execution, stats, swept });+ } catch (err) {+ await sendOpsAlert('Vanity inventory low — replenishment trigger failed', err.message, { signature: 'vanity-replenish-trigger-failed' });+ return json(res, 200, { ok: false, low_stock: true, error: err.message, stats, swept });+ }+});diff --git a/api/openapi-json.js b/api/openapi-json.jsindex 376f02c39..90ea841e3 100644--- a/api/openapi-json.js+++ b/api/openapi-json.js@@ -13,6 +13,7 @@import { env } from './_lib/env.js';import { cors, json, method, wrap } from './_lib/http.js';+import { providerCatalog } from './v1/_providers.js';// Single source of truth for the protocol list on every paid operation. Each// entry is one supported payment protocol; per-network payment lanes (Base /@@ -20,6 +21,91 @@ import { cors, json, method, wrap } from './_lib/http.js';// `accepts[]` array — see api/_lib/x402-spec.js `paymentRequirements()`.const X402_PROTOCOLS = [{ x402: {} }];+// USDC atomics (6 decimals) → a decimal string, trimmed to the shortest+// precision that round-trips (min 2 places) — mirrors the formatting already+// used by hand-authored entries below ('0.001', '5.00', …).+function formatUsd(atomics) {+ const n = Number(atomics) / 1e6;+ if (!Number.isFinite(n)) return '0.00';+ let s = n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');+ const [, dec = ''] = s.split('.');+ if (!s.includes('.')) s += '.00';+ else if (dec.length < 2) s += '0'.repeat(2 - dec.length);+ return s;+}++// GET /api/v1/x/{provider}/{endpoint} paths, rendered live from the registry+// (api/v1/_providers.js `providerCatalog()`) — never hand-enumerated, so this+// document can never drift from the real aggregated endpoint surface no+// matter which provider prompts have or haven't landed. See docs/api-+// reference.md "Unified API — /api/v1/x aggregator" for the full billing-lane+// writeup and the public storefront at /crypto-api.+function aggregatorPaths() {+ const paths = {};+ for (const provider of providerCatalog()) {+ for (const ep of provider.endpoints) {+ const priceUsd = formatUsd(ep.price_usdc_atomics);+ const billing =+ 'Billing lanes, in order: ' ++ (ep.free+ ? `free tier (${ep.free.perMin}/min, ${ep.free.perDay}/day per IP, no credentials) → `+ : '') ++ `x402 pay-per-call ($${priceUsd} USDC via HTTP 402, no credentials) — or send your own upstream ` ++ `key via BYOK, or authenticate with a three.ws API key / OAuth session / browser session for the plan lane.`;+ const description = `${ep.summary} ${billing}`;++ const operation = {+ operationId: `v1_x_${provider.id}_${ep.id}`.replace(/[^a-zA-Z0-9_]/g, '_'),+ summary: `${provider.name}: ${ep.summary}`,+ description,+ tags: ['Crypto API (aggregator)'],+ security: [{}, { bearerAuth: [] }, { apiKeyAuth: [] }],+ responses: {+ 200: { description: 'Normalized upstream response, wrapped as { data, _meta }' },+ 400: { description: 'Missing or invalid parameter' },+ 402: { description: 'Payment Required (x402) — no credentials and free quota (if any) exhausted' },+ 404: { description: 'Unknown provider/endpoint pair' },+ 429: { description: 'Rate limited' },+ },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: priceUsd },+ protocols: X402_PROTOCOLS,+ note: ep.free+ ? `Free before payment: ${ep.free.perMin}/min, ${ep.free.perDay}/day per IP, no credentials required.`+ : undefined,+ },+ };++ if (ep.method === 'POST') {+ operation.requestBody = {+ required: true,+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ description: Object.entries(ep.params || {})+ .map(([k, v]) => `${k}: ${v}`)+ .join('; ') || 'Forwarded as-is to the upstream JSON body.',+ },+ },+ },+ };+ } else {+ operation.parameters = Object.entries(ep.params || {}).map(([name, desc]) => ({+ name,+ in: 'query',+ required: typeof desc === 'string' && /\(required\)/.test(desc),+ schema: { type: 'string' },+ description: desc,+ }));+ }++ paths[ep.path] = { [ep.method.toLowerCase()]: operation };+ }+ }+ return paths;+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -47,9 +133,23 @@ export default wrap(async (req, res) => {'Available MCP tools: list_my_avatars, get_avatar, search_public_avatars, ' +'render_avatar, delete_avatar, validate_model, inspect_model, optimize_model. ' +'Paid REST endpoints under /api/x402/* settle in USDC over ' +- 'x402 (HTTP 402); pay programmatically with @x402/fetch — no API key required.',+ 'x402 (HTTP 402); pay programmatically with @x402/fetch — no API key required. ' ++ 'GET /api/v1/x/{provider}/{endpoint} (tag "Crypto API (aggregator)" below) bundles ' ++ 'CoinGecko, DefiLlama, Jupiter, DexScreener, Solana RPC and more behind one bill — ' ++ 'free tier, BYOK, a three.ws plan, or x402, in that order. Storefront: ' ++ origin ++ '/crypto-api. Discovery: GET /api/v1/x.',},servers: [{ url: origin }],+ tags: [+ {+ name: 'Crypto API (aggregator)',+ description:+ 'Third-party crypto/DeFi/on-chain APIs re-offered as one bill under /api/v1/x — ' ++ 'rendered live from the provider registry (api/v1/_providers.js). See /crypto-api ' ++ 'and docs/api-reference.md § Unified API.',+ },+ ],components: {securitySchemes: {bearerAuth: {@@ -78,6 +178,11 @@ export default wrap(async (req, res) => {},},paths: {+ // Rendered live from the provider registry — see aggregatorPaths()+ // above. Spread first so a duplicate key below always wins (none+ // today: aggregator paths live under /api/v1/x/*, hand-authored+ // paths don't).+ ...aggregatorPaths(),'/api/mcp': {post: {operationId: 'mcp_call',diff --git a/api/v1/README.md b/api/v1/README.mdnew file mode 100644index 000000000..8f4ffd0e1--- /dev/null+++ b/api/v1/README.md@@ -0,0 +1,122 @@+# `api/v1/` — the unified three.ws API++Two things live here:++1. **The platform's own versioned API** (`api/v1/index.js`, `resolve.js`, `sentiment.js`,+ `agents/`, `ai/`, `market/`, `pump/`, `token/`) — first-party endpoints three.ws built.+2. **The aggregator** (`api/v1/x/[...slug].js` + `api/v1/_providers.js`) — a growing bundle+ of third-party crypto/DeFi/on-chain APIs (CoinGecko, DefiLlama, Jupiter, DexScreener,+ Solana RPC, …) re-offered as one bill under `/api/v1/x/<provider>/<endpoint>`. This+ README is about the aggregator.++- **Public storefront:** [`/crypto-api`](https://three.ws/crypto-api) — live provider/+ endpoint table, quickstart, and links, rendered from the same registry as everything below.+- **Machine-readable spec:** [`/openapi.json`](https://three.ws/openapi.json) — generated+ from `providerCatalog()` (see [`api/openapi-json.js`](../openapi-json.js) `aggregatorPaths()`).+- **Human docs:** [`docs/api-reference.md`](../../docs/api-reference.md) § "Unified API —+ `/api/v1/x` aggregator" — the full billing-lane writeup, free-quota table, and one curl per+ provider.+- **Discovery, live:** `GET /api/v1/x` — every provider + endpoint, in JSON, straight from+ production. `GET /api/v1` (`api/v1/index.js`) folds this in under an `aggregator` key+ alongside the platform's first-party endpoints.++## Why an aggregator++An agent that needs a token's price, a swap quote, a chain's TVL, and an ENS lookup+shouldn't juggle four API keys and four rate limits. `api/v1/x` fronts them all: one base+URL, one discovery call, four billing lanes, and per-endpoint response shaping so a caller+gets normalized JSON instead of each upstream's raw (and often huge) payload.++## How a request resolves++```+GET /api/v1/x # discovery — no provider, lists everything+GET /api/v1/x/<provider>/<endpoint>?… # most endpoints+POST /api/v1/x/<provider>/<endpoint> # a few (e.g. openai/chat)+```++One catch-all route, [`api/v1/x/[...slug].js`](x/%5B...slug%5D.js), handles every provider —+adding a provider or endpoint never means a new route file. Each request is dispatched+through [`api/_lib/aggregator.js`](../_lib/aggregator.js) (`executeUpstream`,+`resolveUpstreamKey`, `getPaidHandler`) after billing-lane selection, in this order:++| Lane | Trigger | What happens |+| -------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------- |+| **free** | no credentials, endpoint descriptor carries a `free` quota | served against a real per-(provider, endpoint, IP) quota — see `serveFreeLane` in `x/[...slug].js` |+| **BYOK** | caller sends the provider's own key header (e.g. `x-provider-key`) | pure pass-through to the upstream with the caller's key — no markup, no key custody |+| **plan** | caller authenticates (three.ws API key / OAuth token / session) | uses the platform's own upstream key, billed against the caller's plan |+| **x402** | none of the above, or the free quota is exhausted | standard HTTP 402 challenge — pay per call in USDC, then retry with `X-PAYMENT` |++The free lane exists specifically so "free API" is true, not marketing copy: a scripted+`curl` with zero setup gets real data back, and the *exact same URL* upgrades in place once+the caller adds a key, a payment, or a session — no dead end, no separate "upgrade" endpoint.++## The provider registry — descriptor contract++[`api/v1/_providers.js`](_providers.js) is the single source of truth. Every consumer of the+aggregator — the catch-all route, `providerCatalog()` (discovery JSON), the OpenAPI generator,+the `/crypto-api` storefront, and the docs — reads this file at runtime/build time. **Nothing+downstream hand-enumerates endpoints.** Add a descriptor here and it appears everywhere with+zero other edits.++```js+{+ id: 'coingecko', // url-safe slug — first path segment under /api/v1/x+ name: 'CoinGecko', // human label+ category: 'crypto-market-data', // grouping for discovery+ base: 'https://api.coingecko.com/api/v3', // upstream base URL, no trailing slash+ requiresKey: false, // true when the upstream needs a key to function at all+ envVar: 'COINGECKO_API_KEY', // env var holding three.ws's own platform key (or null)+ byokHeader: 'x-provider-key', // header a caller uses to supply THEIR OWN key (or null)+ applyKey: (headers, url, key) => { /* place the key where the upstream wants it */ },+ endpoints: [+ {+ id: 'price', // url-safe slug — second path segment+ method: 'GET', // caller-facing verb (what api/v1/x/[...slug].js requires)+ path: '/simple/price', // string, or (query) => string for path params+ query: (q) => ({ ids: required(q.ids, 'ids'), vs_currencies: q.vs_currencies || 'usd' }),+ transform: (data) => data, // (data) => normalized response — default passthrough+ free: { perMin: 30, perDay: 2000 }, // unauthenticated per-IP quota, or omit for none+ priceAtomics: '1000', // x402 price in USDC atomics (6 decimals; "1000" = $0.001)+ scope: 'agents:read', // three.ws OAuth scope required for the plan-billing path+ summary: 'Spot price for one or more coins in any fiat/crypto.', // one line for discovery+ params: { ids: 'comma-separated CoinGecko coin ids… (required)' }, // documented inputs+ },+ ],+}+```++Full field-by-field contract, including `upstreamMethod` (for a caller-facing GET that drives+an upstream POST, e.g. Solana's single JSON-RPC endpoint) and `body`, is documented inline at+the top of [`_providers.js`](_providers.js) — read it before adding a descriptor.++### Adding a provider or endpoint++1. Add a descriptor (or a new `endpoints` entry on an existing one) to `PROVIDERS` in+ [`_providers.js`](_providers.js). No new route file — the catch-all resolves it.+2. Keep `transform()` slim: several upstreams (DexScreener, DefiLlama's `/protocols`,+ CoinGecko's `/coins/{id}`) return multi-hundred-KB payloads; every existing descriptor+ trims to the fields an agent actually reasons over. Follow that pattern.+3. Set `free: { perMin, perDay }` if the upstream's own keyless tier can absorb it — this is+ what makes the endpoint discoverable and usable with zero setup. Omit it for endpoints+ with real per-call cost (e.g. `openai/chat`) or an upstream that requires a key to+ function at all.+4. `docs/api-reference.md` § "Unified API" lists providers and quotas by hand today — update+ it alongside `_providers.js` (the free-quota table there is not yet auto-generated).+5. `tests/openapi-aggregator.test.js` fails the build if a registered endpoint is missing+ from the generated OpenAPI doc — run it after adding a descriptor.+6. Add a `data/changelog.json` entry (tag `feature`) if the new provider is user-visible.++## Related files++- [`api/v1/index.js`](index.js) — `GET /api/v1`, folds `providerCatalog()` into the+ platform's own endpoint discovery document.+- [`api/v1/x/[...slug].js`](x/%5B...slug%5D.js) — the aggregator front door: billing-lane+ selection, rate limiting, usage recording.+- [`api/_lib/aggregator.js`](../_lib/aggregator.js) — `executeUpstream`, `resolveUpstreamKey`,+ `getPaidHandler`: the shared engine every provider runs through.+- [`api/_lib/x402-paid-endpoint.js`](../_lib/x402-paid-endpoint.js) — the x402 challenge/+ settlement machinery `getPaidHandler` wraps around a provider endpoint.+- [`api/openapi-json.js`](../openapi-json.js) — `GET /openapi.json`; `aggregatorPaths()`+ renders every `/api/v1/x/*` path from `providerCatalog()`.+- [`pages/crypto-api.html`](../../pages/crypto-api.html) — the public storefront (`/crypto-api`).diff --git a/api/v1/x/index.js b/api/v1/x/index.jsnew file mode 100644index 000000000..dbab4ee4e--- /dev/null+++ b/api/v1/x/index.js@@ -0,0 +1,17 @@+// GET /api/v1/x — discovery front door.+//+// The real dispatch logic (billing-lane selection, provider/endpoint lookup,+// and the zero-segment discovery response) all live in the catch-all route+// ./[...slug].js, which already handles a zero-segment request correctly+// (`if (slug.length === 0) return json(res, 200, { data: { providers: … } })`).+//+// The file-based router (server/index.mjs `resolveApi`) only checks for a+// sibling `index.js` when a request has zero path segments past `/api/v1/x`+// — a bare `[...slug].js` (Vercel's single-bracket "catch-all", not the+// double-bracket "optional catch-all") never matches zero segments. Without+// this file, `GET /api/v1/x` — the exact URL documented in docs/api-+// reference.md, advertised as `base_url` in providerCatalog()'s discovery+// payload, and fetched by the /crypto-api storefront — 404s in production.+// This file exists purely to make the router find the handler that was+// already correct; no logic is duplicated.+export { default } from './[...slug].js';diff --git a/api/x402/pump-launch.js b/api/x402/pump-launch.jsindex c20d2701c..6c76433de 100644--- a/api/x402/pump-launch.js+++ b/api/x402/pump-launch.js@@ -15,7 +15,10 @@//// pump.fun creator rewards accrue to `creator` (any Solana pubkey the buyer// nominates); default is the launcher. An optional `vanityPrefix`/`vanitySuffix`-// grinds a custom mint address before deploy.+// grinds a custom mint address before deploy — or, when a matching address is+// already sitting in the pre-ground inventory (api/_lib/vanity-inventory-store.js,+// shared with api/x402/vanity-premium.js), it's claimed and used instantly instead+// of grinding one live (see claimVanityMintFromInventory in api/_lib/pump-launch.js).//// The launch runs AFTER payment verification but BEFORE settlement: a bad image// URL, IPFS failure, or RPC error throws here and settlement never runs, so a@@ -31,7 +34,12 @@ import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { readJson } from '../_lib/http.js';import { sql } from '../_lib/db.js';-import { loadLauncherKeypair, uploadPumpMetadata, launchPumpToken } from '../_lib/pump-launch.js';+import {+ loadLauncherKeypair,+ uploadPumpMetadata,+ launchPumpToken,+ claimVanityMintFromInventory,+} from '../_lib/pump-launch.js';import pumpLaunchListing from '../_lib/service-catalog/services/pump-launch.js';import { z } from 'zod';@@ -113,12 +121,17 @@ export const INPUT_SCHEMA = {vanityPrefix: {type: 'string',maxLength: 5,- description: 'Base58 prefix to grind into the mint address (≤5 chars; longer = slower).',+ description:+ 'Base58 prefix to grind into the mint address (≤5 chars; longer = slower). When a ' ++ 'matching pre-ground address is already in stock, it is delivered instantly instead ' ++ 'of grinding — see vanity_source in the response.',},vanitySuffix: {type: 'string',maxLength: 5,- description: 'Base58 suffix to grind into the mint address (≤5 chars; longer = slower).',+ description:+ 'Base58 suffix to grind into the mint address (≤5 chars; longer = slower). Same ' ++ 'instant-inventory upsell as vanityPrefix.',},vanityIgnoreCase: {type: 'boolean',@@ -141,6 +154,7 @@ const OUTPUT_EXAMPLE = {vanity_suffix: null,vanity_iterations: 4821,vanity_duration_ms: 190,+ vanity_source: 'ground',};export const OUTPUT_SCHEMA = {@@ -161,6 +175,14 @@ export const OUTPUT_SCHEMA = {vanity_suffix: { type: ['string', 'null'] },vanity_iterations: { type: 'integer' },vanity_duration_ms: { type: 'number' },+ vanity_source: {+ type: ['string', 'null'],+ enum: ['inventory', 'ground', null],+ description:+ "'inventory': the mint was a pre-ground address served instantly from stock " ++ "(same price, no grind wait). 'ground': mined fresh for this launch. null: no " ++ 'vanityPrefix/vanitySuffix was requested.',+ },},};@@ -267,17 +289,53 @@ export default paidEndpoint({metadataUri = pinned.metadataUri;}- const launched = await launchPumpToken({- launcher,- name: body.name,- symbol: body.symbol,- uri: metadataUri,- creator: body.creator,- vanityPrefix: body.vanityPrefix,- vanitySuffix: body.vanitySuffix,- vanityIgnoreCase: body.vanityIgnoreCase,- network: 'mainnet',- });+ // Vanity upsell: check inventory for a pre-ground mint matching the+ // requested pattern before grinding one live. A hit skips the grind+ // entirely (instant); a miss (or any inventory failure) falls straight+ // through to launchPumpToken's own grind, unchanged. Correlation id is+ // scoped to this single launch attempt — only used to tie the claim's+ // reserve → decrypt → reveal steps together.+ let inventoryMint = null;+ if (body.vanityPrefix || body.vanitySuffix) {+ inventoryMint = await claimVanityMintFromInventory({+ prefix: body.vanityPrefix,+ suffix: body.vanitySuffix,+ ignoreCase: body.vanityIgnoreCase,+ paymentId: `pump-launch:${payer || 'x402'}:${Date.now()}:${Math.random().toString(36).slice(2)}`,+ purchaser: payer,+ });+ }++ let launched;+ try {+ launched = await launchPumpToken({+ launcher,+ name: body.name,+ symbol: body.symbol,+ uri: metadataUri,+ creator: body.creator,+ vanityPrefix: body.vanityPrefix,+ vanitySuffix: body.vanitySuffix,+ vanityIgnoreCase: body.vanityIgnoreCase,+ mintKeypair: inventoryMint?.mintKeypair,+ network: 'mainnet',+ });+ } catch (err) {+ // The mint never made it on-chain — release the inventory claim (if+ // any) back to available so a failed launch doesn't strand stock.+ if (inventoryMint) await inventoryMint.release().catch(() => {});+ throw err;+ }++ // The mint is now live on-chain and irreversibly spent whether we were+ // grinding or claiming from inventory. If we used inventory, finalize the+ // claim now: reveal-and-destroy so the ciphertext is gone and this+ // address can never be served again.+ if (inventoryMint) {+ await inventoryMint.reveal().catch((err) => {+ console.error('[x402/pump-launch] inventory reveal/destroy after launch failed', err?.message || err);+ });+ }const network = 'mainnet';const result = {@@ -294,6 +352,7 @@ export default paidEndpoint({vanity_suffix: body.vanitySuffix || null,vanity_iterations: launched.vanityIterations,vanity_duration_ms: launched.vanityDurationMs,+ vanity_source: launched.vanitySource,};// Index the launch for the catalog / analytics. Best-effort: the token isdiff --git a/api/x402/vanity.js b/api/x402/vanity.jsindex aaf5f4486..73a43fdba 100644--- a/api/x402/vanity.js+++ b/api/x402/vanity.js@@ -69,12 +69,14 @@ import { getServiceIdentity } from '../_lib/vanity-service-key.js';import { registerCert } from '../_lib/vanity-cert-store.js';import {claimMatchingPattern,+ hasAvailableMatch,peekReservedSecret,reserveAndReveal,releaseReservation,isDbUnavailableError,} from '../_lib/vanity-inventory-store.js';import { openSecret } from '../_lib/vanity-vault.js';+import { priceFor } from '../_lib/x402-prices.js';import bs58 from 'bs58';const ROUTE = '/api/x402/vanity';@@ -114,10 +116,35 @@ const PRICE_BY_LENGTH_MNEMONIC = {2: 500_000, // $0.50};-function priceAtomicsFor(format, combinedLength) {+// 4–5 Base58 chars is past what a single 45s server grind can reach (58^4 ≈+// 11.3M attempts ≈ 7.5 min at the WASM engine's ~25k/s; 58^5 ≈ 656M ≈ 7++// hours) — those lengths are ONLY ever fulfilled from the pre-ground premium+// inventory (workers/vanity-grinder, api/x402/vanity-premium.js), never+// ground live. Priced well above the flat per-length grind tiers to reflect+// the batch-CPU cost of stocking them ahead of time; env-overridable per+// api/_lib/x402-prices.js so ops can retune without a redeploy. `format=+// mnemonic` is NOT extended here — the batch grinder only stocks raw+// keypairs (mnemonic grinding is itself ~100× slower to produce ahead of+// time), so mnemonic stays capped at MAX_MNEMONIC_PATTERN_LENGTH.+const PREMIUM_PRICE_BY_LENGTH = {+ 4: () => Number(priceFor('vanity-4', '2500000')), // $2.50 default+ 5: () => Number(priceFor('vanity-5', '10000000')), // $10 default+};++// Keypair patterns up to this length are OFFERED (priced + quoted), but only+// ever served from inventory (see hasAvailableMatch gate below) — never+// ground live. Patterns longer than MAX_SERVER_PATTERN_LENGTH and up to this+// ceiling are the "premium" band.+export const INVENTORY_MAX_PATTERN_LENGTH = 5;++export function priceAtomicsFor(format, combinedLength) {if (format === FORMAT_MNEMONIC) {return PRICE_BY_LENGTH_MNEMONIC[combinedLength] ?? PRICE_BY_LENGTH_MNEMONIC[MAX_MNEMONIC_PATTERN_LENGTH];}+ if (combinedLength > MAX_SERVER_PATTERN_LENGTH) {+ const premium = PREMIUM_PRICE_BY_LENGTH[Math.min(combinedLength, INVENTORY_MAX_PATTERN_LENGTH)];+ if (premium) return premium();+ }return PRICE_BY_LENGTH[combinedLength] ?? PRICE_BY_LENGTH[MAX_SERVER_PATTERN_LENGTH];}@@ -128,8 +155,12 @@ const ROUTE_DESCRIPTION ='you want identifiable at a glance. The server grinds a brand-new keypair to match — ' +'no wallet, account, or SOL required. Two output formats: format=keypair (default) ' +'returns the public address and its secret key (Base58 + 64-byte array), ground in a ' +- 'Rust/WASM ed25519 engine — capped at 3 Base58 chars, priced $0.01 (1 char) / $0.05 ' +- '(2) / $0.25 (3). format=mnemonic returns a BIP-39 seed phrase (12 or 24 words) whose ' ++ 'Rust/WASM ed25519 engine — live-ground up to 3 Base58 chars, priced $0.01 (1 char) / ' ++ '$0.05 (2) / $0.25 (3). Longer 4–5 char patterns are offered too, priced $2.50 (4) / ' ++ '$10 (5), but ONLY ever served from the pre-ground premium inventory (never ground ' ++ 'live) — a pattern with no inventory match 404s as not_in_stock instead of quoting a ' ++ 'price you could never redeem; browse stock at GET /api/x402/vanity-premium. ' ++ 'format=mnemonic returns a BIP-39 seed phrase (12 or 24 words) whose ' +"derived key at m/44'/501'/0'/0' lands on the vanity address, importable as a recovery " +'phrase into Phantom / Solflare / the Solana CLI — capped at 2 chars (~100× slower to ' +'grind), priced $0.05 (1 char) / $0.50 (2). Security model: nothing is ever stored — ' +@@ -137,7 +168,11 @@ const ROUTE_DESCRIPTION ='replay/idempotency cache. Optional sealTo=<X25519 public key> seals the secret to you ' +'(ECIES; x25519-hkdf-sha256-aes256gcm) so the plaintext never appears in the response ' +'or any log — open it client-side with the matching private key. Keyless and ' +- 'account-free: pay-per-call in USDC on Base or Solana mainnet — no API keys, no signup.';+ 'account-free: pay-per-call in USDC on Base or Solana mainnet — no API keys, no signup. ' ++ 'A matching pre-ground address in the premium inventory is delivered instantly instead ' ++ "of grinding one — response.source is 'inventory' (pre-generated server-side, never " ++ "re-served — same one-time delivery guarantee as vanity-premium) or 'ground' (freshly " ++ 'mined this request), and pricing is identical either way.';// Base58 excludes 0/O/I/l. Note also that an address is 32 random bytes// Base58-encoded, so its LEADING characters are not uniformly distributed —@@ -213,6 +248,7 @@ const DISCOVERY_OUTPUT_EXAMPLE = {expectedAttempts: 3364,network: 'solana',explorerUrl: 'https://solscan.io/account/SoEXAMPLEdoNotUse1111111111111111111111111111',+ source: 'ground',};const DISCOVERY_OUTPUT_SCHEMA = {@@ -274,6 +310,14 @@ const DISCOVERY_OUTPUT_SCHEMA = {},network: { type: 'string' },explorerUrl: { type: 'string', format: 'uri' },+ source: {+ type: 'string',+ enum: ['inventory', 'ground'],+ description:+ "'inventory': served instantly from a pre-ground address in the premium inventory " ++ "(delivered once, then destroyed server-side — never re-served). 'ground': mined " ++ 'fresh for this request. Price is the same either way.',+ },certificate: {type: 'object',description:@@ -349,14 +393,21 @@ function parsePattern(req) {}}- const maxLength = format === FORMAT_MNEMONIC ? MAX_MNEMONIC_PATTERN_LENGTH : MAX_SERVER_PATTERN_LENGTH;+ // Keypair patterns get a second, wider ceiling: MAX_SERVER_PATTERN_LENGTH is+ // what the live WASM grinder can reach in the 45s budget; anything up to+ // INVENTORY_MAX_PATTERN_LENGTH is OFFERED but only ever fulfilled from the+ // premium inventory (checked below, before any 402 is quoted — see+ // hasAvailableMatch in the handler). Mnemonic format has no inventory+ // backing, so its ceiling stays the live-grind cap.+ const maxLength =+ format === FORMAT_MNEMONIC ? MAX_MNEMONIC_PATTERN_LENGTH : INVENTORY_MAX_PATTERN_LENGTH;const combinedLength = prefix.length + suffix.length;if (combinedLength > maxLength) {const reason =format === FORMAT_MNEMONIC? `seed-phrase grinding is ~100× slower; drop format=mnemonic for up to ${MAX_SERVER_PATTERN_LENGTH} chars, ` +`or grind longer mnemonic patterns on your own machine`- : 'grind longer patterns in the browser at /vanity';+ : 'grind longer patterns in the browser at /vanity, or check /api/x402/vanity-premium for pre-ground stock';throw Object.assign(new Error(`combined pattern length ${combinedLength} exceeds the ${format} server limit of ` +@@ -365,6 +416,10 @@ function parsePattern(req) {{ status: 400, code: 'pattern_too_long' },);}+ // 4–5 chars (keypair only) is the premium, inventory-only band — never+ // ground live. See hasAvailableMatch gate in the handler and the "not in+ // stock" 404 it returns for a pattern inventory doesn't hold.+ const premiumOnly = format !== FORMAT_MNEMONIC && combinedLength > MAX_SERVER_PATTERN_LENGTH;// Optional confidential delivery: an X25519 public key the secret is sealed// to. Validate the key shape up front so a malformed key is a clean 400@@ -375,7 +430,7 @@ function parsePattern(req) {parseX25519Key(sealTo, 'sealTo');}- return { prefix, suffix, ignoreCase, combinedLength, format, strength, sealTo };+ return { prefix, suffix, ignoreCase, combinedLength, format, strength, sealTo, premiumOnly };}// Confidential delivery: when the caller supplies an X25519 public key, encrypt@@ -516,6 +571,7 @@ async function grindAndShape({ prefix, suffix, ignoreCase, format, strength, seaexpectedAttempts: expectedAttemptsFor(prefix, suffix),network: 'solana',explorerUrl: `https://solscan.io/account/${result.publicKey}`,+ source: 'ground',};}@@ -523,6 +579,74 @@ async function grindAndShape({ prefix, suffix, ignoreCase, format, strength, seareturn attachCertificate(delivered, { prefix, suffix, ignoreCase });}+// ── Instant inventory fast path ──────────────────────────────────────────────+// Before grinding, check whether a pre-ground address from+// api/_lib/vanity-inventory-store.js already satisfies the requested+// prefix/suffix pattern. A hit is claimed atomically (reserve → decrypt →,+// after settle, reveal-and-destroy) and delivered exactly once — the same+// sealing/certificate pipeline as a fresh grind, just without the CPU cost or+// the wait. A miss (no match, or ANY failure along the way — DB down,+// decrypt error) returns null and the caller falls straight through to+// grindAndShape() unchanged. Never throws: an inventory outage must degrade+// to "grind as normal", not break the endpoint.+export async function tryInstantFromInventory(pattern, { paymentId, purchaser }) {+ const { prefix, suffix, ignoreCase, format, combinedLength, sealTo } = pattern;+ if (!paymentId || (!prefix && !suffix) || combinedLength === 0) return null;++ // Guardrail: never hand out an inventory item worth more than the flat+ // price this pattern length already charges — see claimMatchingPattern's+ // maxPriceUsd doc for why. Anything pricier stays reserved for the priced+ // premium tier (/api/x402/vanity-premium).+ const maxPriceUsd = priceAtomicsFor(format, combinedLength) / 1_000_000;++ let claim;+ try {+ claim = await claimMatchingPattern({ prefix, suffix, ignoreCase, format, maxPriceUsd, paymentId, purchaser });+ } catch (err) {+ if (!isDbUnavailableError(err)) {+ console.error('[vanity] inventory claim lookup failed; falling back to grind', err?.message || err);+ }+ return null;+ }+ if (!claim.ok) return null;++ const item = claim.item;+ const startedAt = Date.now();+ let bundle;+ try {+ const peek = await peekReservedSecret(item.address, { paymentId });+ if (!peek.ok) throw new Error(peek.reason);+ bundle = JSON.parse(await openSecret(peek.ciphertext, peek.scheme));+ } catch (err) {+ console.error('[vanity] inventory decrypt failed; releasing + falling back to grind', err?.message || err);+ await releaseReservation(item.address, { paymentId }).catch(() => {});+ return null;+ }++ const shaped = {+ address: item.address,+ prefix: prefix || null,+ suffix: suffix || null,+ ignoreCase,+ format: bundle.format || item.format || FORMAT_KEYPAIR,+ secretKeyBase58: bundle.secretKeyBase58,+ secretKey: bundle.secretKey,+ mnemonic: bundle.mnemonic || null,+ wordCount: bundle.wordCount || null,+ derivationPath: bundle.derivationPath || null,+ attempts: item.difficultyAttempts,+ durationMs: Date.now() - startedAt,+ expectedAttempts: item.difficultyAttempts,+ network: 'solana',+ explorerUrl: `https://solscan.io/account/${item.address}`,+ source: 'inventory',+ };++ const delivered = sealTo ? await sealSecret(shaped, sealTo) : shaped;+ const withCert = await attachCertificate(delivered, { prefix, suffix, ignoreCase });+ return { result: withCert, item };+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (req.method !== 'GET') {@@ -544,6 +668,35 @@ export default wrap(async (req, res) => {return error(res, err.status || 400, err.code || 'validation_error', err.message);}+ // Premium 4–5 char band: only ever fulfilled from inventory, so check stock+ // BEFORE quoting a price — a buyer must never be asked to pay for a pattern+ // that isn't sitting in the warehouse. A DB outage here degrades to "not in+ // stock" (honest, refundable-nothing failure) rather than a false quote.+ if (pattern.premiumOnly) {+ let inStock = false;+ try {+ inStock = await hasAvailableMatch({+ prefix: pattern.prefix,+ suffix: pattern.suffix,+ ignoreCase: pattern.ignoreCase,+ format: pattern.format,+ });+ } catch (err) {+ if (!isDbUnavailableError(err)) console.error('[vanity] premium stock check failed', err?.message || err);+ }+ if (!inStock) {+ return error(+ res,+ 404,+ 'not_in_stock',+ `pattern not in stock — the live grinder's grindable range is 1–${MAX_SERVER_PATTERN_LENGTH} ` ++ `Base58 chars; ${pattern.combinedLength}-char patterns are served only from the premium ` ++ `inventory when a match exists. Browse current stock at GET /api/x402/vanity-premium` ++ `?prefix=${encodeURIComponent(pattern.prefix || '')}.`,+ );+ }+ }+const resourceUrl = resolveResourceUrl(req, ROUTE);const priceAtomics = priceAtomicsFor(pattern.format, pattern.combinedLength);const requirements = buildRequirements(resourceUrl, priceAtomics);@@ -628,13 +781,38 @@ export default wrap(async (req, res) => {return error(res, err.status || 502, err.code || 'verify_failed', err.message);}- // Grind AFTER verify but BEFORE settle: an invalid pattern or exhausted- // budget throws here, and settlement never runs, so the buyer isn't charged.- // grindAndShape is async (it may seal the secret to the buyer's key), so it- // must be awaited — otherwise the body serializes an unresolved Promise.+ // Instant path FIRST: a matching pre-ground address in inventory is+ // claimed and decrypted here (still before settle, so a claim/decrypt+ // failure costs the buyer nothing — see tryInstantFromInventory). No+ // match (or any failure) returns null and falls straight through to the+ // live grind, unchanged from before this endpoint knew inventory existed.+ const purchaser = verified?.payer || verified?.from || clientPaymentId || 'x402';let result;+ let inventoryClaim = null;try {- result = await grindAndShape(pattern);+ const instant = paymentId ? await tryInstantFromInventory(pattern, { paymentId, purchaser }) : null;+ if (instant) {+ result = instant.result;+ inventoryClaim = instant.item;+ } else if (pattern.premiumOnly) {+ // The pre-payment hasAvailableMatch check above found stock, but+ // between the 402 quote and this settle another buyer won the race for+ // the (possibly only) matching item. This band is NEVER ground live+ // (58^4-58^5 attempts is hours, far past the 45s budget) — fail clean+ // instead of falling through to an infeasible grind. Settlement has not+ // run, so the buyer is charged nothing and can retry.+ throw Object.assign(+ new Error('the matching inventory item was claimed by another buyer between quote and payment — retry'),+ { status: 409, code: 'sold_out' },+ );+ } else {+ // Grind AFTER verify but BEFORE settle: an invalid pattern or exhausted+ // budget throws here, and settlement never runs, so the buyer isn't+ // charged. grindAndShape is async (it may seal the secret to the+ // buyer's key), so it must be awaited — otherwise the body serializes+ // an unresolved Promise.+ result = await grindAndShape(pattern);+ }} catch (err) {return error(res, err.status || 500, err.code || 'grind_failed', err.message);}@@ -643,9 +821,27 @@ export default wrap(async (req, res) => {try {settled = await settlePayment({ verified });} catch (err) {+ if (inventoryClaim) {+ // Settlement failed after we reserved (but did not yet reveal/destroy)+ // the inventory item — release it back to available so a transient+ // payment failure never strands sellable stock.+ await releaseReservation(inventoryClaim.address, { paymentId }).catch(() => {});+ }return error(res, err.status || 502, err.code || 'settle_failed', err.message);}+ if (inventoryClaim) {+ // One-shot reveal AFTER settle: flips reserved→destroyed and nulls the+ // stored ciphertext atomically, so this address can never be served+ // again. We already hold the plaintext (delivered above), so a hiccup+ // here is logged, not fatal to delivery.+ try {+ await reserveAndReveal(inventoryClaim.address, { paymentId });+ } catch (err) {+ console.error('[vanity] inventory reveal/destroy after settle failed', err?.message || err);+ }+ }+const paymentResponseHeader = encodePaymentResponseHeader(settled);const contentType = 'application/json; charset=utf-8';const body = JSON.stringify(result);diff --git a/avatar-sdk/README.md b/avatar-sdk/README.mdindex 619a34839..7c0cf04b0 100644--- a/avatar-sdk/README.md+++ b/avatar-sdk/README.md@@ -76,6 +76,7 @@ Need only a 3D preview — no chat, no voice, no 3 MB runtime? Use the light viesrc="https://example.com/my-avatar.glb"alt="My avatar"background="transparent"+ ar></three-ws-viewer>```@@ -95,16 +96,31 @@ The package exposes focused subpath exports so you only ship what you use.### `<three-ws-viewer>`A minimal viewer element: loads a GLB at `src`, frames it, and renders with-`OrbitControls` and a `RoomEnvironment` image-based light.+`OrbitControls` and a `RoomEnvironment` image-based light. Supports+`EXT_meshopt_compression` and `KHR_draco_mesh_compression` GLBs transparently+(both decoders are lazy-loaded on first use).| Attribute | Description ||---|---|| `src` | GLB URL to load. |-| `alt` | Accessibility label; also rendered as an on-canvas caption. |+| `alt` | Accessibility label; also rendered as an on-canvas caption. Defaults to `"3D model viewer"` when unset. || `background` | CSS color, or `transparent` (default) for an alpha canvas. |--It dispatches a `load` event (`detail: { url }`) on success and an `error` event-(`detail: { url, error }`) on failure.+| `ar` | Opt-in boolean. Adds a "View in AR" button that opens `three.ws/api/ar` in a new tab — device-aware AR (Android Scene Viewer / iOS Quick Look / desktop viewer fallback). Absent by default. |++It dispatches a `load` event (`detail: { url }`) on success, an `error` event+(`detail: { url, error }`) on failure, and an `ar-launch` event+(`detail: { src, launchUrl }`) when the AR button is activated.++**Accessibility.** The canvas is keyboard-focusable (`role="img"`, matching+`<model-viewer>`'s own convention) — Arrow keys orbit, `+`/`-`/PageUp/PageDown+zoom, and a visible focus ring appears on `:focus-visible`. Orbit damping is+disabled under `prefers-reduced-motion: reduce`.++**Performance.** On a detected low-power device (coarse pointer + ≤4 CPU cores+or ≤4GB `deviceMemory`) the viewer starts at pixel ratio 1 and skips MSAA and+the PMREM environment prefilter. Independently, if live frame time shows+sustained <~24fps for about 1.5s, pixel ratio is stepped down once at runtime.+Both are transparent — no attribute needed, and desktop behavior is unchanged.### `<agent-3d>`diff --git a/avatar-sdk/src/viewer.js b/avatar-sdk/src/viewer.jsindex 6fb0636ac..fea8343df 100644--- a/avatar-sdk/src/viewer.js+++ b/avatar-sdk/src/viewer.js@@ -18,6 +18,7 @@ import {Box3,Vector3,Color,+ Spherical,PMREMGenerator,ACESFilmicToneMapping,SRGBColorSpace,@@ -28,6 +29,13 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';const TAG = 'three-ws-viewer';+// The platform's device-aware "View in AR" launcher (Android → Scene Viewer,+// iOS → Quick Look via model-viewer's on-the-fly USDZ conversion, desktop →+// the interactive viewer fallback). Already live at three.ws — reused as-is+// instead of duplicating USD export logic inside a peer-dependency-only SDK+// package. See api/ar.js + api/_lib/ar-launch.js in the three.ws monorepo.+const AR_LAUNCH_ORIGIN = 'https://three.ws';+// three.ws-served GLBs (and any gltf-transform-optimized asset) may carry// EXT_meshopt_compression; without a decoder GLTFLoader throws before parsing.// Lazy + memoized so uncompressed-only consumers never pay for the wasm init.@@ -39,9 +47,41 @@ function getMeshoptDecoder() {return _meshoptPromise;}+// KHR_draco_mesh_compression decoder — lazy + memoized alongside meshopt so a+// consumer that only ever loads meshopt (or uncompressed) assets never pays+// for the wasm init. Draco-compressed GLBs (max-compression tier, per+// prompts/roadmap/REUSE-MAP.md §1) throw without this wired.+let _dracoPromise = null;+function getDracoLoader() {+ if (!_dracoPromise) {+ _dracoPromise = import('three/addons/loaders/DRACOLoader.js').then((m) => {+ const loader = new m.DRACOLoader();+ loader.setDecoderPath('https://www.gstatic.com/draco/versioned/decoders/1.5.7/');+ return loader;+ });+ }+ return _dracoPromise;+}++// Low-power heuristic: coarse pointer (touch) + few cores/little memory almost+// always means an entry-level phone. `deviceMemory` is Chromium-only and+// absent on iOS/Firefox, so it only ever *adds* signal, never gates alone.+function looksLowPower() {+ if (typeof navigator === 'undefined' || typeof matchMedia === 'undefined') return false;+ const touch = matchMedia('(pointer: coarse)').matches;+ if (!touch) return false;+ const fewCores = typeof navigator.hardwareConcurrency === 'number' && navigator.hardwareConcurrency <= 4;+ const lowMem = typeof navigator.deviceMemory === 'number' && navigator.deviceMemory <= 4;+ return fewCores || lowMem;+}++function prefersReducedMotion() {+ return typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;+}+class ThreeWsViewerElement extends HTMLElement {static get observedAttributes() {- return ['src', 'alt', 'background', 'wallet', 'agent-id', 'api-base'];+ return ['src', 'alt', 'background', 'wallet', 'agent-id', 'api-base', 'ar'];}constructor() {@@ -49,12 +89,28 @@ class ThreeWsViewerElement extends HTMLElement {this._shadow = this.attachShadow({ mode: 'open' });this._shadow.innerHTML = `<style>:host { display: block; position: relative; width: 100%; height: 100%; min-height: 320px; }- canvas { display: block; width: 100%; height: 100%; outline: none; }+ canvas { display: block; width: 100%; height: 100%; outline: none; touch-action: none; }+ canvas:focus-visible { outline: 2px solid #6ee7b7; outline-offset: -2px; }.label { position: absolute; inset: auto 0 8px 0; text-align: center; font: 12px system-ui, sans-serif; color: rgba(255,255,255,0.65); pointer-events: none; text-shadow: 0 1px 2px rgba(0,0,0,0.6); }+ .ar-btn {+ position: absolute; right: 10px; bottom: 10px; z-index: 1;+ display: inline-flex; align-items: center; gap: 6px;+ appearance: none; cursor: pointer; border: 1px solid rgba(255,255,255,0.22);+ border-radius: 999px; padding: 8px 14px; background: rgba(10,11,14,0.72);+ color: #fff; font: 600 12.5px/1 system-ui, sans-serif; backdrop-filter: blur(6px);+ transition: background 0.15s, border-color 0.15s, transform 0.08s;+ }+ .ar-btn:hover { background: rgba(20,22,28,0.85); border-color: rgba(255,255,255,0.4); }+ .ar-btn:active { transform: translateY(1px); }+ .ar-btn:focus-visible { outline: 2px solid #6ee7b7; outline-offset: 2px; }+ @media (prefers-reduced-motion: reduce) { .ar-btn { transition: none; } }</style>`;this._canvas = document.createElement('canvas');+ this._canvas.tabIndex = 0;+ this._canvas.setAttribute('role', 'img');this._shadow.appendChild(this._canvas);this._label = null;+ this._arBtn = null;this._scene = null;this._camera = null;@@ -65,6 +121,14 @@ class ThreeWsViewerElement extends HTMLElement {this._resizeObs = null;this._loadToken = 0;this._wallet = null; // mounted wallet affordance, when opted in++ this._reducedMotion = prefersReducedMotion();+ this._lowPower = looksLowPower();+ this._basePixelRatio = this._lowPower ? 1 : Math.min(window.devicePixelRatio || 1, 2);+ this._fpsWindow = [];+ this._degraded = false;++ this._onKeydown = this._onKeydown.bind(this);}connectedCallback() {@@ -75,11 +139,14 @@ class ThreeWsViewerElement extends HTMLElement {if (src) this._loadModel(src);this._applyAlt(this.getAttribute('alt'));this._applyWallet();+ this._applyAr();+ this._canvas.addEventListener('keydown', this._onKeydown);}disconnectedCallback() {cancelAnimationFrame(this._raf);this._raf = 0;+ this._canvas.removeEventListener('keydown', this._onKeydown);if (this._resizeObs) {this._resizeObs.disconnect();this._resizeObs = null;@@ -107,6 +174,7 @@ class ThreeWsViewerElement extends HTMLElement {else if (name === 'alt') this._applyAlt(value);else if (name === 'background') this._applyBackground(value);else if (name === 'wallet' || name === 'agent-id' || name === 'api-base') this._applyWallet();+ else if (name === 'ar') this._applyAr();}_init() {@@ -121,28 +189,35 @@ class ThreeWsViewerElement extends HTMLElement {this._renderer = new WebGLRenderer({canvas: this._canvas,- antialias: true,+ // Low-power devices skip MSAA — the biggest single GPU cost on+ // entry-level mobile GPUs — in exchange for a stable frame rate.+ antialias: !this._lowPower,alpha: true,powerPreference: 'high-performance',});- this._renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ this._renderer.setPixelRatio(this._basePixelRatio);this._renderer.setSize(width, height, false);this._renderer.outputColorSpace = SRGBColorSpace;this._renderer.toneMapping = ACESFilmicToneMapping;this._renderer.toneMappingExposure = 1.0;- const pmrem = new PMREMGenerator(this._renderer);- this._envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;- this._scene.environment = this._envTex;- pmrem.dispose();+ // Low-power devices skip the PMREM environment prefilter (a real-time+ // render-to-cubemap pass) and get a slightly brighter ambient term+ // instead — visually close, meaningfully cheaper on first paint.+ if (!this._lowPower) {+ const pmrem = new PMREMGenerator(this._renderer);+ this._envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ this._scene.environment = this._envTex;+ pmrem.dispose();+ }- this._scene.add(new AmbientLight(0xffffff, 0.55));+ this._scene.add(new AmbientLight(0xffffff, this._lowPower ? 0.75 : 0.55));const key = new DirectionalLight(0xffffff, 1.1);key.position.set(2, 4, 3);this._scene.add(key);this._controls = new OrbitControls(this._camera, this._canvas);- this._controls.enableDamping = true;+ this._controls.enableDamping = !this._reducedMotion;this._controls.dampingFactor = 0.08;this._controls.target.set(0, 1.0, 0);this._controls.update();@@ -151,6 +226,37 @@ class ThreeWsViewerElement extends HTMLElement {this._resizeObs.observe(this);}+ // Keyboard-only orbit + zoom for users who can't drag a pointer. Arrow keys+ // rotate azimuth/polar around the current target; +/- and PageUp/PageDown+ // dolly. Mirrors OrbitControls' own step sizes so keyboard and pointer+ // interaction feel consistent.+ _onKeydown(event) {+ if (!this._controls || !this._camera) return;+ const rotateStep = 0.05; // radians+ const zoomStep = 1.08;+ const offset = new Vector3().subVectors(this._camera.position, this._controls.target);+ const spherical = new Spherical().setFromVector3(offset);+ let handled = true;+ switch (event.key) {+ case 'ArrowLeft': spherical.theta -= rotateStep; break;+ case 'ArrowRight': spherical.theta += rotateStep; break;+ case 'ArrowUp': spherical.phi = Math.max(0.05, spherical.phi - rotateStep); break;+ case 'ArrowDown': spherical.phi = Math.min(Math.PI - 0.05, spherical.phi + rotateStep); break;+ case '+':+ case '=':+ case 'PageUp': spherical.radius /= zoomStep; break;+ case '-':+ case '_':+ case 'PageDown': spherical.radius *= zoomStep; break;+ default: handled = false;+ }+ if (!handled) return;+ event.preventDefault();+ offset.setFromSpherical(spherical);+ this._camera.position.copy(this._controls.target).add(offset);+ this._controls.update();+ }+_handleResize() {if (!this._renderer || !this._camera) return;const w = this.clientWidth || 1;@@ -162,10 +268,13 @@ class ThreeWsViewerElement extends HTMLElement {async _loadModel(url) {if (!url) return;+ this._currentSrc = url;const token = ++this._loadToken;const loader = new GLTFLoader();try {- loader.setMeshoptDecoder(await getMeshoptDecoder());+ const [meshoptDecoder, dracoLoader] = await Promise.all([getMeshoptDecoder(), getDracoLoader()]);+ loader.setMeshoptDecoder(meshoptDecoder);+ loader.setDRACOLoader(dracoLoader);const gltf = await loader.loadAsync(url);if (token !== this._loadToken || !this._scene) return;if (this._model) { this._scene.remove(this._model); this._disposeModel(this._model); }@@ -212,16 +321,16 @@ class ThreeWsViewerElement extends HTMLElement {}_applyAlt(value) {- const text = (value || '').trim();- if (!text) {+ const text = (value || '').trim() || '3D model viewer';+ this.setAttribute('aria-label', text);+ this._canvas.setAttribute('aria-label', text);+ if (!(value || '').trim()) {if (this._label) {this._label.remove();this._label = null;}- this.removeAttribute('aria-label');return;}- this.setAttribute('aria-label', text);if (!this._label) {this._label = document.createElement('div');this._label.className = 'label';@@ -230,6 +339,51 @@ class ThreeWsViewerElement extends HTMLElement {this._label.textContent = text;}+ // Opt-in "View in AR" affordance (`ar` boolean attribute). Absent by+ // default — existing embeds are unaffected. Delegates to the platform's+ // already-live device-aware AR launcher (three.ws/api/ar): Android opens+ // Google Scene Viewer, iOS opens Apple Quick Look (model-viewer converts+ // the GLB to USDZ on the fly there — no client-side USD export needed in+ // this lightweight, peer-dependency-only SDK component), desktop falls+ // back to the interactive viewer. New tab, so the host page never+ // navigates away under the embed.+ _applyAr() {+ const wants = this.hasAttribute('ar');+ if (!wants) {+ if (this._arBtn) { this._arBtn.remove(); this._arBtn = null; }+ return;+ }+ if (this._arBtn) return; // already mounted+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'ar-btn';+ btn.setAttribute('aria-label', 'View this model in augmented reality');+ btn.innerHTML =+ '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' ++ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z"/>' ++ '<path d="m3 7 9 5 9-5"/><path d="M12 12v10"/></svg><span>View in AR</span>';+ btn.addEventListener('click', () => this._launchAr());+ this._shadow.appendChild(btn);+ this._arBtn = btn;+ }++ _launchAr() {+ const src = this._currentSrc || this.getAttribute('src');+ if (!src) return;+ let absoluteSrc;+ try {+ absoluteSrc = new URL(src, window.location.href).href;+ } catch {+ return;+ }+ const params = new URLSearchParams({ src: absoluteSrc });+ const title = (this.getAttribute('alt') || '').trim();+ if (title) params.set('title', title.slice(0, 120));+ const launchUrl = `${AR_LAUNCH_ORIGIN}/api/ar?${params.toString()}`;+ window.open(launchUrl, '_blank', 'noopener');+ this.dispatchEvent(new CustomEvent('ar-launch', { detail: { src: absoluteSrc, launchUrl } }));+ }+// Opt-in wallet identity: with `wallet agent-id="<uuid>"` the viewer shows the// agent's public wallet (address, value, tips, one-tap tip) without pulling the// heavy <agent-3d> runtime or any dependency. Lazy-loaded so a wallet-less embed@@ -263,11 +417,35 @@ class ThreeWsViewerElement extends HTMLElement {});}- _render() {+ _render(now) {if (!this._renderer) return;this._raf = requestAnimationFrame(this._render);this._controls?.update();this._renderer.render(this._scene, this._camera);+ this._sampleFps(now || performance.now());+ }++ // Runtime quality auto-degrade: a device that *reports* as capable but+ // actually renders below ~24fps (thermal throttling, an old iGPU, a+ // background-tab wake-up) gets its pixel ratio dropped once, live — no+ // reload, no flicker, just a resolution step-down. Only ever tightens;+ // never re-escalates mid-session (avoids oscillating).+ _sampleFps(now) {+ if (this._degraded || !this._lastFrameTime) {+ this._lastFrameTime = now;+ return;+ }+ const delta = now - this._lastFrameTime;+ this._lastFrameTime = now;+ this._fpsWindow.push(delta);+ if (this._fpsWindow.length < 90) return; // ~1.5s at 60fps before judging+ const avg = this._fpsWindow.reduce((a, b) => a + b, 0) / this._fpsWindow.length;+ this._fpsWindow.length = 0;+ if (avg > 41.6) { // sustained < ~24fps+ this._degraded = true;+ const next = Math.max(1, this._basePixelRatio * 0.75);+ this._renderer.setPixelRatio(next);+ }}}diff --git a/avatar-sdk/types/viewer.d.ts b/avatar-sdk/types/viewer.d.tsindex cc43cb940..0916b18ae 100644--- a/avatar-sdk/types/viewer.d.ts+++ b/avatar-sdk/types/viewer.d.ts@@ -13,21 +13,41 @@ declare global {}/**- * `<three-ws-viewer src="..." alt="..." background="...">`+ * `<three-ws-viewer src="..." alt="..." background="..." ar>`** Attributes:- * - `src` — GLB URL (required to render anything).- * - `alt` — accessibility label and caption text.+ * - `src` — GLB URL (required to render anything). Supports+ * `EXT_meshopt_compression` and `KHR_draco_mesh_compression` transparently.+ * - `alt` — accessibility label and caption text. Defaults to+ * `"3D model viewer"` when unset so the canvas is never unlabeled.* - `background` — CSS color string, or `'transparent'`. Default transparent.+ * - `ar` — opt-in boolean. Renders a "View in AR" button that opens the+ * platform's device-aware AR launcher (`three.ws/api/ar`) in a new tab:+ * Android → Google Scene Viewer, iOS → Apple Quick Look, desktop → the+ * interactive viewer. Absent by default; existing embeds are unaffected.+ *+ * Accessibility: the canvas is keyboard-focusable (`role="img"`, matching+ * `<model-viewer>`'s own pattern) and orbits/zooms via Arrow keys and+ * `+`/`-`/PageUp/PageDown. `prefers-reduced-motion: reduce` disables orbit+ * damping (no lingering inertia after a drag or key press).+ *+ * Performance: on a detected low-power device (coarse pointer + ≤4 cores or+ * ≤4GB `deviceMemory`) the viewer starts at a lower pixel ratio, skips MSAA+ * and the PMREM environment prefilter. Independently, if live frame time+ * shows sustained <~24fps for ~1.5s, pixel ratio is stepped down once at+ * runtime (never re-escalated mid-session).** Events:- * - `load` — `CustomEvent<{ url: string }>` once the GLB is parsed and added.- * - `error` — `CustomEvent<{ url: string, error: Error }>` on load failure.+ * - `load` — `CustomEvent<{ url: string }>` once the GLB is parsed and added.+ * - `error` — `CustomEvent<{ url: string, error: Error }>` on load failure.+ * - `ar-launch` — `CustomEvent<{ src: string, launchUrl: string }>` when the+ * AR button is activated.*/export class ThreeWsViewerElement extends HTMLElement {src?: string;alt?: string;background?: string;+ ar?: boolean;}export default ThreeWsViewerElement;diff --git a/contracts/.env.example b/contracts/.env.exampleindex 4709d3f89..2ebd7d3be 100644--- a/contracts/.env.example+++ b/contracts/.env.example@@ -22,3 +22,9 @@ ARB_RPC_URL=https://arb1.arbitrum.io/rpcPOLYGON_RPC_URL=https://polygon-rpc.comBSC_RPC_URL=https://bsc-dataseed.binance.orgAVAX_RPC_URL=https://api.avax.network/ext/bc/C/rpc++# ── BNB Chain testnet deploys (WorldMoves, GreenfieldVault) ─────────────────+# BSC testnet RPC — all bnb-chain campaign deploys default here (chain id 97).+BSC_TESTNET_RPC_URL=https://data-seed-prebsc-1-s1.bnbchain.org:8545+# BscScan API key (for --verify on BSC/BSC testnet).+BSCSCAN_API_KEY=diff --git a/contracts/DEPLOYMENTS.md b/contracts/DEPLOYMENTS.mdindex ca2db5be9..90f941ae6 100644--- a/contracts/DEPLOYMENTS.md+++ b/contracts/DEPLOYMENTS.md@@ -229,6 +229,63 @@ hash, and a BscScan link, and paste ~10 real `move()` tx block numbers/timestamps here as live proof of sub-second block spacing (per`prompts/bnb-chain/14-world-moves-contract.md`'s definition of done).+## GreenfieldVault (pay → PermissionHub grant, on-chain-gated 3D asset vault)++BNB Chain campaign, Track B: a BSC marketplace contract that, on payment,+calls the REAL Greenfield `PermissionHub.createPolicy` cross-chain, granting+the buyer read permission on an encrypted object. Source:+[`src/GreenfieldVault.sol`](src/GreenfieldVault.sol); real interface stubs+(sourced from `bnb-chain/greenfield-contracts`, verified against `master` on+2026-07-08 — no invented ABI) in [`src/greenfield/`](src/greenfield). Uses the+real, already-deployed `PermissionHub`/`CrossChain`/`ObjectHub` hubs — no+Greenfield contract of our own to deploy.++Constructor-supplied hub addresses (deploy script+[`script/DeployGreenfieldVault.s.sol`](script/DeployGreenfieldVault.s.sol)+defaults per `block.chainid`, env-overridable):++| Network | PermissionHub | CrossChain | ObjectHub (IGnfdAccessControl) |+| --- | --- | --- | --- |+| BSC mainnet (56) | `0xe1776006dBE9B60d9eA38C0dDb80b41f2657acE8` | `0x77e719b714be09F70D484AB81F70D02B0E182f7d` | `0x634eB9c438b8378bbdd8D0e10970Ec88db0b4d0f` |+| BSC testnet (97) | `0x25E1eeDb5CaBf288210B132321FBB2d90b4174ad` | `0xa5B2c9194131A4E0BFaCbF9E5D6722c873159cb7` | `0x1b059D8481dEe299713F18601fB539D066553e39` |++(Mainnet CrossChain/ObjectHub bytecode-verified 2026-07-07 per+`prompts/bnb-chain/00-CONTEXT.md`; PermissionHub mainnet + all testnet+addresses read live from `bnb-chain/greenfield-contracts`'s README "Contract+Entrypoint" tables on 2026-07-08 — never invented.)++**Status: built, compiled, and fully unit-tested locally (34/34 `forge test`+passing, including two dedicated re-entrancy proofs against a mocked+PermissionHub/CrossChain/IGnfdAccessControl). NOT deployed to BSC testnet.** A+`forge script ... -vvvv` dry-run against the live BSC testnet RPC+(`https://data-seed-prebsc-1-s1.bnbchain.org:8545`, also reachable via the new+`bsc_testnet` `foundry.toml` alias) simulated successfully end-to-end+(constructor executes against the real testnet PermissionHub/CrossChain/+ObjectHub addresses above, ~1.16M gas estimated for the deploy tx at 0.1 gwei+≈ 0.000170 BNB) — the RPC, script, and bytecode are all deploy-ready. The only+missing piece is a funded deployer key: neither `DEPLOYER_PK` nor+`BNB_TESTNET_DEPLOYER_KEY` is present in this environment (checked `.env`,+`contracts/.env`, `cast wallet list`, and shell env; no secret values were+read, only key presence). Same funding blocker as campaign items 13 and 18 —+owner-only to unblock (fund a deployer EOA via the tBNB faucet, then run the+broadcast command below).++Deploy (once funded):+```+forge script script/DeployGreenfieldVault.s.sol:DeployGreenfieldVault \+ --rpc-url https://data-seed-prebsc-1-s1.bnbchain.org:8545 \+ --private-key $DEPLOYER_PK \+ --broadcast+```++After a real deploy: replace this status block with the address, deploy tx+hash, and a BscScan link; have a seller `grantRole(ROLE_CREATE, vault, expiry)`+on the real testnet ObjectHub for a real uploaded object (prompt 09); execute+one real `buy()`; and paste the BSC tx hash plus the resulting+`PermissionHub.settleCreatePolicy`/`PolicyGranted` proof (BscScan ++GreenfieldScan once the cross-chain ack settles) per+`prompts/bnb-chain/10-vault-contract.md`'s definition of done.+## Notes- Addresses are authoritative in [`src/erc8004/abi.js`](../src/erc8004/abi.js) (`REGISTRY_DEPLOYMENTS`).diff --git a/contracts/foundry.toml b/contracts/foundry.tomlindex dc761d533..52f44e6bf 100644--- a/contracts/foundry.toml+++ b/contracts/foundry.toml@@ -14,7 +14,11 @@ remappings = [[rpc_endpoints]base_sepolia = "${BASE_SEPOLIA_RPC_URL}"base = "${BASE_RPC_URL}"+bsc_testnet = "${BSC_TESTNET_RPC_URL}"+bsc = "${BSC_RPC_URL}"[etherscan]base_sepolia = { key = "${BASESCAN_API_KEY}", url = "https://api-sepolia.basescan.org/api" }base = { key = "${BASESCAN_API_KEY}", url = "https://api.basescan.org/api" }+bsc_testnet = { key = "${BSCSCAN_API_KEY}", url = "https://api-testnet.bscscan.com/api" }+bsc = { key = "${BSCSCAN_API_KEY}", url = "https://api.bscscan.com/api" }diff --git a/contracts/script/DeployGreenfieldVault.s.sol b/contracts/script/DeployGreenfieldVault.s.solnew file mode 100644index 000000000..e883f070b--- /dev/null+++ b/contracts/script/DeployGreenfieldVault.s.sol@@ -0,0 +1,70 @@+// SPDX-License-Identifier: MIT+pragma solidity ^0.8.24;++import {Script, console} from "forge-std/Script.sol";+import {GreenfieldVault} from "../src/GreenfieldVault.sol";++/// @notice Deploys GreenfieldVault against the REAL, already-deployed Greenfield+/// cross-chain hubs for the target network — never a fresh mock/hub+/// deployment. Addresses default from `bnb-chain/greenfield-contracts`+/// (verified against `master` on 2026-07-08; mainnet cross-checked+/// against `prompts/bnb-chain/00-CONTEXT.md`'s bytecode-verified list)+/// and can be overridden via env for a future hub migration:+///+/// GREENFIELD_PERMISSION_HUB, GREENFIELD_CROSS_CHAIN, GREENFIELD_OBJECT_HUB+///+/// Run (BSC testnet, dry-run simulation — no --broadcast):+/// forge script script/DeployGreenfieldVault.s.sol:DeployGreenfieldVault \+/// --rpc-url $BSC_TESTNET_RPC_URL -vvvv+///+/// Run (BSC testnet, real deploy):+/// forge script script/DeployGreenfieldVault.s.sol:DeployGreenfieldVault \+/// --rpc-url $BSC_TESTNET_RPC_URL \+/// --private-key $DEPLOYER_PK \+/// --broadcast+contract DeployGreenfieldVault is Script {+ // Mainnet (56) — bytecode-verified 2026-07-07, prompts/bnb-chain/00-CONTEXT.md.+ address internal constant PERMISSION_HUB_MAINNET = 0xe1776006dBE9B60d9eA38C0dDb80b41f2657acE8;+ address internal constant CROSS_CHAIN_MAINNET = 0x77e719b714be09F70D484AB81F70D02B0E182f7d;+ address internal constant OBJECT_HUB_MAINNET = 0x634eB9c438b8378bbdd8D0e10970Ec88db0b4d0f;++ // Testnet (97) — bnb-chain/greenfield-contracts README "Contract Entrypoint".+ address internal constant PERMISSION_HUB_TESTNET = 0x25E1eeDb5CaBf288210B132321FBB2d90b4174ad;+ address internal constant CROSS_CHAIN_TESTNET = 0xa5B2c9194131A4E0BFaCbF9E5D6722c873159cb7;+ address internal constant OBJECT_HUB_TESTNET = 0x1b059D8481dEe299713F18601fB539D066553e39;++ function run() external returns (GreenfieldVault vault) {+ (address permissionHub, address crossChain, address objectHub) = _hubsForChain(block.chainid);++ permissionHub = vm.envOr("GREENFIELD_PERMISSION_HUB", permissionHub);+ crossChain = vm.envOr("GREENFIELD_CROSS_CHAIN", crossChain);+ objectHub = vm.envOr("GREENFIELD_OBJECT_HUB", objectHub);++ vm.startBroadcast();+ vault = new GreenfieldVault(permissionHub, crossChain, objectHub);+ vm.stopBroadcast();++ console.log("GreenfieldVault: ", address(vault));+ console.log("PermissionHub: ", permissionHub);+ console.log("CrossChain: ", crossChain);+ console.log("ObjectHub (ACL): ", objectHub);+ console.log("Chain id: ", block.chainid);+ console.log("");+ console.log("Next: sellers must grantRole(ROLE_CREATE, vaultAddress, expiry) on");+ console.log("ObjectHub for their mirrored object before list() will accept it.");+ }++ function _hubsForChain(uint256 chainId)+ internal+ pure+ returns (address permissionHub, address crossChain, address objectHub)+ {+ if (chainId == 56) {+ return (PERMISSION_HUB_MAINNET, CROSS_CHAIN_MAINNET, OBJECT_HUB_MAINNET);+ }+ if (chainId == 97) {+ return (PERMISSION_HUB_TESTNET, CROSS_CHAIN_TESTNET, OBJECT_HUB_TESTNET);+ }+ revert("GreenfieldVault: no known Greenfield hub addresses for this chain id");+ }+}diff --git a/contracts/src/GreenfieldVault.sol b/contracts/src/GreenfieldVault.solnew file mode 100644index 000000000..640e17942--- /dev/null+++ b/contracts/src/GreenfieldVault.sol@@ -0,0 +1,331 @@+// SPDX-License-Identifier: MIT+pragma solidity ^0.8.24;++import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";+import {IPermissionHub} from "./greenfield/IPermissionHub.sol";+import {ICrossChain} from "./greenfield/ICrossChain.sol";+import {IGnfdAccessControl} from "./greenfield/IGnfdAccessControl.sol";+import {IApplication} from "./greenfield/IApplication.sol";++/**+ * @title GreenfieldVault+ * @notice On-chain-gated marketplace for encrypted 3D assets stored on BNB+ * Greenfield. A seller lists an encrypted object (uploaded per+ * `specs/vault-manifest.md`); on payment, the vault calls the real+ * Greenfield `PermissionHub.createPolicy` cross-chain, granting the+ * buyer's address read permission on that object. Off-chain (the+ * unlock API, prompt 11) watches for the resulting policy grant and+ * wraps the object's content-encryption key to the buyer once it+ * settles — this contract only proves and gates the payment↔permission+ * link on-chain.+ *+ * Every cross-chain primitive here is the REAL BSC↔Greenfield bridge+ * (`src/greenfield/*.sol`, addresses verified against+ * `bnb-chain/greenfield-contracts`) — no invented interface, no mock+ * in production code. `createPolicy` is genuinely asynchronous: this+ * contract does not (cannot) know the minted policy id at `buy()`+ * time. It implements `IApplication.greenfieldCall` to receive the+ * real id when Greenfield's ack settles and relays it via+ * `PolicyGranted` — the same "surface pending honestly" pattern the+ * rest of this campaign uses for Greenfield's async settlement.+ *+ * Multiple buyers may each hold an independent read grant on the same+ * listed object (this is a content-access marketplace, not an+ * ownership-transfer one) — `list()` never auto-delists after a sale.+ * A given (objectId, buyer) pair may only buy once at a time+ * (`AlreadyPurchased`); a seller-initiated `revoke()` clears that+ * guard so the buyer could be resold access later. Grants are+ * otherwise permanent — there is no expiry.+ *+ * Payment: native BNB. `buy()`/`revoke()` require enough `msg.value`+ * to cover both the listed price (buy only) and Greenfield's real+ * cross-chain relay fee (`ICrossChain.getRelayFees()`, queried live —+ * never hardcoded); any excess is refunded to the caller in the same+ * transaction. Sale proceeds use a pull-payment pattern+ * (`pendingWithdrawals` + `withdraw()`) so a misbehaving seller+ * receive() can never block a buyer's purchase.+ */+contract GreenfieldVault is ReentrancyGuard, IApplication {+ /*----------------- Greenfield wire constants -----------------*/+ // Mirrors bnb-chain/greenfield-contracts Config.sol / CmnStorage.sol+ // (verified against `master` on 2026-07-08).+ uint8 private constant PERMISSION_CHANNEL_ID = 0x07;+ uint32 private constant STATUS_SUCCESS = 0;+ uint8 private constant TYPE_CREATE = 2;++ /// @notice Role a seller must grant this vault on the Greenfield object's+ /// mirrored ERC-721 (via `IGnfdAccessControl.grantRole`) before+ /// `list()` will accept it. Mirrors+ /// `CmnStorage.ROLE_CREATE = keccak256("ROLE_CREATE")`.+ bytes32 public constant ROLE_CREATE = keccak256("ROLE_CREATE");++ /*----------------- immutables -----------------*/+ /// @notice The real, deployed PermissionHub for this network.+ IPermissionHub public immutable permissionHub;+ /// @notice The real, deployed CrossChain relay-fee oracle for this network.+ ICrossChain public immutable crossChain;+ /// @notice The real, deployed ObjectHub (implements IGnfdAccessControl)+ /// whose mirrored ERC-721s represent Greenfield objects on BSC.+ IGnfdAccessControl public immutable objectAccessControl;++ /*----------------- types -----------------*/+ struct Listing {+ address seller;+ uint256 price; // wei, exact amount credited to the seller per sale+ bool active;+ }++ enum SaleStatus {+ Pending, // createPolicy syn-package sent, ack not yet settled+ Granted, // Greenfield confirmed the policy (real policyId recorded)+ Failed, // Greenfield rejected the policy request+ Revoked // seller called revoke() after a Granted sale+ }++ struct Sale {+ bytes32 objectId;+ address buyer;+ address seller;+ uint256 price;+ uint256 policyId; // 0 until Granted+ SaleStatus status;+ }++ /*----------------- storage -----------------*/+ mapping(bytes32 => Listing) public listings;+ mapping(uint256 => Sale) public sales;+ /// @dev objectId => buyer => saleId. 0 means "no open purchase" — cleared+ /// on Failed/Revoked so the pair can transact again.+ mapping(bytes32 => mapping(address => uint256)) public saleIdOf;+ /// @dev Pull-payment balances credited to sellers on each sale.+ mapping(address => uint256) public pendingWithdrawals;+ uint256 public nextSaleId = 1;++ /*----------------- events -----------------*/+ event Listed(bytes32 indexed objectId, address indexed seller, uint256 price);+ event Delisted(bytes32 indexed objectId, address indexed seller);+ event Purchased(bytes32 indexed objectId, address indexed buyer, uint256 indexed saleId, uint256 price);+ event PolicyGranted(bytes32 indexed objectId, address indexed buyer, uint256 indexed saleId, uint256 policyId);+ event PolicyGrantFailed(bytes32 indexed objectId, address indexed buyer, uint256 indexed saleId, uint32 status);+ event RevokeRequested(bytes32 indexed objectId, uint256 indexed saleId, uint256 policyId);+ event Withdrawn(address indexed seller, uint256 amount);++ /*----------------- errors -----------------*/+ error ZeroAddress();+ error BadObjectId();+ error BadPrice();+ error OnlySeller();+ error ListedByAnotherSeller();+ error NotAuthorizedByObjectOwner();+ error NotListed();+ error EmptyPolicyData();+ error AlreadyPurchased();+ error InsufficientPayment();+ error TransferFailed();+ error UnknownSale();+ error NotSaleSeller();+ error SaleNotGranted();+ error InsufficientRelayFee();+ error OnlyPermissionHub();+ error BadChannel();+ error NothingToWithdraw();++ constructor(address _permissionHub, address _crossChain, address _objectAccessControl) {+ if (_permissionHub == address(0) || _crossChain == address(0) || _objectAccessControl == address(0)) {+ revert ZeroAddress();+ }+ permissionHub = IPermissionHub(_permissionHub);+ crossChain = ICrossChain(_crossChain);+ objectAccessControl = IGnfdAccessControl(_objectAccessControl);+ }++ /*----------------- listing -----------------*/++ /**+ * @notice Register (or re-price) a for-sale encrypted object.+ * @dev Requires `seller` to have already run+ * `IGnfdAccessControl(ObjectHub).grantRole(ROLE_CREATE, address(this), expiry)`+ * on the mirrored Greenfield object — the on-chain proof that "the+ * vault controls its permissions" for this object, checked live+ * against the real ObjectHub, not merely asserted by the caller.+ * @param objectId Opaque platform object reference (matches+ * `specs/vault-manifest.md`'s `glbObjectRef`), NOT the Greenfield+ * ERC-721 token id — `policyData` (supplied at `buy()` time) is what+ * actually encodes the Greenfield-side resource/principal/statement.+ */+ function list(bytes32 objectId, uint256 price, address seller) external {+ if (objectId == bytes32(0)) revert BadObjectId();+ if (price == 0) revert BadPrice();+ if (seller == address(0)) revert ZeroAddress();+ if (msg.sender != seller) revert OnlySeller();++ Listing storage existing = listings[objectId];+ if (existing.active && existing.seller != seller) revert ListedByAnotherSeller();++ if (!objectAccessControl.hasRole(ROLE_CREATE, seller, address(this))) {+ revert NotAuthorizedByObjectOwner();+ }++ listings[objectId] = Listing({seller: seller, price: price, active: true});+ emit Listed(objectId, seller, price);+ }++ /// @notice Take a listing off sale. Existing grants are unaffected.+ function delist(bytes32 objectId) external {+ Listing storage listing = listings[objectId];+ if (!listing.active) revert NotListed();+ if (msg.sender != listing.seller) revert OnlySeller();+ listing.active = false;+ emit Delisted(objectId, listing.seller);+ }++ /*----------------- buying -----------------*/++ /**+ * @notice Pay for read access to `objectId` and submit the cross-chain+ * `PermissionHub.createPolicy` request granting `msg.sender`.+ * @dev `policyData` is the pre-built Greenfield permission payload (GNFD+ * protobuf-encoded `principal`/`resource`/`statements`, built+ * off-chain by the unlock API using bnb-chain's greenfield-js-sdk+ * permission codec against this object's real GRN and `msg.sender`+ * as principal) — PermissionHub accepts and forwards this as opaque+ * `bytes` on real mainnet/testnet too; no EVM contract encodes GNFD+ * protobuf on-chain. `msg.value` must cover `price +` the live+ * relay fee quoted by `crossChain.getRelayFees()`; excess is+ * refunded. Reverts atomically (no partial state change) on+ * underpayment, an unlisted object, or an uncovered relay fee.+ */+ function buy(bytes32 objectId, bytes calldata policyData) external payable nonReentrant returns (uint256 saleId) {+ Listing storage listing = listings[objectId];+ if (!listing.active) revert NotListed();+ if (policyData.length == 0) revert EmptyPolicyData();+ if (saleIdOf[objectId][msg.sender] != 0) revert AlreadyPurchased();++ (uint256 relayFee, uint256 minAckRelayFee) = crossChain.getRelayFees();+ uint256 requiredFee = relayFee + minAckRelayFee;+ uint256 totalRequired = listing.price + requiredFee;+ if (msg.value < totalRequired) revert InsufficientPayment();++ saleId = nextSaleId++;+ sales[saleId] = Sale({+ objectId: objectId,+ buyer: msg.sender,+ seller: listing.seller,+ price: listing.price,+ policyId: 0,+ status: SaleStatus.Pending+ });+ saleIdOf[objectId][msg.sender] = saleId;+ pendingWithdrawals[listing.seller] += listing.price;++ IPermissionHub.ExtraData memory extraData = IPermissionHub.ExtraData({+ appAddress: address(this),+ refundAddress: listing.seller,+ failureHandleStrategy: IPermissionHub.FailureHandleStrategy.SkipOnFail,+ callbackData: abi.encode(saleId)+ });++ permissionHub.createPolicy{value: requiredFee}(policyData, extraData);++ emit Purchased(objectId, msg.sender, saleId, listing.price);++ uint256 refund = msg.value - totalRequired;+ if (refund > 0) {+ (bool ok,) = msg.sender.call{value: refund}("");+ if (!ok) revert TransferFailed();+ }+ }++ /*----------------- async settlement callback -----------------*/++ /// @inheritdoc IApplication+ /// @dev Called by the real PermissionHub when the GNFD ack for a+ /// `createPolicy` request settles (success or failure) — this is+ /// the only path that ever learns the real Greenfield policy id.+ function greenfieldCall(+ uint32 status,+ uint8 channelId,+ uint8 operationType,+ uint256 resourceId,+ bytes calldata callbackData+ ) external override {+ if (msg.sender != address(permissionHub)) revert OnlyPermissionHub();+ if (channelId != PERMISSION_CHANNEL_ID) revert BadChannel();+ if (operationType != TYPE_CREATE) return; // this vault only opts into create-callbacks++ uint256 saleId = abi.decode(callbackData, (uint256));+ Sale storage sale = sales[saleId];+ if (sale.buyer == address(0)) revert UnknownSale();++ if (status == STATUS_SUCCESS) {+ sale.policyId = resourceId;+ sale.status = SaleStatus.Granted;+ emit PolicyGranted(sale.objectId, sale.buyer, saleId, resourceId);+ } else {+ sale.status = SaleStatus.Failed;+ saleIdOf[sale.objectId][sale.buyer] = 0; // let the buyer retry+ emit PolicyGrantFailed(sale.objectId, sale.buyer, saleId, status);+ }+ }++ /*----------------- revoke -----------------*/++ /**+ * @notice Seller-initiated revoke of a settled grant, via the real+ * `PermissionHub.deletePolicy`. Design choice (documented per+ * spec): grants are permanent on purchase by default — this is+ * the explicit escape hatch for refunds/disputes, gated to the+ * sale's seller, not automatic expiry. Reverts if the sale never+ * settled (`Pending`/`Failed`) or was already revoked. Clears+ * `saleIdOf` so the object can be resold to the same buyer.+ * Purchase-price refund (if any) is a separate off-chain/business+ * decision — proceeds may already have been withdrawn by the time+ * a revoke happens, so this contract cannot safely auto-refund+ * from its own balance.+ */+ function revoke(uint256 saleId) external payable nonReentrant {+ Sale storage sale = sales[saleId];+ if (sale.buyer == address(0)) revert UnknownSale();+ if (msg.sender != sale.seller) revert NotSaleSeller();+ if (sale.status != SaleStatus.Granted) revert SaleNotGranted();++ uint256 policyId = sale.policyId;+ sale.status = SaleStatus.Revoked;+ saleIdOf[sale.objectId][sale.buyer] = 0;++ (uint256 relayFee, uint256 minAckRelayFee) = crossChain.getRelayFees();+ uint256 requiredFee = relayFee + minAckRelayFee;+ if (msg.value < requiredFee) revert InsufficientRelayFee();++ permissionHub.deletePolicy{value: requiredFee}(policyId);+ emit RevokeRequested(sale.objectId, saleId, policyId);++ uint256 refund = msg.value - requiredFee;+ if (refund > 0) {+ (bool ok,) = msg.sender.call{value: refund}("");+ if (!ok) revert TransferFailed();+ }+ }++ /*----------------- withdrawal -----------------*/++ /// @notice Pull-payment withdrawal of accumulated sale proceeds.+ function withdraw() external nonReentrant returns (uint256 amount) {+ amount = pendingWithdrawals[msg.sender];+ if (amount == 0) revert NothingToWithdraw();+ pendingWithdrawals[msg.sender] = 0;+ (bool ok,) = msg.sender.call{value: amount}("");+ if (!ok) revert TransferFailed();+ emit Withdrawn(msg.sender, amount);+ }++ /*----------------- views -----------------*/++ /// @notice Live quote of the BNB a caller must add to `price` for `buy()`,+ /// or send outright for `revoke()`. Never hardcoded — always the+ /// real, current `CrossChain.getRelayFees()`.+ function quoteRelayFee() external view returns (uint256 relayFee, uint256 minAckRelayFee, uint256 total) {+ (relayFee, minAckRelayFee) = crossChain.getRelayFees();+ total = relayFee + minAckRelayFee;+ }+}diff --git a/contracts/src/greenfield/IApplication.sol b/contracts/src/greenfield/IApplication.solnew file mode 100644index 000000000..96f2152d5--- /dev/null+++ b/contracts/src/greenfield/IApplication.sol@@ -0,0 +1,30 @@+// SPDX-License-Identifier: GPL-3.0-or-later+pragma solidity ^0.8.0;++/// @title IApplication+/// @notice Real ABI of the Greenfield middle-layer async-callback surface.+/// `GreenfieldVault` implements this so `PermissionHub.handleAckPackage`+/// can deliver the real, GNFD-minted policy id once an async+/// `createPolicy` request settles (see `CmnHub._handleCreateAckPackage`+/// in the upstream repo, which calls back into `extraData.appAddress`).+/// Mirrors `bnb-chain/greenfield-contracts/contracts/interface/IApplication.sol`+/// (verified against `master` on 2026-07-08 —+/// https://github.com/bnb-chain/greenfield-contracts).+interface IApplication {+ /**+ * @param status STATUS_SUCCESS (0), STATUS_FAILED (1), or STATUS_UNEXPECTED (2).+ * @param channelId BUCKET_CHANNEL_ID (0x04) / OBJECT_CHANNEL_ID (0x05) /+ * GROUP_CHANNEL_ID (0x06) / PERMISSION_CHANNEL_ID (0x07).+ * @param operationType TYPE_CREATE (2) / TYPE_DELETE (3) / TYPE_UPDATE (4).+ * @param resourceId The ERC-721 token id of the resource operated on+ * (for PermissionHub: the created policy id). Not valid when+ * `status == STATUS_UNEXPECTED`.+ */+ function greenfieldCall(+ uint32 status,+ uint8 channelId,+ uint8 operationType,+ uint256 resourceId,+ bytes calldata callbackData+ ) external;+}diff --git a/contracts/src/greenfield/ICrossChain.sol b/contracts/src/greenfield/ICrossChain.solnew file mode 100644index 000000000..5a6f9d985--- /dev/null+++ b/contracts/src/greenfield/ICrossChain.sol@@ -0,0 +1,30 @@+// SPDX-License-Identifier: GPL-3.0-or-later+pragma solidity ^0.8.0;++/// @title ICrossChain+/// @notice Real ABI of BNB Greenfield's CrossChain contract — the relayer-fee+/// oracle every middle-layer hub (PermissionHub included) queries+/// before submitting a syn-package to Greenfield. Mirrors+/// `bnb-chain/greenfield-contracts/contracts/interface/ICrossChain.sol`+/// (verified against `master` on 2026-07-08 —+/// https://github.com/bnb-chain/greenfield-contracts).+///+/// Deployed addresses (bytecode-verified 2026-07-07, `00-CONTEXT.md`,+/// and that repo's README "Contract Entrypoint" for testnet):+/// mainnet(56) CrossChain `0x77e719b714be09F70D484AB81F70D02B0E182f7d`+/// testnet(97) CrossChain `0xa5B2c9194131A4E0BFaCbF9E5D6722c873159cb7`+interface ICrossChain {+ function sendSynPackage(uint8 channelId, bytes calldata msgBytes, uint256 relayFee, uint256 ackRelayFee) external;++ /// @return relayFee The BNB fee for relaying the syn-package to Greenfield.+ /// @return minAckRelayFee The minimum BNB fee for relaying the ack back to BSC.+ function getRelayFees() external view returns (uint256 relayFee, uint256 minAckRelayFee);++ function callbackGasPrice() external returns (uint256);++ function handleAckPackageFromMultiMessage(+ bytes calldata multiMessagePayload,+ uint8 packageType,+ uint64 multiMessageSequence+ ) external;+}diff --git a/contracts/src/greenfield/IGnfdAccessControl.sol b/contracts/src/greenfield/IGnfdAccessControl.solnew file mode 100644index 000000000..ae7328aaa--- /dev/null+++ b/contracts/src/greenfield/IGnfdAccessControl.sol@@ -0,0 +1,28 @@+// SPDX-License-Identifier: GPL-3.0-or-later+pragma solidity ^0.8.0;++/// @title IGnfdAccessControl+/// @notice Real ABI of the role-delegation surface every Greenfield+/// resource-mirror hub (BucketHub/ObjectHub/GroupHub) implements,+/// letting a resource owner authorize a third-party operator (e.g. a+/// marketplace contract) to act cross-chain on their behalf. Mirrors+/// `bnb-chain/greenfield-contracts/contracts/interface/IGnfdAccessControl.sol`+/// (verified against `master` on 2026-07-08 —+/// https://github.com/bnb-chain/greenfield-contracts).+///+/// `GreenfieldVault` reads this against ObjectHub — mainnet(56)+/// `0x634eB9c438b8378bbdd8D0e10970Ec88db0b4d0f`, testnet(97)+/// `0x1b059D8481dEe299713F18601fB539D066553e39` (`00-CONTEXT.md` /+/// that repo's README) — to enforce "the vault must control its+/// permissions" at `list()` time: a seller must+/// `grantRole(ROLE_CREATE, vaultAddress, expiry)` on their mirrored+/// Greenfield object before the vault will list it for sale.+interface IGnfdAccessControl {+ function hasRole(bytes32 role, address granter, address account) external view returns (bool);++ function grantRole(bytes32 role, address grantee, uint256 expireTime) external;++ function revokeRole(bytes32 role, address account) external;++ function renounceRole(bytes32 role, address granter) external;+}diff --git a/contracts/src/greenfield/IPermissionHub.sol b/contracts/src/greenfield/IPermissionHub.solnew file mode 100644index 000000000..e56f963b6--- /dev/null+++ b/contracts/src/greenfield/IPermissionHub.sol@@ -0,0 +1,74 @@+// SPDX-License-Identifier: GPL-3.0-or-later+pragma solidity ^0.8.0;++/// @title IPermissionHub+/// @notice Real ABI of BNB Greenfield's PermissionHub — the BSC-side cross-chain+/// entry point for creating/deleting Greenfield "policy" resources+/// (object/bucket/group permission grants). Mirrors+/// `bnb-chain/greenfield-contracts/contracts/interface/IPermissionHub.sol`+/// and the `ExtraData` / `FailureHandleStrategy` types it depends on from+/// `.../middle-layer/resource-mirror/storage/{PermissionStorage,CmnStorage}.sol`+/// and `.../storage/PackageQueue.sol` (verified against `master` on+/// 2026-07-08 — https://github.com/bnb-chain/greenfield-contracts).+///+/// Deployed addresses (from that repo's README "Contract Entrypoint"):+/// mainnet(56) PermissionHub `0xe1776006dBE9B60d9eA38C0dDb80b41f2657acE8`+/// testnet(97) PermissionHub `0x25E1eeDb5CaBf288210B132321FBB2d90b4174ad`+///+/// Reproduced here as a minimal interface — not the full upgradeable+/// implementation tree, which depends on OpenZeppelin's upgradeable+/// contracts package (a library this workspace does not otherwise+/// use) — so `GreenfieldVault` can call the real, already deployed+/// contract without inventing any signature or address.+interface IPermissionHub {+ /// @dev Mirrors `PackageQueue.FailureHandleStrategy`. Only `SkipOnFail` is+ /// accepted by `AdditionalPermissionHub._prepareCreatePolicy`/+ /// `_prepareDeletePolicy` when an `ExtraData` callback is supplied —+ /// the other two strategies exist for GNFD-native middle-layer apps+ /// that need retry/blocking semantics this vault does not use.+ enum FailureHandleStrategy {+ BlockOnFail,+ CacheOnFail,+ SkipOnFail+ }++ /// @dev Mirrors `CmnStorage.ExtraData`. `appAddress` is ALWAYS overwritten+ /// by `AdditionalPermissionHub` to the effective caller+ /// (`_erc2771Sender()`) before the syn-package is sent — whatever a+ /// caller passes for this field is ignored on-chain; the ack callback+ /// (`IApplication.greenfieldCall`) always targets the real caller.+ struct ExtraData {+ address appAddress;+ address refundAddress;+ FailureHandleStrategy failureHandleStrategy;+ bytes callbackData;+ }++ function createPolicy(bytes calldata data) external payable returns (bool);++ function createPolicy(bytes calldata data, ExtraData memory extraData) external payable returns (bool);++ function deletePolicy(uint256 id) external payable returns (bool);++ function deletePolicy(uint256 id, ExtraData memory extraData) external payable returns (bool);++ function prepareCreatePolicy(address sender, bytes calldata data)+ external+ payable+ returns (uint8, bytes memory, uint256, uint256, address);++ function prepareCreatePolicy(address sender, bytes calldata data, ExtraData memory extraData)+ external+ payable+ returns (uint8, bytes memory, uint256, uint256, address);++ function prepareDeletePolicy(address sender, uint256 id)+ external+ payable+ returns (uint8, bytes memory, uint256, uint256, address);++ function prepareDeletePolicy(address sender, uint256 id, ExtraData memory extraData)+ external+ payable+ returns (uint8, bytes memory, uint256, uint256, address);+}diff --git a/contracts/test/GreenfieldVault.t.sol b/contracts/test/GreenfieldVault.t.solnew file mode 100644index 000000000..ba6ce4fe5--- /dev/null+++ b/contracts/test/GreenfieldVault.t.sol@@ -0,0 +1,461 @@+// SPDX-License-Identifier: MIT+pragma solidity ^0.8.24;++import {Test} from "forge-std/Test.sol";+import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";+import {GreenfieldVault} from "../src/GreenfieldVault.sol";+import {IPermissionHub} from "../src/greenfield/IPermissionHub.sol";+import {MockCrossChain, MockPermissionHub, MockGnfdAccessControl} from "./mocks/MockGreenfield.sol";+import {Reentrant} from "./mocks/Reentrant.sol";++contract GreenfieldVaultTest is Test {+ MockCrossChain internal crossChain;+ MockPermissionHub internal permissionHub;+ MockGnfdAccessControl internal accessControl;+ GreenfieldVault internal vault;++ address internal seller = makeAddr("seller");+ address internal buyer = makeAddr("buyer");+ address internal buyer2 = makeAddr("buyer2");++ bytes32 internal constant OBJECT_ID = keccak256("three-ws/vault/object-1");+ bytes32 internal constant OBJECT_ID_2 = keccak256("three-ws/vault/object-2");+ uint256 internal constant PRICE = 1 ether;+ uint256 internal constant RELAY_FEE = 0.001 ether;+ uint256 internal constant ACK_RELAY_FEE = 0.0005 ether;+ uint256 internal constant TOTAL_FEE = RELAY_FEE + ACK_RELAY_FEE;+ uint256 internal constant TOTAL_REQUIRED = PRICE + TOTAL_FEE;++ // Opaque stand-in for an off-chain-built Greenfield permission payload+ // (real protobuf principal/resource/statements — see GreenfieldVault.buy natspec).+ bytes internal constant POLICY_DATA = hex"0102030405";++ uint32 internal constant STATUS_SUCCESS = 0;+ uint32 internal constant STATUS_FAILED = 1;++ event Listed(bytes32 indexed objectId, address indexed seller, uint256 price);+ event Delisted(bytes32 indexed objectId, address indexed seller);+ event Purchased(bytes32 indexed objectId, address indexed buyer, uint256 indexed saleId, uint256 price);+ event PolicyGranted(bytes32 indexed objectId, address indexed buyer, uint256 indexed saleId, uint256 policyId);+ event PolicyGrantFailed(bytes32 indexed objectId, address indexed buyer, uint256 indexed saleId, uint32 status);+ event RevokeRequested(bytes32 indexed objectId, uint256 indexed saleId, uint256 policyId);+ event Withdrawn(address indexed seller, uint256 amount);++ function setUp() public {+ crossChain = new MockCrossChain(RELAY_FEE, ACK_RELAY_FEE);+ permissionHub = new MockPermissionHub(crossChain);+ accessControl = new MockGnfdAccessControl();+ vault = new GreenfieldVault(address(permissionHub), address(crossChain), address(accessControl));++ vm.deal(seller, 10 ether);+ vm.deal(buyer, 10 ether);+ vm.deal(buyer2, 10 ether);+ }++ // ── helpers ──────────────────────────────────────────────────────────++ function _grantRole(address _seller) internal {+ bytes32 role = vault.ROLE_CREATE();+ vm.prank(_seller);+ accessControl.grantRole(role, address(vault), 0);+ }++ function _list(address _seller, bytes32 objectId, uint256 price) internal {+ _grantRole(_seller);+ vm.prank(_seller);+ vault.list(objectId, price, _seller);+ }++ function _buy(address _buyer, bytes32 objectId) internal returns (uint256 saleId) {+ vm.prank(_buyer);+ saleId = vault.buy{value: TOTAL_REQUIRED}(objectId, POLICY_DATA);+ }++ // ── constructor ──────────────────────────────────────────────────────++ function testConstructorRejectsZeroAddresses() public {+ vm.expectRevert(GreenfieldVault.ZeroAddress.selector);+ new GreenfieldVault(address(0), address(crossChain), address(accessControl));++ vm.expectRevert(GreenfieldVault.ZeroAddress.selector);+ new GreenfieldVault(address(permissionHub), address(0), address(accessControl));++ vm.expectRevert(GreenfieldVault.ZeroAddress.selector);+ new GreenfieldVault(address(permissionHub), address(crossChain), address(0));+ }++ // ── list / delist ────────────────────────────────────────────────────++ function testListRequiresRoleGrant() public {+ vm.prank(seller);+ vm.expectRevert(GreenfieldVault.NotAuthorizedByObjectOwner.selector);+ vault.list(OBJECT_ID, PRICE, seller);+ }++ function testListOnlySeller() public {+ _grantRole(seller);+ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.OnlySeller.selector);+ vault.list(OBJECT_ID, PRICE, seller);+ }++ function testListRejectsBadInput() public {+ _grantRole(seller);+ vm.startPrank(seller);+ vm.expectRevert(GreenfieldVault.BadObjectId.selector);+ vault.list(bytes32(0), PRICE, seller);++ vm.expectRevert(GreenfieldVault.BadPrice.selector);+ vault.list(OBJECT_ID, 0, seller);+ vm.stopPrank();+ }++ function testListEmitsAndStores() public {+ _grantRole(seller);+ vm.prank(seller);+ vm.expectEmit(true, true, false, true, address(vault));+ emit Listed(OBJECT_ID, seller, PRICE);+ vault.list(OBJECT_ID, PRICE, seller);++ (address listedSeller, uint256 price, bool active) = vault.listings(OBJECT_ID);+ assertEq(listedSeller, seller);+ assertEq(price, PRICE);+ assertTrue(active);+ }++ function testRelistBySameSellerUpdatesPrice() public {+ _list(seller, OBJECT_ID, PRICE);+ vm.prank(seller);+ vault.list(OBJECT_ID, PRICE * 2, seller);+ (, uint256 price,) = vault.listings(OBJECT_ID);+ assertEq(price, PRICE * 2);+ }++ function testListByAnotherSellerReverts() public {+ _list(seller, OBJECT_ID, PRICE);+ _grantRole(buyer);+ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.ListedByAnotherSeller.selector);+ vault.list(OBJECT_ID, PRICE, buyer);+ }++ function testDelist() public {+ _list(seller, OBJECT_ID, PRICE);+ vm.prank(seller);+ vm.expectEmit(true, true, false, true, address(vault));+ emit Delisted(OBJECT_ID, seller);+ vault.delist(OBJECT_ID);++ (,, bool active) = vault.listings(OBJECT_ID);+ assertFalse(active);+ }++ function testDelistOnlySeller() public {+ _list(seller, OBJECT_ID, PRICE);+ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.OnlySeller.selector);+ vault.delist(OBJECT_ID);+ }++ function testDelistNotListedReverts() public {+ vm.expectRevert(GreenfieldVault.NotListed.selector);+ vault.delist(OBJECT_ID);+ }++ // ── buy ──────────────────────────────────────────────────────────────++ function testBuyHappyPathAndSettlement() public {+ _list(seller, OBJECT_ID, PRICE);++ vm.prank(buyer);+ vm.expectEmit(true, true, true, true, address(vault));+ emit Purchased(OBJECT_ID, buyer, 1, PRICE);+ uint256 saleId = vault.buy{value: TOTAL_REQUIRED}(OBJECT_ID, POLICY_DATA);++ assertEq(saleId, 1);+ assertEq(vault.pendingWithdrawals(seller), PRICE);+ assertEq(vault.saleIdOf(OBJECT_ID, buyer), 1);++ (+ bytes32 objId,+ address buy_,+ address sell_,+ uint256 price_,+ uint256 policyId_,+ GreenfieldVault.SaleStatus status_+ ) = vault.sales(1);+ assertEq(objId, OBJECT_ID);+ assertEq(buy_, buyer);+ assertEq(sell_, seller);+ assertEq(price_, PRICE);+ assertEq(policyId_, 0);+ assertEq(uint8(status_), uint8(GreenfieldVault.SaleStatus.Pending));++ // Simulate the real Greenfield relayer settling the ack.+ vm.expectEmit(true, true, true, true, address(vault));+ emit PolicyGranted(OBJECT_ID, buyer, 1, 1);+ permissionHub.settleCreatePolicy(1, STATUS_SUCCESS);++ (,,,, uint256 policyIdAfter, GreenfieldVault.SaleStatus statusAfter) = vault.sales(1);+ assertEq(policyIdAfter, 1);+ assertEq(uint8(statusAfter), uint8(GreenfieldVault.SaleStatus.Granted));+ }++ function testBuyUnlistedReverts() public {+ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.NotListed.selector);+ vault.buy{value: TOTAL_REQUIRED}(OBJECT_ID, POLICY_DATA);+ }++ function testBuyEmptyPolicyDataReverts() public {+ _list(seller, OBJECT_ID, PRICE);+ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.EmptyPolicyData.selector);+ vault.buy{value: TOTAL_REQUIRED}(OBJECT_ID, "");+ }++ function testBuyUnderpaymentReverts() public {+ _list(seller, OBJECT_ID, PRICE);+ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.InsufficientPayment.selector);+ vault.buy{value: TOTAL_REQUIRED - 1}(OBJECT_ID, POLICY_DATA);+ }++ function testBuyMissingCrossChainFeeReverts() public {+ _list(seller, OBJECT_ID, PRICE);+ // Pays the exact list price but covers none of the relay fee.+ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.InsufficientPayment.selector);+ vault.buy{value: PRICE}(OBJECT_ID, POLICY_DATA);+ }++ function testBuyDoesNotHalfExecuteOnUnderpayment() public {+ _list(seller, OBJECT_ID, PRICE);+ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.InsufficientPayment.selector);+ vault.buy{value: PRICE}(OBJECT_ID, POLICY_DATA);++ // Nothing was recorded: no sale, no pending withdrawal, no saleIdOf entry.+ assertEq(vault.nextSaleId(), 1);+ assertEq(vault.pendingWithdrawals(seller), 0);+ assertEq(vault.saleIdOf(OBJECT_ID, buyer), 0);+ }++ function testBuyRefundsExcessPayment() public {+ _list(seller, OBJECT_ID, PRICE);+ uint256 overpay = TOTAL_REQUIRED + 0.5 ether;+ uint256 before = buyer.balance;++ vm.prank(buyer);+ vault.buy{value: overpay}(OBJECT_ID, POLICY_DATA);++ assertEq(buyer.balance, before - TOTAL_REQUIRED);+ }++ function testDoubleBuySameBuyerReverts() public {+ _list(seller, OBJECT_ID, PRICE);+ _buy(buyer, OBJECT_ID);++ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.AlreadyPurchased.selector);+ vault.buy{value: TOTAL_REQUIRED}(OBJECT_ID, POLICY_DATA);+ }++ function testDifferentBuyersCanEachPurchase() public {+ _list(seller, OBJECT_ID, PRICE);+ uint256 saleId1 = _buy(buyer, OBJECT_ID);+ uint256 saleId2 = _buy(buyer2, OBJECT_ID);+ assertTrue(saleId1 != saleId2);+ assertEq(vault.pendingWithdrawals(seller), PRICE * 2);+ }++ function testSettlementFailureAllowsRetry() public {+ _list(seller, OBJECT_ID, PRICE);+ uint256 saleId = _buy(buyer, OBJECT_ID);++ vm.expectEmit(true, true, true, true, address(vault));+ emit PolicyGrantFailed(OBJECT_ID, buyer, saleId, STATUS_FAILED);+ permissionHub.settleCreatePolicy(saleId, STATUS_FAILED);++ (,,,,, GreenfieldVault.SaleStatus status) = vault.sales(saleId);+ assertEq(uint8(status), uint8(GreenfieldVault.SaleStatus.Failed));+ assertEq(vault.saleIdOf(OBJECT_ID, buyer), 0);++ // Buyer can now retry.+ uint256 saleId2 = _buy(buyer, OBJECT_ID);+ assertTrue(saleId2 != saleId);+ }++ // ── greenfieldCall access control ───────────────────────────────────++ function testGreenfieldCallOnlyPermissionHub() public {+ vm.expectRevert(GreenfieldVault.OnlyPermissionHub.selector);+ vault.greenfieldCall(STATUS_SUCCESS, 0x07, 2, 1, abi.encode(uint256(1)));+ }++ function testGreenfieldCallBadChannelReverts() public {+ vm.prank(address(permissionHub));+ vm.expectRevert(GreenfieldVault.BadChannel.selector);+ vault.greenfieldCall(STATUS_SUCCESS, 0x05, 2, 1, abi.encode(uint256(1)));+ }++ function testGreenfieldCallUnknownSaleReverts() public {+ vm.prank(address(permissionHub));+ vm.expectRevert(GreenfieldVault.UnknownSale.selector);+ vault.greenfieldCall(STATUS_SUCCESS, 0x07, 2, 999, abi.encode(uint256(999)));+ }++ // ── revoke ───────────────────────────────────────────────────────────++ function testRevokeHappyPath() public {+ _list(seller, OBJECT_ID, PRICE);+ uint256 saleId = _buy(buyer, OBJECT_ID);+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);++ vm.prank(seller);+ vm.expectEmit(true, true, false, true, address(vault));+ emit RevokeRequested(OBJECT_ID, saleId, saleId); // policyId == saleId here (both start at 1)+ vault.revoke{value: TOTAL_FEE}(saleId);++ (,,,,, GreenfieldVault.SaleStatus status) = vault.sales(saleId);+ assertEq(uint8(status), uint8(GreenfieldVault.SaleStatus.Revoked));+ assertEq(vault.saleIdOf(OBJECT_ID, buyer), 0);+ assertTrue(permissionHub.deletedPolicies(saleId));++ // Buyer can be resold access.+ uint256 saleId2 = _buy(buyer, OBJECT_ID);+ assertTrue(saleId2 != saleId);+ }++ function testRevokeOnlySaleSeller() public {+ _list(seller, OBJECT_ID, PRICE);+ uint256 saleId = _buy(buyer, OBJECT_ID);+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);++ vm.prank(buyer);+ vm.expectRevert(GreenfieldVault.NotSaleSeller.selector);+ vault.revoke{value: TOTAL_FEE}(saleId);+ }++ function testRevokeUnknownSaleReverts() public {+ vm.prank(seller);+ vm.expectRevert(GreenfieldVault.UnknownSale.selector);+ vault.revoke{value: TOTAL_FEE}(999);+ }++ function testRevokeRequiresGrantedStatus() public {+ _list(seller, OBJECT_ID, PRICE);+ uint256 saleId = _buy(buyer, OBJECT_ID);+ // Still Pending — never settled.+ vm.prank(seller);+ vm.expectRevert(GreenfieldVault.SaleNotGranted.selector);+ vault.revoke{value: TOTAL_FEE}(saleId);+ }++ function testRevokeInsufficientFeeReverts() public {+ _list(seller, OBJECT_ID, PRICE);+ uint256 saleId = _buy(buyer, OBJECT_ID);+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);++ vm.prank(seller);+ vm.expectRevert(GreenfieldVault.InsufficientRelayFee.selector);+ vault.revoke{value: TOTAL_FEE - 1}(saleId);+ }++ function testRevokeRefundsExcessFee() public {+ _list(seller, OBJECT_ID, PRICE);+ uint256 saleId = _buy(buyer, OBJECT_ID);+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);++ uint256 before = seller.balance;+ vm.prank(seller);+ vault.revoke{value: TOTAL_FEE + 0.2 ether}(saleId);+ assertEq(seller.balance, before - TOTAL_FEE);+ }++ // ── withdraw ─────────────────────────────────────────────────────────++ function testWithdrawHappyPath() public {+ _list(seller, OBJECT_ID, PRICE);+ _buy(buyer, OBJECT_ID);++ uint256 before = seller.balance;+ vm.prank(seller);+ vm.expectEmit(true, false, false, true, address(vault));+ emit Withdrawn(seller, PRICE);+ uint256 amount = vault.withdraw();++ assertEq(amount, PRICE);+ assertEq(seller.balance, before + PRICE);+ assertEq(vault.pendingWithdrawals(seller), 0);+ }++ function testWithdrawNothingReverts() public {+ vm.prank(seller);+ vm.expectRevert(GreenfieldVault.NothingToWithdraw.selector);+ vault.withdraw();+ }++ // ── views ────────────────────────────────────────────────────────────++ function testQuoteRelayFee() public view {+ (uint256 relayFee, uint256 minAckRelayFee, uint256 total) = vault.quoteRelayFee();+ assertEq(relayFee, RELAY_FEE);+ assertEq(minAckRelayFee, ACK_RELAY_FEE);+ assertEq(total, TOTAL_FEE);+ }++ // ── re-entrancy ──────────────────────────────────────────────────────++ /// Proves `nonReentrant` blocks a *cross-function* reentrant call: an+ /// attacker buying object A, whose refund callback tries to buy an+ /// entirely separate, validly listed object B. Absent the guard this+ /// nested `buy()` would succeed outright (B is listed, unpurchased, fully+ /// funded) — instead the whole outer transaction reverts, proving the+ /// lock (not incidental state) is what stopped it.+ function testReentrantBuyBlocked() public {+ _list(seller, OBJECT_ID, PRICE);+ _list(seller, OBJECT_ID_2, PRICE);++ Reentrant attacker = new Reentrant(vault);+ vm.deal(address(attacker), 10 ether);++ attacker.arm(abi.encodeWithSelector(GreenfieldVault.buy.selector, OBJECT_ID_2, POLICY_DATA), TOTAL_REQUIRED);++ uint256 overpay = TOTAL_REQUIRED + TOTAL_REQUIRED; // enough refund to fund the nested attempt+ // The outer buy() itself succeeds — the low-level refund call only+ // reverts if the *callee* (receive()) reverts, and receive() swallows+ // the nested call's failure via a low-level `.call`. What proves the+ // guard fired is that the nested call captured inside `attacker`+ // failed with exactly `ReentrancyGuardReentrantCall`.+ attacker.doBuy{value: overpay}(OBJECT_ID, POLICY_DATA);++ assertTrue(attacker.reentryAttempted());+ assertFalse(attacker.reentryOk());+ assertEq(bytes4(attacker.reentryReturnData()), ReentrancyGuard.ReentrancyGuardReentrantCall.selector);++ // The nested buy never happened: object B is still unpurchased.+ assertEq(vault.saleIdOf(OBJECT_ID_2, address(attacker)), 0);+ }++ /// Same proof against `withdraw()`: a malicious seller's payout callback+ /// tries to re-enter `withdraw()` itself.+ function testReentrantWithdrawBlocked() public {+ Reentrant attacker = new Reentrant(vault);+ bytes32 role = vault.ROLE_CREATE();+ vm.prank(address(attacker));+ accessControl.grantRole(role, address(vault), 0);+ attacker.doList(OBJECT_ID, PRICE);++ _buy(buyer, OBJECT_ID);+ assertEq(vault.pendingWithdrawals(address(attacker)), PRICE);++ attacker.arm(abi.encodeWithSelector(GreenfieldVault.withdraw.selector), 0);++ attacker.doWithdraw();++ assertTrue(attacker.reentryAttempted());+ assertFalse(attacker.reentryOk());+ assertEq(bytes4(attacker.reentryReturnData()), ReentrancyGuard.ReentrancyGuardReentrantCall.selector);+ }+}diff --git a/contracts/test/mocks/MockGreenfield.sol b/contracts/test/mocks/MockGreenfield.solnew file mode 100644index 000000000..1dec0c579--- /dev/null+++ b/contracts/test/mocks/MockGreenfield.sol@@ -0,0 +1,213 @@+// SPDX-License-Identifier: MIT+pragma solidity ^0.8.24;++import {IPermissionHub} from "../../src/greenfield/IPermissionHub.sol";+import {ICrossChain} from "../../src/greenfield/ICrossChain.sol";+import {IGnfdAccessControl} from "../../src/greenfield/IGnfdAccessControl.sol";+import {IApplication} from "../../src/greenfield/IApplication.sol";++/// @notice Minimal, faithful mock of the real `CrossChain` relay-fee oracle.+/// Fees are test-configurable; every other real hub (including the+/// mock PermissionHub below) queries this exactly like production.+contract MockCrossChain is ICrossChain {+ uint256 public relayFee;+ uint256 public minAckRelayFee;++ constructor(uint256 _relayFee, uint256 _minAckRelayFee) {+ relayFee = _relayFee;+ minAckRelayFee = _minAckRelayFee;+ }++ function setFees(uint256 _relayFee, uint256 _minAckRelayFee) external {+ relayFee = _relayFee;+ minAckRelayFee = _minAckRelayFee;+ }++ function sendSynPackage(uint8, bytes calldata, uint256, uint256) external override {}++ function getRelayFees() external view override returns (uint256, uint256) {+ return (relayFee, minAckRelayFee);+ }++ function callbackGasPrice() external pure override returns (uint256) {+ return 0;+ }++ function handleAckPackageFromMultiMessage(bytes calldata, uint8, uint64) external override {}+}++/// @notice Mock of the real `PermissionHub`, faithful to the two-phase+/// syn/ack cross-chain flow: `createPolicy`/`deletePolicy` only+/// accept the request and charge the relay fee (mirroring+/// `AdditionalPermissionHub._prepareCreatePolicy`'s fee check and+/// `appAddress` override to the real caller) — a separate `settle*`+/// call, invoked by the test harness playing the role of the+/// Greenfield relayer, delivers the async ack via+/// `IApplication.greenfieldCall`, exactly like the real+/// `CmnHub._handleCreateAckPackage` does once Greenfield settles.+contract MockPermissionHub is IPermissionHub {+ uint8 private constant PERMISSION_CHANNEL_ID = 0x07;+ uint32 private constant STATUS_SUCCESS = 0;+ uint8 private constant TYPE_CREATE = 2;++ ICrossChain public immutable crossChain;+ uint256 public nextPolicyId = 1;+ bool public revertOnCreate;+ bool public revertOnDelete;++ struct PendingCreate {+ address caller; // becomes the minted policy's owner on success, mirrors real `_doCreate`+ bytes callbackData;+ bool hasCallback;+ bool settled;+ }++ mapping(uint256 => PendingCreate) public pendingCreates;+ mapping(uint256 => address) public policyOwner; // set on successful settle, mirrors ERC721Token.ownerOf+ mapping(uint256 => bool) public deletedPolicies;++ event CreatePolicyRequested(address indexed caller, uint256 indexed policyId, bytes data);+ event DeletePolicyRequested(address indexed caller, uint256 indexed policyId);++ constructor(ICrossChain _crossChain) {+ crossChain = _crossChain;+ }++ function setRevertOnCreate(bool v) external {+ revertOnCreate = v;+ }++ function setRevertOnDelete(bool v) external {+ revertOnDelete = v;+ }++ /*----------------- IPermissionHub -----------------*/++ function createPolicy(bytes calldata data) external payable override returns (bool) {+ _createPolicy(data, "", false);+ return true;+ }++ function createPolicy(bytes calldata data, ExtraData memory extraData) external payable override returns (bool) {+ require(extraData.failureHandleStrategy == FailureHandleStrategy.SkipOnFail, "only SkipOnFail");+ _createPolicy(data, extraData.callbackData, true);+ return true;+ }++ function deletePolicy(uint256 id) external payable override returns (bool) {+ _deletePolicy(id);+ return true;+ }++ function deletePolicy(uint256 id, ExtraData memory extraData) external payable override returns (bool) {+ require(extraData.failureHandleStrategy == FailureHandleStrategy.SkipOnFail, "only SkipOnFail");+ _deletePolicy(id);+ return true;+ }++ function prepareCreatePolicy(address, bytes calldata)+ external+ payable+ override+ returns (uint8, bytes memory, uint256, uint256, address)+ {+ revert("not implemented");+ }++ function prepareCreatePolicy(address, bytes calldata, ExtraData memory)+ external+ payable+ override+ returns (uint8, bytes memory, uint256, uint256, address)+ {+ revert("not implemented");+ }++ function prepareDeletePolicy(address, uint256)+ external+ payable+ override+ returns (uint8, bytes memory, uint256, uint256, address)+ {+ revert("not implemented");+ }++ function prepareDeletePolicy(address, uint256, ExtraData memory)+ external+ payable+ override+ returns (uint8, bytes memory, uint256, uint256, address)+ {+ revert("not implemented");+ }++ /*----------------- internal -----------------*/++ function _createPolicy(bytes calldata data, bytes memory callbackData, bool hasCallback) internal {+ (uint256 relayFee, uint256 minAckRelayFee) = crossChain.getRelayFees();+ require(msg.value >= relayFee + minAckRelayFee, "not enough fee");+ require(data.length > 0, "empty data");+ if (revertOnCreate) revert("mock: create reverted");++ uint256 policyId = nextPolicyId++;+ pendingCreates[policyId] =+ PendingCreate({caller: msg.sender, callbackData: callbackData, hasCallback: hasCallback, settled: false});+ emit CreatePolicyRequested(msg.sender, policyId, data);+ }++ function _deletePolicy(uint256 id) internal {+ (uint256 relayFee, uint256 minAckRelayFee) = crossChain.getRelayFees();+ require(msg.value >= relayFee + minAckRelayFee, "not enough fee");+ if (revertOnDelete) revert("mock: delete reverted");+ require(policyOwner[id] == msg.sender, "invalid operator");++ deletedPolicies[id] = true;+ emit DeletePolicyRequested(msg.sender, id);+ }++ /*----------------- test harness: simulate the GNFD relayer -----------------*/++ /// @notice Simulate the async ack for `policyId` settling with `status`+ /// (0 = STATUS_SUCCESS, 1 = STATUS_FAILED). Mirrors+ /// `CmnHub._handleCreateAckPackage`: mints the policy to the+ /// original caller on success, then — if the caller opted into a+ /// callback — invokes `IApplication.greenfieldCall` on it.+ function settleCreatePolicy(uint256 policyId, uint32 status) external {+ PendingCreate storage p = pendingCreates[policyId];+ require(p.caller != address(0), "unknown policy");+ require(!p.settled, "already settled");+ p.settled = true;++ if (status == STATUS_SUCCESS) {+ policyOwner[policyId] = p.caller;+ }++ if (p.hasCallback) {+ IApplication(p.caller).greenfieldCall(status, PERMISSION_CHANNEL_ID, TYPE_CREATE, policyId, p.callbackData);+ }+ }+}++/// @notice Mock of the real `IGnfdAccessControl` surface implemented by+/// ObjectHub. `grantRole`/`revokeRole` key by `msg.sender` as the+/// granter, exactly like the real contract.+contract MockGnfdAccessControl is IGnfdAccessControl {+ // role => granter => account => granted+ mapping(bytes32 => mapping(address => mapping(address => bool))) private _roles;++ function hasRole(bytes32 role, address granter, address account) external view override returns (bool) {+ return _roles[role][granter][account];+ }++ function grantRole(bytes32 role, address grantee, uint256) external override {+ _roles[role][msg.sender][grantee] = true;+ }++ function revokeRole(bytes32 role, address account) external override {+ _roles[role][msg.sender][account] = false;+ }++ function renounceRole(bytes32 role, address granter) external override {+ _roles[role][granter][msg.sender] = false;+ }+}diff --git a/contracts/test/mocks/Reentrant.sol b/contracts/test/mocks/Reentrant.solnew file mode 100644index 000000000..b8d44bc05--- /dev/null+++ b/contracts/test/mocks/Reentrant.sol@@ -0,0 +1,58 @@+// SPDX-License-Identifier: MIT+pragma solidity ^0.8.24;++import {GreenfieldVault} from "../../src/GreenfieldVault.sol";++/// @notice Generic reentrancy-attack harness: acts as buyer/seller against+/// `GreenfieldVault` and, on receiving a refund/payout, attempts one+/// armed reentrant call back into the vault. Used to prove+/// `nonReentrant` blocks cross-function reentrancy (e.g. a `buy()`+/// refund trying to trigger a second `buy()`), not merely that+/// checks-effects-interactions happens to leave nothing to steal.+contract Reentrant {+ GreenfieldVault public immutable vault;++ bytes private _reentryCalldata;+ uint256 private _reentryValue;+ bool private _armed;++ bool public reentryAttempted;+ bool public reentryOk;+ bytes public reentryReturnData;++ constructor(GreenfieldVault _vault) {+ vault = _vault;+ }++ function arm(bytes calldata data, uint256 value) external {+ _reentryCalldata = data;+ _reentryValue = value;+ _armed = true;+ }++ receive() external payable {+ if (_armed) {+ _armed = false;+ reentryAttempted = true;+ (bool ok, bytes memory ret) = address(vault).call{value: _reentryValue}(_reentryCalldata);+ reentryOk = ok;+ reentryReturnData = ret;+ }+ }++ function doList(bytes32 objectId, uint256 price) external {+ vault.list(objectId, price, address(this));+ }++ function doBuy(bytes32 objectId, bytes calldata policyData) external payable returns (uint256) {+ return vault.buy{value: msg.value}(objectId, policyData);+ }++ function doWithdraw() external {+ vault.withdraw();+ }++ function doRevoke(uint256 saleId) external payable {+ vault.revoke{value: msg.value}(saleId);+ }+}diff --git a/data/changelog.json b/data/changelog.jsonindex 6b9d298ee..f0d842989 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$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": "Register your agent identity on BNB Chain with zero gas",+ "summary": "A brand-new wallet holding zero tBNB can now mint its ERC-8004 on-chain identity on BSC Testnet in one click — no faucet, no funding. The /deploy wizard's Review & Deploy step gets a new ⚡ Register gasless button when BSC Testnet is selected: it generates a page-local wallet in your browser, signs the registration transaction, and relays it through BNB Chain's MegaFuel paymaster, which sponsors the gas atomically at the block-builder layer — a trick that's mechanically impossible on Ethereum or Base. If sponsorship isn't available for a given wallet, it falls back cleanly to a small self-paid transaction (well under a cent) instead of failing.",+ "tags": [+ "feature",+ "sdk"+ ],+ "link": "/deploy"+ },{"date": "2026-07-08","title": "Restyle Studio can now AI-restyle any model and remembers every version",diff --git a/data/pages.json b/data/pages.jsonindex 339bcf2e5..1dab84639 100644--- a/data/pages.json+++ b/data/pages.json@@ -1698,6 +1698,15 @@"added": "2026-07-07","showcase": true},+ {+ "path": "/crypto-api",+ "title": "Crypto API",+ "description": "One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.",+ "priority": 0.8,+ "changefreq": "weekly",+ "added": "2026-07-08",+ "showcase": true+ },{"path": "/docs/crypto-api","title": "Docs · Crypto Data API",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex eb6bdf853..d16f0b3e9 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -2384,6 +2384,14 @@ reads** (`solana`, balance/token-holdings/token-supply/largest-holders/transaction/account/priority-fees via public RPC), **OpenAI-compatible LLM**(`openai`).+**Public storefront:** [three.ws/crypto-api](https://three.ws/crypto-api) — the live+provider/endpoint table below, rendered at page load straight from `GET /api/v1/x` (never+hand-enumerated, so it can't drift from what's actually deployed), plus the quickstart curl+below and links to this page, the OpenAPI spec, and the x402 docs. **Machine-readable spec:**+[three.ws/openapi.json](https://three.ws/openapi.json) — every `/api/v1/x/*` path generated+from the same registry (`api/v1/_providers.js` `providerCatalog()`), tagged `Crypto API+(aggregator)`. Adding a provider directory in the repo: [`api/v1/README.md`](../api/v1/README.md).+```GET /api/v1/x # discovery: every provider + endpointGET /api/v1/x/<provider>/<endpoint>?… # most endpoints (GET)diff --git a/docs/erc8004.md b/docs/erc8004.mdindex caf0440fd..0fdcaf248 100644--- a/docs/erc8004.md+++ b/docs/erc8004.md@@ -205,6 +205,64 @@ https://three.ws/a/<chainId>/<agentId>/embed---+## Gasless agent registration on BNB++A brand-new wallet holding **zero tBNB** can mint its ERC-8004 identity on BSC Testnet in one click — no faucet, no funding, no wallet-connect step. This is BNB Chain's BEP-414 paymaster (MegaFuel, operated by NodeReal): a plain private-key EOA signs a normal transaction with `gasPrice: 0`, and a sponsor transaction pairs with it atomically at the block-builder layer. It's mechanically impossible on Ethereum L1/Base (EIP-1559 rejects a zero-fee tx; ERC-4337 needs a smart account; EIP-7702 needs delegation) — see `prompts/bnb-chain/00-CONTEXT.md` for the full verified-facts writeup.++**How it works, end to end:**++1. The browser generates a fresh, page-local ephemeral BSC account (`src/erc8004/gasless-register.js`, `getEphemeralAccount()`). Its private key is stored in `sessionStorage` only — it never leaves the browser and is never sent anywhere.+2. It signs a legacy `register(agentURI)` transaction against the Identity Registry with `gasPrice: 0`.+3. The signed bytes (not the key) are POSTed to `/api/bnb/register-agent`, which probes MegaFuel's `pm_isSponsorable` and, if sponsorable, relays the exact bytes via `eth_sendRawTransaction` to MegaFuel's paymaster (`api/_lib/bnb/megafuel.js`, `api/_lib/bnb/erc8004-gasless.js`).+4. If MegaFuel declines sponsorship, the endpoint returns `{ mode: 'declined', reason, hint }` instead of failing — a zero-gasPrice transaction can never be broadcast to a normal node outside the paymaster path, so there is nothing to retry blindly. The UI shows the wallet address and a "fund it and retry" prompt; a self-pay retry re-signs the same call with a real gasPrice and broadcasts normally.++**Try it:** go to [/deploy](https://three.ws/deploy), pick **BSC Testnet** in the network selector, fill in a name and description, and on the final "Review & Deploy" step click **⚡ Register gasless (0 tBNB wallet)** — no wallet extension required for this path.++**Server endpoint** — `POST /api/bnb/register-agent`:++```bash+curl -X POST https://three.ws/api/bnb/register-agent \+ -H 'content-type: application/json' \+ -d '{+ "signedRegisterTx": "0xf8...<a legacy, gasPrice:0, signed register() tx>",+ "network": "bscTestnet"+ }'+```++A real response, sponsored (zero-balance wallet, live BSC testnet, 2026-07-08):++```json+{+ "mode": "sponsored",+ "address": "0xfb35130d94D80437eb3350c71e2c62898e9c57E3",+ "network": "bscTestnet",+ "sponsor": { "sponsorable": true, "sponsorName": "Yolin", "sponsorIcon": "Yolin" },+ "pending": false,+ "agentId": "1593",+ "hash": "0x29b2999e1543d7e6d4eba21b41b33718d8e0196e18c1510d39e4cffcfe52bc95",+ "blockNumber": 117842997,+ "explorerUrl": "https://testnet.bscscan.com/tx/0x29b2999e1543d7e6d4eba21b41b33718d8e0196e18c1510d39e4cffcfe52bc95"+}+```++That transaction's receipt shows `effectiveGasPrice: 0x0` and `status: 0x1` on the live public RPC — a genuinely free, sponsored mint, not a simulation.++**Response shapes:**++| Shape | When |+|---|---|+| `{ mode: 'sponsored', hash, agentId, explorerUrl }` | MegaFuel accepted the probe and relayed the exact signed bytes. |+| `{ mode: 'self-pay', hash, agentId, explorerUrl }` | The caller re-signed with a real `gasPrice` (after a decline, or knowing sponsorship was unavailable) and the endpoint broadcast it normally. |+| `{ mode: 'declined', reason, hint, address }` | MegaFuel has no sponsor policy for this address right now. No broadcast was attempted — resign with a real `gasPrice` and POST again to self-pay. |+| `{ alreadyRegistered: true, agentId, address, explorerUrl }` | This address already owns an agent on the registry — no new mint. `agentId` is `null` when the deployed registry doesn't implement `tokenOfOwnerByIndex` (confirmed live on the BSC Testnet Identity Registry, 2026-07-08 — `balanceOf` still proves the address is registered even when the id itself can't be resolved). |++**Known limits:**+- This flow targets the ERC-8004 Identity Registry only, on **BSC Testnet (chainId 97)** by default; `network: "bscMainnet"` is supported by the relay but real MegaFuel sponsor policies are provisioned per environment by the operator.+- The mint seeds the token URI with the GLB/image URL only (matching the first transaction of the standard two-transaction flow above) — pointing it at the full agent card JSON still requires a follow-up `setAgentURI` call, which this gasless path does not perform automatically.+- MegaFuel sponsorship is a NodeReal-operated service with whitelisted policies — a decline is a normal, expected response, not an error; the self-pay fallback always completes the mint once the wallet holds a small amount of tBNB (well under $0.01 at BSC Testnet gas prices).++---+## The agent card formatThe document your `tokenURI` resolves to is an *agent card* — a JSON file pinned to IPFS. Here is a minimal example:diff --git a/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json b/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.jsonindex 22a04b8b2..9333b6894 100644--- a/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json+++ b/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json@@ -21,7 +21,6 @@"trellis","mcp"],- "category": "creative","mcpServers": {"3d-agent": {"command": "npx",diff --git a/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json b/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.jsonindex cc9bc9f1d..8a1ba0656 100644--- a/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json+++ b/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json@@ -26,6 +26,5 @@"mcp","tools","agent"- ],- "category": "developer-tools"+ ]}diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex 2501d7d7a..196a7471b 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -19,8 +19,8 @@ import { Room } from '@colyseus/core';import { Player, Block, Vehicle, Mob, Tombstone, WorldObject, WalkState } from '../schemas.js';import {- VEHICLE_SPAWNS, vehicleSpec, isVehicleType,- VEHICLE_WORLD_RADIUS_M, VEHICLE_ENTER_RANGE_M,+ VEHICLE_SPAWNS, vehicleSpec, isVehicleType, vehicleRestHeight,+ VEHICLE_WORLD_BOUND_M, VEHICLE_ENTER_RANGE_M,vehicleMaxStepM, vehicleMaxSpeedMps,} from '../vehicles.js';import { cleanAvatarUrl } from '../avatar-url.js';@@ -223,10 +223,6 @@ const KING_TICK_MS = 1000;const KING_POINTS_PER_SEC = 10;const KING_MIN_PLAYERS = 1;-// Legacy disc radius — still used as the fallback drop clamp when a driver steps-// out of a vehicle (vehicles carry their own VEHICLE_WORLD_RADIUS_M bound).-const WORLD_RADIUS_M = 60;-// Open-world district bounds (W01). The /play world is no longer the 60 m disc:// it's a square district the client renders streets/buildings across. These// mirror DISTRICT.half in src/game/world-zones.js — keep the two in sync so the@@ -1745,7 +1741,9 @@ export class WalkRoom extends Room {v.type = spawn.type;v.color = Number.isInteger(spawn.color) ? spawn.color : spec.color;v.x = spawn.x;- v.y = 0;+ // Rest the chassis on its suspension, not embedded in the asphalt — see+ // vehicleRestHeight's doc for the geometry this mirrors.+ v.y = vehicleRestHeight(spawn.type);v.z = spawn.z;// Resting heading → quaternion about the up axis.const half = (spawn.yaw || 0) / 2;@@ -1804,13 +1802,12 @@ export class WalkRoom extends Room {v.speed = 0;v.tsServer = Date.now();- // Drop the avatar just left of the car (chassis-left), clamped to the world.+ // Drop the avatar just left of the car (chassis-left), clamped to the same+ // square world bound as ordinary movement.const yaw = this._vehicleYaw(v);const off = (vehicleSpec(v.type).dims.w / 2) + 0.6;- let dx = v.x + Math.cos(yaw) * off;- let dz = v.z - Math.sin(yaw) * off;- const r = Math.hypot(dx, dz);- if (r > WORLD_RADIUS_M) { const k = WORLD_RADIUS_M / r; dx *= k; dz *= k; }+ const dx = Math.max(-WORLD_BOUND_M, Math.min(WORLD_BOUND_M, v.x + Math.cos(yaw) * off));+ const dz = Math.max(-WORLD_BOUND_M, Math.min(WORLD_BOUND_M, v.z - Math.sin(yaw) * off));player.x = dx;player.z = dz;player.y = 0;@@ -1859,15 +1856,11 @@ export class WalkRoom extends Room {const sp = typeof speed === 'number' && Number.isFinite(speed) ? speed : 0;if (Math.abs(sp) > vehicleMaxSpeedMps(v.type)) return false;- // World bounds — keep the car inside the visible arena (scale x/z together so- // a clamp doesn't change heading).- const r = Math.hypot(x, z);- if (r > VEHICLE_WORLD_RADIUS_M) {- const k = VEHICLE_WORLD_RADIUS_M / r;- v.x = x * k; v.z = z * k;- } else {- v.x = x; v.z = z;- }+ // World bounds — the same square district clamp ordinary movement uses, so a+ // car can reach the avenue spawns at x/z=±90 without being pulled toward the+ // centre by a stale circular radius.+ v.x = Math.max(-VEHICLE_WORLD_BOUND_M, Math.min(VEHICLE_WORLD_BOUND_M, x));+ v.z = Math.max(-VEHICLE_WORLD_BOUND_M, Math.min(VEHICLE_WORLD_BOUND_M, z));v.y = Math.max(-2, Math.min(8, y));// Normalize the quaternion defensively so a denormalized client value can't// poison every peer's renderer.diff --git a/multiplayer/src/vehicles.js b/multiplayer/src/vehicles.jsindex 603c25b96..11421d4f3 100644--- a/multiplayer/src/vehicles.js+++ b/multiplayer/src/vehicles.js@@ -101,6 +101,19 @@ export function vehicleSpec(type) {return VEHICLE_TYPES[type] || VEHICLE_TYPES.sedan;}+// The chassis-centre height a parked/resting vehicle sits at, derived from the+// same geometry `PhysicsWorld.createVehicle` uses for its wheel connection+// points (src/physics/physics-world.js): the connection sits `hy*0.2` below the+// chassis centre, the suspension extends `rest` further, and the wheel radius+// carries the rest of the way to the ground. Used to seed parked vehicles+// (so they don't spawn sunk into the asphalt) and to place the chassis when a+// driver takes the wheel.+export function vehicleRestHeight(type) {+ const spec = vehicleSpec(type);+ const hy = spec.dims.h / 2;+ return hy * 0.2 + spec.suspension.rest + spec.wheel.radius;+}+// The fleet every world spawns with. The avenue bays mirror W01's vehicle// spawn-points (src/game/world-zones.js SPAWN_POINTS, type:'vehicle') so cars// park on the open cross-avenues the district keeps clear of buildings; two@@ -120,9 +133,12 @@ export const VEHICLE_SPAWNS = [// --- Anti-cheat limits (server-enforced) -----------------------------------// World bounds must match WalkRoom's player clamp so a car can't be driven past-// the visible arena.-export const VEHICLE_WORLD_RADIUS_M = 60;+// World bounds must match WalkRoom's own square player clamp (WORLD_BOUND_M =+// world-zones.js WORLD_BOUND = DISTRICT.half - 2 = 198) so a car can't be+// driven past the visible arena — and, just as importantly, so the avenue+// vehicle spawns at x/z=±90 (VEHICLE_SPAWNS below) aren't clamped away by a+// stale, smaller radius the first time they sync.+export const VEHICLE_WORLD_BOUND_M = 198;// How close a player must stand to a parked vehicle to take the wheel.export const VEHICLE_ENTER_RANGE_M = 3.4;diff --git a/pages/bnb-latency.html b/pages/bnb-latency.htmlnew file mode 100644index 000000000..25d5cf9a4--- /dev/null+++ b/pages/bnb-latency.html@@ -0,0 +1,569 @@+<!doctype html>+<html lang="en">+ <head>+ <script>+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>BNB Chain live block race — 0.45s vs Base, Ethereum, Solana · three.ws</title>+ <meta+ name="description"+ content="A live, honest block race: BNB Chain's ~0.45s blocks measured right now against Base, Ethereum, and Solana off real public RPCs. No wallet, no payment, no hardcoded numbers — every figure is a fresh on-chain measurement."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/bnb-latency" />+ <meta property="og:title" content="BNB Chain live block race · three.ws" />+ <meta+ property="og:description"+ content="Watch BNB Chain confirm blocks in real time next to Base, Ethereum, and Solana — measured live off public RPCs, never a hardcoded '0.45s'."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=BNB+Chain+live+block+race&d=BNB+Chain%27s+~0.45s+blocks+measured+live+against+Base%2C+Ethereum%2C+and+Solana+off+real+public+RPCs.+No+wallet%2C+no+payment%2C+no+hardcoded+numbers.&p=%2Fbnb-latency"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="BNB Chain live block race · three.ws" />+ <meta+ name="twitter:description"+ content="Watch BNB Chain confirm blocks in real time next to Base, Ethereum, and Solana — measured live off public RPCs, never a hardcoded '0.45s'."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=BNB+Chain+live+block+race&d=BNB+Chain%27s+~0.45s+blocks+measured+live+against+Base%2C+Ethereum%2C+and+Solana+off+real+public+RPCs.+No+wallet%2C+no+payment%2C+no+hardcoded+numbers.&p=%2Fbnb-latency"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/bnb-latency" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="BNB Chain × three.ws — live block race" />++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "BNB Chain live block race",+ "description": "A live, honest race showing BNB Chain confirming blocks next to Base, Ethereum, and Solana — every number measured fresh off public RPCs, no hardcoded claims.",+ "url": "https://three.ws/bnb-latency",+ "isPartOf": { "@type": "WebSite", "name": "three.ws", "url": "https://three.ws" }+ }+ ]+ }+ </script>++ <style>+ :root {+ color-scheme: dark;+ }+ :root[data-theme='light'] {+ color-scheme: light;+ }+ .bnbl-wrap {+ max-width: 1180px;+ margin: 0 auto;+ padding: 0 24px;+ }+ @media (max-width: 600px) {+ .bnbl-wrap {+ padding: 0 16px;+ }+ }++ /* ── Hero ─────────────────────────────────────────────────────── */+ .bnbl-hero {+ padding: 76px 0 36px;+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ }+ .bnbl-eyebrow {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-size: 12px;+ font-weight: 600;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--gold, #f0b90b);+ margin: 0 0 16px;+ }+ .bnbl-eyebrow .dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: #f0b90b;+ }+ .bnbl-eyebrow a {+ color: inherit;+ text-decoration: underline;+ text-underline-offset: 2px;+ }+ .bnbl-hero h1 {+ font-family: var(--font-display, 'Space Grotesk', system-ui, sans-serif);+ font-size: clamp(30px, 4.6vw, 50px);+ font-weight: 700;+ letter-spacing: -0.03em;+ line-height: 1.08;+ margin: 0 0 18px;+ max-width: 20ch;+ }+ .bnbl-hero p.lede {+ font-size: 16px;+ line-height: 1.65;+ color: var(--ink-dim, #888);+ margin: 0;+ max-width: 66ch;+ }++ /* ── Headline number ──────────────────────────────────────────── */+ .bnbl-headline {+ padding: 36px 0;+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ }+ .bnbl-headline-card {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ justify-content: space-between;+ gap: 16px 28px;+ padding: 26px 28px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-card, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ }+ .bnbl-headline-num {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: clamp(36px, 7vw, 72px);+ font-weight: 700;+ line-height: 1;+ color: var(--ink, #e8e8e8);+ white-space: nowrap;+ max-width: 100%;+ }+ @media (max-width: 380px) {+ .bnbl-headline-num {+ white-space: normal;+ }+ }+ .bnbl-headline-num .unit {+ font-size: 0.32em;+ color: var(--ink-dim, #888);+ font-weight: 500;+ margin-left: 6px;+ }+ .bnbl-headline-sub {+ font-size: 13.5px;+ color: var(--ink-dim, #888);+ max-width: 46ch;+ line-height: 1.6;+ }+ #bnbl-updated {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ color: var(--ink-faint, rgba(255, 255, 255, 0.4));+ white-space: nowrap;+ }++ /* ── Page error (all lanes down) ─────────────────────────────── */+ .bnbl-page-error {+ margin: 36px 0 0;+ padding: 20px 24px;+ border: 1px solid rgba(251, 191, 36, 0.25);+ border-radius: var(--radius-card, 14px);+ background: rgba(251, 191, 36, 0.06);+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 14px;+ justify-content: space-between;+ }+ .bnbl-page-error p {+ margin: 0;+ font-size: 14px;+ color: var(--ink, #e8e8e8);+ max-width: 56ch;+ line-height: 1.6;+ }+ .bnbl-retry {+ padding: 8px 18px;+ border-radius: var(--radius-control, 10px);+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink, #e8e8e8);+ font-family: inherit;+ font-size: 13px;+ cursor: pointer;+ transition: background 0.14s;+ flex-shrink: 0;+ }+ .bnbl-retry:hover {+ background: rgba(255, 255, 255, 0.1);+ }+ .bnbl-retry:active {+ transform: translateY(1px);+ }+ .bnbl-retry:focus-visible {+ outline: 2px solid rgba(255, 255, 255, 0.4);+ outline-offset: 2px;+ }++ /* ── Race grid ────────────────────────────────────────────────── */+ .bnbl-race-section {+ padding: 44px 0 24px;+ }+ .bnbl-section-heading {+ font-family: var(--font-display, 'Space Grotesk', system-ui, sans-serif);+ font-size: 20px;+ font-weight: 700;+ letter-spacing: -0.01em;+ margin: 0 0 8px;+ }+ .bnbl-section-sub {+ font-size: 13.5px;+ color: var(--ink-dim, #888);+ margin: 0 0 28px;+ max-width: 68ch;+ line-height: 1.6;+ }+ .bnbl-grid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 16px;+ }+ @media (max-width: 1040px) {+ .bnbl-grid {+ grid-template-columns: repeat(2, 1fr);+ }+ }+ @media (max-width: 560px) {+ .bnbl-grid {+ grid-template-columns: 1fr;+ }+ }+ .bnbl-lane {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 20px 20px 18px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-card, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ transition: border-color 0.18s, box-shadow 0.18s;+ }+ .bnbl-lane[data-state='live'] {+ border-color: rgba(74, 222, 128, 0.22);+ }+ .bnbl-lane[data-state='reconnecting'] {+ border-color: rgba(251, 191, 36, 0.25);+ }+ .bnbl-lane.bnbl-tick {+ animation: bnbl-tick-flash 0.5s ease-out;+ }+ @media (prefers-reduced-motion: reduce) {+ .bnbl-lane.bnbl-tick {+ animation: none;+ }+ }+ @keyframes bnbl-tick-flash {+ 0% {+ box-shadow: 0 0 0 1px rgba(74, 222, 128, 0.45);+ }+ 100% {+ box-shadow: 0 0 0 1px transparent;+ }+ }+ .bnbl-lane-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ }+ .bnbl-lane-name {+ font-family: var(--font-display, 'Space Grotesk', system-ui, sans-serif);+ font-size: 15px;+ font-weight: 650;+ color: var(--ink, #e8e8e8);+ }+ .bnbl-lane-status {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 10.5px;+ font-weight: 500;+ padding: 3px 8px;+ border-radius: 999px;+ white-space: nowrap;+ flex-shrink: 0;+ }+ .bnbl-lane-status::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ flex-shrink: 0;+ }+ .bnbl-lane-status[data-state='live'] {+ background: rgba(74, 222, 128, 0.1);+ color: var(--success, #4ade80);+ border: 1px solid rgba(74, 222, 128, 0.2);+ }+ .bnbl-lane-status[data-state='live']::before {+ background: var(--success, #4ade80);+ }+ .bnbl-lane-status[data-state='reconnecting'] {+ background: rgba(251, 191, 36, 0.1);+ color: var(--warn, #fbbf24);+ border: 1px solid rgba(251, 191, 36, 0.2);+ animation: bnbl-pulse 1.8s ease-in-out infinite;+ }+ .bnbl-lane-status[data-state='reconnecting']::before {+ background: var(--warn, #fbbf24);+ }+ .bnbl-lane-status[data-state='measuring'] {+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink-dim, #888);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ animation: bnbl-pulse 1.8s ease-in-out infinite;+ }+ .bnbl-lane-status[data-state='measuring']::before {+ background: var(--ink-dim, #888);+ }+ @media (prefers-reduced-motion: reduce) {+ .bnbl-lane-status[data-state='reconnecting'],+ .bnbl-lane-status[data-state='measuring'] {+ animation: none;+ }+ }+ @keyframes bnbl-pulse {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.45;+ }+ }+ .bnbl-lane-kicker {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 10.5px;+ color: var(--ink-dim, #888);+ text-transform: uppercase;+ letter-spacing: 0.04em;+ margin: 0;+ }+ .bnbl-lane-num {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 30px;+ font-weight: 700;+ line-height: 1;+ color: var(--ink, #e8e8e8);+ min-height: 34px;+ display: flex;+ align-items: center;+ }+ .bnbl-lane-num .unit {+ font-size: 0.36em;+ color: var(--ink-dim, #888);+ font-weight: 500;+ margin-left: 5px;+ }+ .bnbl-lane-num-stale {+ opacity: 0.4;+ }+ .bnbl-spinner {+ width: 16px;+ height: 16px;+ border-radius: 50%;+ border: 2px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-top-color: var(--ink, #e8e8e8);+ animation: bnbl-spin 0.8s linear infinite;+ flex-shrink: 0;+ }+ @media (prefers-reduced-motion: reduce) {+ .bnbl-spinner {+ animation: none;+ border-top-color: var(--stroke-strong, rgba(255, 255, 255, 0.14));+ }+ }+ @keyframes bnbl-spin {+ to {+ transform: rotate(360deg);+ }+ }+ .bnbl-sparkline {+ display: flex;+ align-items: flex-end;+ gap: 2px;+ height: 32px;+ }+ .bnbl-bar {+ flex: 1 1 auto;+ min-width: 2px;+ background: var(--ink-faint, rgba(255, 255, 255, 0.22));+ border-radius: 1px;+ transition: height 0.3s ease-out;+ }+ @media (prefers-reduced-motion: reduce) {+ .bnbl-bar {+ transition: none;+ }+ }+ .bnbl-lane[data-state='live'] .bnbl-bar {+ background: rgba(74, 222, 128, 0.55);+ }+ .bnbl-sparkline-empty {+ font-size: 11px;+ color: var(--ink-faint, rgba(255, 255, 255, 0.3));+ }+ .bnbl-lane-meta {+ font-size: 11.5px;+ color: var(--ink-dim, #888);+ margin: 0;+ line-height: 1.5;+ }++ /* ── Honesty footer ───────────────────────────────────────────── */+ .bnbl-honesty {+ padding: 36px 0 80px;+ }+ .bnbl-honesty-card {+ padding: 22px 24px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-card, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ }+ .bnbl-honesty-card h3 {+ font-size: 14px;+ font-weight: 600;+ margin: 0 0 10px;+ }+ .bnbl-honesty-card ul {+ margin: 0;+ padding-left: 18px;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .bnbl-honesty-card li {+ font-size: 12.5px;+ line-height: 1.6;+ color: var(--ink-dim, #888);+ }+ .bnbl-honesty-card code {+ font-family: var(--font-mono, ui-monospace, monospace);+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ padding: 1px 5px;+ border-radius: 4px;+ font-size: 11.5px;+ }+ .bnbl-honesty-card a {+ color: var(--ink, #e8e8e8);+ }+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js" defer></script>++ <main id="main-content">+ <div class="bnbl-wrap">+ <!-- Hero -->+ <section class="bnbl-hero" aria-labelledby="bnbl-heading">+ <p class="bnbl-eyebrow">+ <span class="dot" aria-hidden="true"></span><a href="/bnb">BNB Chain × three.ws</a>+ </p>+ <h1 id="bnbl-heading">Watch BNB Chain confirm blocks in real time.</h1>+ <p class="lede">+ Four lanes, one honest race: BNB Chain, Base, Ethereum, and Solana, each measured live off a+ public RPC every few seconds — never a hardcoded "0.45s." A lane that goes quiet shows+ "reconnecting," not a frozen fake number, while the others keep racing.+ </p>+ </section>++ <!-- Headline BNB number -->+ <section class="bnbl-headline" aria-label="Live BNB Chain block-time headline">+ <div class="bnbl-headline-card">+ <div>+ <div class="bnbl-headline-num" id="bnbl-headline-num">+ <span class="bnbl-spinner" aria-hidden="true"></span>+ </div>+ <p class="bnbl-headline-sub" id="bnbl-headline-sub">+ Measuring live BNB Chain block time from a public RPC…+ </p>+ </div>+ <span id="bnbl-updated"></span>+ </div>+ <div class="bnbl-page-error" id="bnbl-page-error" role="alert" hidden>+ <p>+ Every chain's public RPC is unreachable right now — this is a real outage, not a bug.+ Retry, or check back shortly.+ </p>+ <button class="bnbl-retry" id="bnbl-retry" type="button">Retry</button>+ </div>+ </section>++ <!-- Race lanes -->+ <section class="bnbl-race-section" id="bnbl-race" aria-label="Live block-race lanes">+ <h2 class="bnbl-section-heading">The race, lane by lane</h2>+ <p class="bnbl-section-sub">+ Each card samples real blocks (or slots, for Solana) off a public RPC and reports the+ measured average interval — the sparkline is the last 24 live readings, tallest bar = fastest+ measurement.+ </p>+ <div class="bnbl-grid" id="bnbl-grid"></div>+ </section>++ <!-- Honesty / methodology -->+ <section class="bnbl-honesty" aria-label="How this race is measured">+ <div class="bnbl-honesty-card">+ <h3>How we keep this race honest</h3>+ <ul>+ <li>+ Every number comes from <code>/api/bnb/latency</code>, which samples real blocks (BNB+ via <code>probeBlockTime</code>, the same function backing the+ <a href="/bnb">/bnb hub</a>'s proof strip) off public RPCs on every poll — nothing is+ precomputed or hardcoded.+ </li>+ <li>+ We never claim BNB's roadmap targets — 20,000 TPS or BEP-670's 250ms finality — as+ shipped. This page only shows what it measured itself, right now.+ </li>+ <li>+ A chain's RPC going quiet shows "reconnecting" on that lane only; the rest of the race+ keeps running. All four down at once shows a designed error with a retry, never a+ blank page.+ </li>+ </ul>+ </div>+ </section>+ </div>+ </main>++ <div id="footer-container"></div>+ <script type="module" src="/src/bnb-latency.js"></script>+ <script src="/footer.js" defer></script>+ </body>+</html>diff --git a/pages/crypto-api.html b/pages/crypto-api.htmlnew file mode 100644index 000000000..53198d450--- /dev/null+++ b/pages/crypto-api.html@@ -0,0 +1,441 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){document.documentElement.classList.add('js');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, viewport-fit=cover" />+ <title>Crypto API — one free, keyless API for on-chain data · three.ws</title>+ <meta+ name="description"+ content="One free API for crypto data: DEX pairs, prices, quotes, TVL, on-chain reads, name resolution. No key, no wallet. Generous free tier, pay-per-call only above quota. Live registry, OpenAPI 3.1 spec included."+ />+ <meta name="robots" content="index, follow" />+ <link rel="canonical" href="https://three.ws/crypto-api" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Crypto API — one free, keyless API for on-chain data · three.ws" />+ <meta+ property="og:description"+ content="DEX pairs, prices, quotes, TVL, on-chain reads, name resolution — one free API, no key, no wallet. Pay-per-call only above the free quota."+ />+ <meta property="og:url" content="https://three.ws/crypto-api" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Crypto+API&d=One+free+API+for+crypto+data%3A+DEX+pairs%2C+prices%2C+quotes%2C+TVL%2C+on-chain+reads%2C+name+resolution.+No+key%2C+no+wallet.&p=%2Fcrypto-api" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Crypto API — one free, keyless API for on-chain data · three.ws" />+ <meta+ name="twitter:description"+ content="DEX pairs, prices, quotes, TVL, on-chain reads, name resolution — free, keyless, one fetch."+ />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Crypto+API&d=One+free+API+for+crypto+data%3A+DEX+pairs%2C+prices%2C+quotes%2C+TVL%2C+on-chain+reads%2C+name+resolution.+No+key%2C+no+wallet.&p=%2Fcrypto-api" />++ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <script defer src="/footer-newsletter.js"></script>++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@type": "WebAPI",+ "name": "three.ws Crypto API",+ "description": "Free, keyless aggregator API for crypto/DeFi/on-chain data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — bundled from CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC behind one bill.",+ "url": "https://three.ws/crypto-api",+ "documentation": "https://three.ws/openapi.json",+ "provider": { "@type": "Organization", "name": "three.ws", "url": "https://three.ws" },+ "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" }+ }+ </script>++ <style>+ /* ─────────────────────────────────────────────────────────────+ /crypto-api — Crypto API aggregator storefront. All values come+ from the design tokens in /tokens.css (loaded via /style.css).+ ───────────────────────────────────────────────────────────── */+ .ca-main { max-width: 1100px; margin: 0 auto; padding: 0 var(--space-lg) var(--space-2xl); width: 100%; }+ .ca-main :where(h2) {+ font: var(--weight-bold) var(--text-2xl) / var(--leading-tight) var(--font-display);+ color: var(--ink-bright); margin: 0 0 var(--space-xs); letter-spacing: -0.01em;+ }+ .ca-section { padding-block: var(--space-2xl); border-top: 1px solid var(--stroke); }+ .ca-section:first-of-type { border-top: 0; }+ .ca-section-lede { color: var(--ink-dim); max-width: 62ch; margin: 0 0 var(--space-lg); line-height: var(--leading-normal); }++ /* ── Hero ─────────────────────────────────────────────────── */+ .ca-hero { position: relative; text-align: center; padding: clamp(var(--space-2xl), 8vw, 6rem) var(--space-lg) var(--space-2xl); max-width: 1100px; margin: 0 auto; overflow: hidden; }+ .ca-hero::before {+ content: ""; position: absolute; inset: -40% 0 auto 0; height: 70%;+ background: radial-gradient(60% 100% at 50% 0%, var(--accent-soft), transparent 70%);+ pointer-events: none; z-index: -1;+ }+ .ca-hero .eyebrow { justify-content: center; display: inline-flex; align-items: center; gap: 0.5ch; margin-bottom: var(--space-md); }+ .ca-hero h1 { font: var(--weight-bold) clamp(2rem, 6vw, 3.4rem) / 1.05 var(--font-display); color: var(--ink-bright); letter-spacing: -0.02em; margin: 0 auto var(--space-md); max-width: 20ch; }+ .ca-hero h1 em { font-style: normal; color: var(--ink-dim); }+ .ca-hero-sub { color: var(--ink-dim); font-size: var(--text-lg); line-height: var(--leading-normal); max-width: 58ch; margin: 0 auto var(--space-lg); }+ .ca-hero-cta { display: flex; gap: var(--space-sm); justify-content: center; flex-wrap: wrap; }++ .ca-badges { display: flex; flex-wrap: wrap; gap: var(--space-2xs); justify-content: center; margin-top: var(--space-lg); }+ .ca-badge { display: inline-flex; align-items: center; gap: 0.5ch; font: var(--weight-medium) var(--text-xs) / 1 var(--font-mono); color: var(--ink-dim); background: var(--surface-1); border: 1px solid var(--stroke); padding: 0.5em 0.85em; border-radius: var(--radius-pill); }++ .ca-live-pill { display: inline-flex; align-items: center; gap: 0.55ch; font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.08em; padding: 0.5em 0.85em; border-radius: var(--radius-pill); background: var(--surface-2); border: 1px solid var(--stroke); color: var(--ink-dim); }+ .ca-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ink-faint); flex: none; }+ .ca-dot--live { background: var(--success); box-shadow: 0 0 0 0 var(--success); animation: ca-pulse 2s infinite; }+ .ca-dot--err { background: #f87171; }+ @keyframes ca-pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--success) 55%, transparent); } 70% { box-shadow: 0 0 0 6px transparent; } 100% { box-shadow: 0 0 0 0 transparent; } }+ @media (prefers-reduced-motion: reduce) { .ca-dot--live { animation: none; } }++ /* ── Code block ───────────────────────────────────────────── */+ .ca-code { position: relative; background: var(--bg-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg); overflow: hidden; }+ .ca-code pre { margin: 0; padding: var(--space-md) var(--space-md); overflow-x: auto; font: var(--weight-regular) var(--text-sm) / 1.6 var(--font-mono); color: var(--ink); tab-size: 2; }+ .ca-code code { font: inherit; color: inherit; background: none; white-space: pre; }+ .ca-copy { position: absolute; top: var(--space-2xs); right: var(--space-2xs); font: var(--weight-medium) var(--text-2xs) / 1 var(--font-mono); color: var(--ink-dim); background: var(--surface-2); border: 1px solid var(--stroke); padding: 0.5em 0.75em; border-radius: var(--radius-sm); cursor: pointer; display: inline-flex; align-items: center; gap: 0.5ch; transition: color var(--dur-fast, 120ms) ease, border-color var(--dur-fast, 120ms) ease; }+ .ca-copy:hover { color: var(--ink-bright); border-color: var(--stroke-strong); }+ .ca-copy:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .ca-copy.is-done { color: var(--success); border-color: color-mix(in srgb, var(--success) 40%, var(--stroke)); }+ .ca-tok { color: var(--ink-faint); } .ca-str { color: var(--success); } .ca-key { color: var(--accent); } .ca-num { color: var(--warn); } .ca-cmd { color: var(--ink-bright); font-weight: var(--weight-medium); }++ /* ── Table ────────────────────────────────────────────────── */+ .ca-toolbar { display: flex; align-items: center; gap: var(--space-sm); flex-wrap: wrap; margin-bottom: var(--space-md); }+ .ca-toolbar input[type=search] {+ flex: 1 1 260px; min-width: 200px; background: var(--surface-1); border: 1px solid var(--stroke-strong);+ color: var(--ink); padding: 0.6em 1em; font-size: var(--text-sm); border-radius: var(--radius-pill); outline: none;+ font-family: var(--font-body);+ }+ .ca-toolbar input[type=search]:focus-visible { border-color: var(--accent); outline: 2px solid var(--accent); outline-offset: 1px; }+ .ca-toolbar .ca-count { color: var(--ink-faint); font-size: var(--text-xs); font-family: var(--font-mono); margin-left: auto; }+ .ca-table-wrap { border: 1px solid var(--stroke); border-radius: var(--radius-lg); overflow-x: auto; background: var(--surface-1); }+ table.ca-table { width: 100%; border-collapse: collapse; min-width: 760px; font-size: var(--text-sm); }+ .ca-table th { text-align: left; font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-faint); padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--stroke); white-space: nowrap; }+ .ca-table td { padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--stroke); vertical-align: top; }+ .ca-table tr:last-child td { border-bottom: 0; }+ .ca-table tbody tr { transition: background var(--dur-fast, 120ms) ease; }+ .ca-table tbody tr:hover { background: var(--surface-2); }+ .ca-provider { font-weight: var(--weight-semibold); color: var(--ink-bright); }+ .ca-purpose { color: var(--ink-dim); }+ .ca-meth { display: inline-block; font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono); color: var(--ink); background: var(--surface-2); border: 1px solid var(--stroke); padding: 0.35em 0.55em; border-radius: var(--radius-sm); margin-right: 0.5ch; }+ .ca-path { font: var(--weight-regular) var(--text-xs) / 1.4 var(--font-mono); color: var(--ink-dim); word-break: break-all; }+ .ca-free { color: var(--success); font-weight: var(--weight-semibold); font-family: var(--font-mono); font-size: var(--text-xs); white-space: nowrap; }+ .ca-price { font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim); white-space: nowrap; }++ /* ── States ───────────────────────────────────────────────── */+ .ca-empty, .ca-err { padding: 3.5rem 1.25rem; text-align: center; color: var(--ink-dim); border: 1px dashed var(--stroke-strong); border-radius: var(--radius-lg); }+ .ca-err { color: #fecaca; border-color: rgba(248,113,113,0.35); border-style: solid; background: rgba(248,113,113,0.05); }+ .ca-err .ca-err-title { font-weight: var(--weight-semibold); margin-bottom: var(--space-2xs); color: #fecaca; font-family: var(--font-display); font-size: var(--text-lg); }+ .ca-err .ca-retry {+ margin-top: var(--space-md); background: var(--accent); color: var(--bg-0, #0b0b0b); border: none;+ padding: 0.6em 1.3em; font-size: var(--text-sm); border-radius: var(--radius-md); cursor: pointer; font-weight: var(--weight-semibold);+ }+ .ca-err .ca-retry:hover { filter: brightness(1.1); }+ .ca-err .ca-retry:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }++ .ca-skel-row td { padding: var(--space-sm) var(--space-md); }+ .ca-skel { background: linear-gradient(90deg, var(--surface-1) 25%, var(--surface-2) 50%, var(--surface-1) 75%); background-size: 200% 100%; animation: ca-shimmer 1.4s ease-in-out infinite; border-radius: var(--radius-sm); height: 0.9em; }+ @keyframes ca-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .ca-skel { animation: none; } }++ /* ── CTA cards ────────────────────────────────────────────── */+ .ca-cta-grid { display: grid; gap: var(--space-md); grid-template-columns: repeat(3, 1fr); }+ @media (max-width: 860px) { .ca-cta-grid { grid-template-columns: 1fr; } }+ .ca-cta-card { display: flex; flex-direction: column; gap: var(--space-2xs); background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg); padding: var(--space-lg); text-decoration: none; color: inherit; transition: transform var(--dur-fast, 120ms) ease, border-color var(--dur-fast, 120ms) ease, background var(--dur-fast, 120ms) ease; }+ .ca-cta-card:hover { transform: translateY(-2px); border-color: var(--stroke-strong); background: var(--surface-2); }+ .ca-cta-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .ca-cta-tag { font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.08em; color: var(--accent); }+ .ca-cta-card h3 { font: var(--weight-bold) var(--text-lg)/1.2 var(--font-display); color: var(--ink-bright); margin: 0.15rem 0; }+ .ca-cta-card p { color: var(--ink-dim); font-size: var(--text-sm); line-height: var(--leading-normal); margin: 0; }+ .ca-cta-card .ca-cta-go { margin-top: auto; padding-top: var(--space-sm); color: var(--ink-bright); font: var(--weight-medium) var(--text-sm)/1 var(--font-body); display: inline-flex; align-items: center; gap: 0.4ch; }+ .ca-anchor { color: inherit; text-decoration: none; border-bottom: 1px solid var(--stroke-strong); }+ .ca-anchor:hover { color: var(--ink-bright); border-color: var(--ink-dim); }+ </style>++ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Crypto API — three.ws" />+ <meta name="twitter:site" content="@trythreews" />+ </head>+ <body>+ <a href="#ca-endpoints" class="h-skip-link">Skip to endpoints</a>++ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content">+ <!-- ── HERO ────────────────────────────────────────────────── -->+ <section class="ca-hero">+ <div class="eyebrow"><span class="ca-dot ca-dot--live"></span><span>Crypto API · Free forever</span></div>+ <h1>One free API for crypto data — <em>agents, not applications</em></h1>+ <p class="ca-hero-sub">+ DEX pairs, prices, swap quotes, TVL, on-chain reads, name resolution — one bill for+ CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC. No key, no wallet. A generous+ free tier, pay-per-call in USDC only above quota.+ </p>+ <div class="ca-hero-cta">+ <a class="btn btn--primary btn--lg" href="#ca-quickstart">Copy the quickstart</a>+ <a class="btn btn--secondary btn--lg" href="#ca-endpoints">Browse the live catalog</a>+ </div>+ <div class="ca-badges">+ <span class="ca-badge">Free tier — no key</span>+ <span class="ca-badge">BYOK pass-through</span>+ <span class="ca-badge">x402 pay-per-call</span>+ <span class="ca-badge">CoinGecko · DefiLlama · Jupiter · DexScreener · Solana RPC</span>+ <span class="ca-live-pill" id="ca-live-count"><span class="ca-dot"></span><span id="ca-live-count-text">Loading live registry…</span></span>+ </div>+ </section>++ <div class="ca-main">+ <!-- ── QUICKSTART ─────────────────────────────────────── -->+ <section class="ca-section" id="ca-quickstart">+ <div class="eyebrow">Quickstart</div>+ <h2>One call, real data back</h2>+ <p class="ca-section-lede">+ Every endpoint is a plain HTTP call under <code>/api/v1/x/<provider>/<endpoint></code>.+ No auth header, no SDK, no signup — the free tier serves real JSON immediately. Here's+ a live SOL price from CoinGecko.+ </p>+ <div class="ca-code" id="ca-quickstart-code"><!-- filled by JS --></div>+ <p class="ca-try-note" style="margin-top:var(--space-sm); color:var(--ink-faint); font-size:var(--text-xs)">+ Base URL: <code>https://three.ws/api/v1/x</code> · discovery index:+ <a class="ca-anchor" href="/api/v1/x" target="_blank" rel="noopener"><code>GET /api/v1/x</code></a> ·+ machine spec: <a class="ca-anchor" href="/openapi.json" target="_blank" rel="noopener"><code>openapi.json</code></a>+ </p>+ </section>++ <!-- ── LIVE ENDPOINT TABLE ────────────────────────────── -->+ <section class="ca-section" id="ca-endpoints">+ <div class="eyebrow">Live registry</div>+ <h2>Every endpoint, rendered from production</h2>+ <p class="ca-section-lede">+ This table is not hand-written — it's fetched from <code>GET /api/v1/x</code> at page+ load, so it always matches exactly what's deployed. New providers appear here the+ moment they ship, with zero edits to this page.+ </p>+ <div class="ca-toolbar">+ <input type="search" id="ca-search" placeholder="Filter by provider, endpoint, or summary…" aria-label="Filter endpoints" />+ <span class="ca-count" id="ca-count"></span>+ </div>+ <div id="ca-table-host"><!-- filled by JS: skeleton → table / error / empty --></div>+ </section>++ <!-- ── CTA ────────────────────────────────────────────── -->+ <section class="ca-section" id="ca-build">+ <div class="eyebrow">Reference</div>+ <h2>Read the docs, or pay for scale</h2>+ <p class="ca-section-lede">+ The free tier is real production data with zero setup. When your agent needs more —+ its own upstream key, a three.ws plan, or scripted pay-per-call — the same URLs+ upgrade in place.+ </p>+ <div class="ca-cta-grid">+ <a class="ca-cta-card" href="/docs">+ <span class="ca-cta-tag">Docs</span>+ <h3>Full API reference</h3>+ <p>Every provider, every billing lane, and the free-tier quota table in one page.</p>+ <span class="ca-cta-go">Read the docs →</span>+ </a>+ <a class="ca-cta-card" href="/openapi.json" target="_blank" rel="noopener">+ <span class="ca-cta-tag">OpenAPI 3.1</span>+ <h3>Machine-readable spec</h3>+ <p>Generated live from the same registry as this page — feed it to any codegen or agent tool.</p>+ <span class="ca-cta-go">Open openapi.json →</span>+ </a>+ <a class="ca-cta-card" href="/docs/x402">+ <span class="ca-cta-tag">x402</span>+ <h3>Pay-per-call, programmatically</h3>+ <p>How the HTTP 402 challenge works, and how an agent settles USDC to keep calling past the free tier.</p>+ <span class="ca-cta-go">Read the x402 docs →</span>+ </a>+ </div>+ </section>+ </div>+ </main>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>++ <script type="module">+ /* ── /crypto-api: the live table, quickstart, and status pill all+ render from GET /api/v1/x — the real production registry. Nothing+ here is hand-enumerated; a new provider/endpoint shows up with+ zero edits to this file. ─────────────────────────────────────── */+ const REGISTRY_URL = '/api/v1/x';+ const QUICKSTART_URL = '/api/v1/x/coingecko/price?ids=solana';++ const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c]));+ const el = (tag, cls, html) => { const n = document.createElement(tag); if (cls) n.className = cls; if (html != null) n.innerHTML = html; return n; };++ function formatUsd(atomics) {+ const n = Number(atomics) / 1e6;+ if (!Number.isFinite(n)) return '$0.00';+ let s = n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');+ const dec = s.includes('.') ? s.split('.')[1] : '';+ if (!s.includes('.')) s += '.00';+ else if (dec.length < 2) s += '0'.repeat(2 - dec.length);+ return `$${s}`;+ }++ function copyIcon() {+ return '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';+ }++ function codeBlock(innerHtml) {+ const wrap = el('div', 'ca-code');+ const btn = el('button', 'ca-copy', copyIcon() + '<span>Copy</span>');+ btn.type = 'button';+ const pre = el('pre'); const code = el('code'); code.innerHTML = innerHtml; pre.appendChild(code);+ wrap.append(btn, pre);+ btn.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(code.textContent);+ btn.classList.add('is-done'); btn.querySelector('span').textContent = 'Copied';+ setTimeout(() => { btn.classList.remove('is-done'); btn.querySelector('span').textContent = 'Copy'; }, 1600);+ } catch { btn.querySelector('span').textContent = 'Press ⌘C'; }+ });+ return wrap;+ }++ /* ── Quickstart code block ────────────────────────────────── */+ function renderQuickstart() {+ const html =+ `<span class="ca-cmd">curl</span> <span class="ca-str">"https://three.ws${esc(QUICKSTART_URL)}"</span>`;+ const host = document.getElementById('ca-quickstart-code');+ host.replaceChildren(codeBlock(html));+ }+ renderQuickstart();++ /* ── Live registry: skeleton → table / error / empty ─────── */+ const tableHost = document.getElementById('ca-table-host');+ const searchInput = document.getElementById('ca-search');+ const countEl = document.getElementById('ca-count');+ const livePill = document.getElementById('ca-live-count');+ const liveText = document.getElementById('ca-live-count-text');+ let ROWS = [];++ function skeletonRows(n = 8) {+ const wrap = el('div', 'ca-table-wrap');+ const table = el('table', 'ca-table');+ table.innerHTML = '<thead><tr><th>Provider</th><th>Endpoint</th><th>Method & path</th><th>Free tier</th><th>x402 price</th></tr></thead>';+ const tbody = el('tbody');+ for (let i = 0; i < n; i++) {+ const tr = el('tr', 'ca-skel-row');+ for (let c = 0; c < 5; c++) {+ const td = el('td');+ td.appendChild(el('div', 'ca-skel'));+ tr.appendChild(td);+ }+ tbody.appendChild(tr);+ }+ table.appendChild(tbody);+ wrap.appendChild(table);+ return wrap;+ }++ function renderTable(rows) {+ const wrap = el('div', 'ca-table-wrap');+ const table = el('table', 'ca-table');+ table.innerHTML = '<thead><tr><th>Provider</th><th>Endpoint</th><th>Method & path</th><th>Free tier</th><th>x402 price</th></tr></thead>';+ const tbody = el('tbody');+ if (rows.length === 0) {+ tableHost.replaceChildren(emptyState());+ countEl.textContent = '';+ return;+ }+ for (const r of rows) {+ const tr = el('tr');+ tr.innerHTML =+ `<td class="ca-provider">${esc(r.providerName)}</td>` ++ `<td class="ca-purpose">${esc(r.summary)}</td>` ++ `<td><span class="ca-meth">${esc(r.method)}</span><span class="ca-path">${esc(r.path)}</span></td>` ++ `<td class="ca-free">${r.free ? `${r.free.perMin}/min · ${r.free.perDay}/day` : '—'}</td>` ++ `<td class="ca-price">${esc(formatUsd(r.price_usdc_atomics))} / call</td>`;+ tbody.appendChild(tr);+ }+ table.appendChild(tbody);+ wrap.appendChild(table);+ tableHost.replaceChildren(wrap);+ countEl.textContent = `${rows.length} endpoint${rows.length === 1 ? '' : 's'}`;+ }++ function emptyState() {+ const wrap = el('div', 'ca-empty');+ wrap.innerHTML = '<div style="font-size:1.5rem;margin-bottom:.5rem">🗂️</div><div><b>No endpoints match.</b> Clear the filter to see the full live registry, or check <a class="ca-anchor" href="/docs">the docs</a>.</div>';+ return wrap;+ }++ function errorState(err) {+ const wrap = el('div', 'ca-err');+ wrap.innerHTML =+ `<div class="ca-err-title">Couldn't load the live registry</div>` ++ `<div>${esc(err?.message || 'Network error')} — the catalog is served from <code>GET /api/v1/x</code>. Retry, or hit it directly.</div>`;+ const retry = el('button', 'ca-retry', 'Retry');+ retry.type = 'button';+ retry.addEventListener('click', loadRegistry);+ wrap.appendChild(retry);+ return wrap;+ }++ function applyFilter() {+ const q = searchInput.value.trim().toLowerCase();+ const filtered = q+ ? ROWS.filter((r) =>+ r.providerName.toLowerCase().includes(q) ||+ r.summary.toLowerCase().includes(q) ||+ r.path.toLowerCase().includes(q),+ )+ : ROWS;+ renderTable(filtered);+ }+ searchInput.addEventListener('input', applyFilter);++ async function loadRegistry() {+ tableHost.replaceChildren(skeletonRows());+ countEl.textContent = '';+ liveText.textContent = 'Loading live registry…';+ try {+ const res = await fetch(REGISTRY_URL, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const body = await res.json();+ const providers = body?.data?.providers;+ if (!Array.isArray(providers)) throw new Error('malformed registry response');++ ROWS = [];+ for (const p of providers) {+ for (const e of p.endpoints || []) {+ ROWS.push({+ providerName: p.name,+ summary: e.summary || '',+ method: e.method,+ path: e.path,+ free: e.free || null,+ price_usdc_atomics: e.price_usdc_atomics,+ });+ }+ }++ applyFilter();++ const dot = livePill.querySelector('.ca-dot');+ if (ROWS.length > 0) {+ dot.classList.remove('ca-dot--err'); dot.classList.add('ca-dot--live');+ liveText.textContent = `${ROWS.length} endpoint${ROWS.length === 1 ? '' : 's'} live across ${providers.length} provider${providers.length === 1 ? '' : 's'}`;+ } else {+ dot.classList.remove('ca-dot--live');+ liveText.textContent = 'Registry is live but empty right now';+ }+ } catch (err) {+ tableHost.replaceChildren(errorState(err));+ countEl.textContent = '';+ const dot = livePill.querySelector('.ca-dot');+ dot.classList.remove('ca-dot--live'); dot.classList.add('ca-dot--err');+ liveText.textContent = 'Live registry unreachable — retry below';+ }+ }+ loadRegistry();+ </script>+ </body>+</html>diff --git a/prompts/bnb-chain/PROGRESS.md b/prompts/bnb-chain/PROGRESS.mdindex 98d91ea87..ff96a74d5 100644--- a/prompts/bnb-chain/PROGRESS.md+++ b/prompts/bnb-chain/PROGRESS.md@@ -395,3 +395,219 @@ not_found + SP-failover + all-SPs-down, and XML/JSON list parsing.which is prompt 09's funded upload (same tBNB-faucet blocker noted in prompts 01/02).**Status: DONE (code + tests, live-wire proven).** Upload (09) + unlock (11) can import it.++---++## 2026-07-08 — Prompt 10: GreenfieldVault.sol (pay → PermissionHub grant) — SHIPPED, deploy BLOCKED++**Outcome: `contracts/src/GreenfieldVault.sol` + real interface stubs + full Foundry+test suite done and compiling/passing. Live BSC testnet deploy is blocked on a funded+deployer key (same as items 13/18) — everything else is deploy-ready.**++- **Real interfaces, not invented ones.** `contracts/src/greenfield/{IPermissionHub,+ ICrossChain,IGnfdAccessControl,IApplication}.sol` reproduce the exact ABIs from+ `bnb-chain/greenfield-contracts` (`contracts/interface/*.sol` ++ `middle-layer/resource-mirror/storage/{PermissionStorage,CmnStorage}.sol` ++ `storage/PackageQueue.sol`), fetched and verified against `master` on 2026-07-08 —+ every function signature, the `ExtraData`/`FailureHandleStrategy` types, and every+ address are sourced, not guessed. Kept as minimal self-contained interfaces (not the+ full upgradeable implementation tree) so this workspace doesn't need to add+ `@openzeppelin/contracts-upgradeable` as a new dependency.+- **Real addresses, cross-checked two ways.** Mainnet CrossChain/ObjectHub from+ `00-CONTEXT.md`'s bytecode-verified list; PermissionHub mainnet + all four testnet+ hub addresses read live from `bnb-chain/greenfield-contracts`' README "Contract+ Entrypoint" tables (testnet PermissionHub `0x25E1eeDb5CaBf288210B132321FBB2d90b4174ad`,+ CrossChain `0xa5B2c9194131A4E0BFaCbF9E5D6722c873159cb7`, ObjectHub+ `0x1b059D8481dEe299713F18601fB539D066553e39`) — full table in `DEPLOYMENTS.md`.+- **`list`/`buy`/`revoke` exactly as specced, plus what "the vault must control its+ permissions" actually means on-chain:** `list()` requires the seller to have already+ called the real `IGnfdAccessControl.grantRole(ROLE_CREATE, vaultAddress, expiry)` on+ ObjectHub — checked live via `hasRole`, not merely asserted. `buy()` takes an+ off-chain-built GNFD permission payload (`policyData`, opaque bytes — no EVM contract+ encodes GNFD protobuf on-chain, real PermissionHub doesn't either), validates+ `price + live crossChain.getRelayFees()` atomically (no half-execution on+ underpayment or an uncovered relay fee), forwards the real relay fee to+ `PermissionHub.createPolicy`, and emits `Purchased`. Because `createPolicy` is+ genuinely asynchronous (00-CONTEXT: "poll for effect, never assume same-block"), the+ vault implements `IApplication.greenfieldCall` to receive the real minted policy id+ when Greenfield's ack settles, emitting `PolicyGranted`/`PolicyGrantFailed` — the+ "surface pending honestly" pattern the rest of this campaign uses, not a fabricated+ synchronous policyId. `revoke()` is seller-gated, calls the real+ `PermissionHub.deletePolicy`, documented as permanent-grants-by-default with an+ explicit escape hatch (spec left this a documented choice). Multiple buyers can each+ hold an independent grant on the same object (content-access marketplace, not+ ownership transfer); double-buy by the same buyer is idempotent-by-design+ (`AlreadyPurchased`, cleared on revoke/failed-settlement so a retry/resell works).+ Pull-payment `withdraw()` for seller proceeds; `nonReentrant` on every state-changing+ external-payment path.+- **Tests:** `contracts/test/GreenfieldVault.t.sol` (34 tests) ++ `contracts/test/mocks/{MockGreenfield.sol,Reentrant.sol}` — mocked+ PermissionHub/CrossChain/IGnfdAccessControl faithful to the real two-phase syn/ack+ flow (a `settleCreatePolicy(policyId, status)` harness call plays the Greenfield+ relayer). Covers: list requires role grant, only-seller list/delist, relist repricing,+ listed-by-another-seller, buy happy path + settlement, unlisted/empty-data/underpayment/+ missing-relay-fee reverts (atomic, no partial state), excess-payment refund, double-buy+ reverts and clears on failed-settlement/revoke, `greenfieldCall` access control (only+ PermissionHub, only the real channel id, unknown-sale guard), full revoke lifecycle+ (only sale's seller, requires `Granted` status, insufficient-fee revert, excess-fee+ refund), withdraw pull-payment, `quoteRelayFee` view, and two dedicated+ cross-function re-entrancy proofs (a `buy()` refund trying to re-enter `buy()` on a+ separate valid listing; a `withdraw()` payout trying to re-enter `withdraw()`) —+ both assert the nested low-level call fails with OpenZeppelin's+ `ReentrancyGuardReentrantCall` specifically, not just "nothing happened to steal".+- **`contracts/script/DeployGreenfieldVault.s.sol`** — selects real hub addresses by+ `block.chainid` (56/97), env-overridable. Dry-run proof below.++**Real build/test proof:**+```+$ forge build+Compiler run successful!++$ forge test --match-path test/GreenfieldVault.t.sol+Ran 34 tests for test/GreenfieldVault.t.sol:GreenfieldVaultTest+Suite result: ok. 34 passed; 0 failed; 0 skipped++$ forge test # full contracts/ workspace, nothing else touched+Ran 6 test suites: 94 tests passed, 0 failed, 0 skipped+```++**Deploy: BLOCKED on a funded deployer key (owner-only, same as items 13/18).**+`forge script script/DeployGreenfieldVault.s.sol:DeployGreenfieldVault --rpc-url+https://data-seed-prebsc-1-s1.bnbchain.org:8545 -vvvv` (no `--broadcast`) simulated+successfully end-to-end against the LIVE BSC testnet RPC: constructor executes with the+real testnet PermissionHub/CrossChain/ObjectHub addresses baked in, ~1.16M gas estimated+at 0.1 gwei ≈ 0.000170 BNB. Checked (presence only, no secret values read):+`DEPLOYER_PK`/`BNB_TESTNET_DEPLOYER_KEY` absent from shell env, no root `.env`, no+`contracts/.env`, `cast wallet list` empty. Full dry-run trace + constructor args+recorded in `DEPLOYMENTS.md`'s new GreenfieldVault section.++**Other changes:** added `BSC_TESTNET_RPC_URL`/`BSCSCAN_API_KEY` to+`contracts/.env.example` and `bsc_testnet`/`bsc` entries to `contracts/foundry.toml`+`[rpc_endpoints]`/`[etherscan]` (additive only — did not touch `AgentPayments.sol`,+the ERC-8004 registries, or `api/_lib/bnb/`, per this prompt's file boundaries).++**Gap for prompt 11 (unlock API) / 13 (e2e proof):** the real end-to-end proof (a real+`buy()` tx, a real `createPolicy` ack settling, a real `PolicyGranted` with a real+Greenfield policy id, cross-checked on GreenfieldScan) needs both this contract deployed+AND a real uploaded+listed object (prompt 09, same funding blocker) — same single root+cause blocking 07/08/09/13/14/18 in this campaign.++**Status: DONE (code + tests). Deploy BLOCKED on funded deployer key — owner action+needed.**++---++## 2026-07-08 — Prompt 03: Gas-free ERC-8004 agent registration on BSC — SHIPPED, verified live end-to-end with real mints++**Outcome: `api/_lib/bnb/erc8004-gasless.js`, `api/bnb/register-agent.js`,+`src/erc8004/gasless-register.js`, and the `/deploy` wizard's new gasless panel are done+and proven with REAL BSC testnet mints — not simulations.** Prereqs 01/02 confirmed+committed (`92bab1faf`, `c61c96452`) and imported as-is; `megafuel.js` gained one small+additive export (`submitRawTx`, a low-level "relay bytes I was handed" primitive — see+below for why `sendGasless()` didn't fit this prompt's signing model).++**Architecture decision — why this ISN'T `sendGasless()`:** the spec's phrasing ("server+relays via `sendGasless`") assumes a server-held signer. That's right for prompt 02's+demo/ops account, but wrong here: this endpoint must never see a private key. Real+design: the CLIENT (browser wallet or, for the true "zero-balance wallet" demo, an+in-page ephemeral viem account whose key lives in `sessionStorage` only) signs a+*legacy* `register(agentURI)` transaction entirely itself — with `gasPrice: 0` for a+gasless attempt, or a real `gasPrice` for a self-pay attempt — and POSTs only the raw+signed bytes. The server (`relayGaslessRegistration`) parses them (`viem.parseTransaction`++ `recoverTransactionAddress`), validates the target is the real Identity Registry, and+either relays the EXACT bytes to MegaFuel's `eth_sendRawTransaction` (gasless branch) or+broadcasts them as-is via the public RPC (self-pay branch) — it never constructs or signs+anything. A `gasPrice: 0` tx that MegaFuel declines is mechanically unbroadcastable on any+normal node (guaranteed underpriced-tx rejection outside the paymaster path), so a decline+returns `{ mode: 'declined', reason, hint }` instead of attempting a doomed send — the+caller re-signs with a real gasPrice and POSTs again to self-pay.++**Two real bugs found and fixed by live testing (would have shipped broken from mocks alone):**+1. **Already-registered guard crashed on the real contract.** The live BSC Testnet+ Identity Registry (`0x8004A818BFB912233c491871b3d84c89A494BD9e`) declares+ `tokenOfOwnerByIndex` in its ABI but **reverts** on every call to it (no+ ERC721Enumerable storage wired) — confirmed live 2026-07-08. The original guard did+ `.catch(() => null)` around the whole already-registered check, which silently treated+ a revert as "not registered" and would have let an already-registered address slip+ into a duplicate mint attempt. Fixed: `balanceOf` alone (which works) now+ short-circuits registration; `tokenOfOwnerByIndex` is best-effort enrichment only —+ `agentId: null` with `alreadyRegistered: true` when it can't be resolved, never a+ silent false negative.+2. **agentId decoded from the wrong topic when both `Transfer` and `Registered` logs are+ present.** Every real mint emits BOTH events in the same receipt, with `Transfer`+ logged first. `Transfer(from, to, tokenId)` puts `tokenId` at `topics[3]`, not+ `topics[1]` (that's `from`, which is `0x0` on a mint) — a naive "first+ Registered-or-Transfer match, read `topics[1]`" decoder silently returned `"0"` as the+ agentId on every real registration. Live testing caught it immediately (a real mint+ returning agentId `"0"` was an obvious tell). Fixed: `Registered`'s `topics[1]` is+ preferred when present; `Transfer` fallback now correctly reads `topics[3]`. Regression+ tests added for both bugs (`tests/bnb-erc8004-gasless.test.js`).++**Tests:** `tests/bnb-erc8004-gasless.test.js` (17 cases) — real legacy-tx signing ++parsing with synthetic per-test viem accounts (never a real key), injected+publicClient/megafuelOpts mocks for sponsored/self-pay/declined/pending/reverted paths,+both regression tests above, input validation (malformed tx, wrong target, non-legacy+type). `tests/bnb-register-agent.test.js` (10 cases) — HTTP boundary only (validation,+status/body shaping, rate limiting via new `limits.bnbRegisterIp`, method/CORS), mirrors+`tests/bnb-babt-check-endpoint.test.js`'s mock-the-lib pattern. `npx vitest run+tests/bnb-erc8004-gasless.test.js tests/bnb-register-agent.test.js tests/bnb-megafuel.test.js`+→ 36/36 passed.++**REAL testnet proof — four independent layers, zero mocks, all cross-verified against+three public RPCs (`data-seed-prebsc-1-s1.bnbchain.org`, `bsc-testnet.drpc.org`,+`bsc-testnet-rpc.publicnode.com`):**++1. **Library-direct** (`relayGaslessRegistration()` called with zero overrides — real+ `getPublicClient('bscTestnet')`, real MegaFuel fetch): fresh account+ `0xfb35130d94D80437eb3350c71e2c62898e9c57E3`, balance **0 wei both before and after**.+ ```json+ {"mode":"sponsored","agentId":"1593",+ "hash":"0x29b2999e1543d7e6d4eba21b41b33718d8e0196e18c1510d39e4cffcfe52bc95",+ "blockNumber":117842997,+ "sponsor":{"sponsorable":true,"sponsorName":"Yolin","sponsorIcon":"Yolin"}}+ ```+ Receipt independently fetched: `status:0x1, effectiveGasPrice:0x0` — genuinely free.+ Same account re-registered a second time → `{"alreadyRegistered":true,"agentId":null}`,+ no second broadcast (proves bug-fix #1 above against real state).+2. **HTTP-layer** (`curl` → real `server/index.mjs` on a local port, the actual+ production Express routing/CORS/rate-limit/JSON-parse stack, not a reimplementation):+ fresh account `0x693E0892C9970055e599fB286FA9116039bCbE00` → `{"mode":"sponsored",+ "agentId":"1594","hash":"0xa51be73cc33f9336e5527fc500cbb651228013f491fe071b336d849dc1be6687"}`,+ independently confirmed `status:0x1, effectiveGasPrice:0x0` on-chain.+3. **Real browser UI** (Playwright driving the actual `/deploy` page: select BSC Testnet,+ fill the wizard, click **⚡ Register gasless (0 tBNB wallet)**): ephemeral wallet+ `0xC101347Ef63059F346026eA338c1dd48C58937BB` generated client-side, log output "Relayed+ via MegaFuel — mode: sponsored. Tx: 0x9d5ba2b1... Confirmed. Agent ID: 1595."+ Independently confirmed on-chain: `status:0x1, effectiveGasPrice:0x0,+ from:0xc101347ef63059f346026ea338c1dd48c58937bb`.+4. **Self-pay branch** (public testnet faucet still reCAPTCHA-gated — same blocker prompt+ 02 documented — so funded via `anvil --chain-id 97 --fork-url+ https://bsc-testnet.drpc.org` + `anvil_setBalance`, same pattern prompt 02 used,+ `relayGaslessRegistration()` run unmodified against the fork): funded 0.1 tBNB, minted+ agentId `"1594"` (fork-local counter), real gas charged+ (`0.1 → 0.099867272 tBNB`), confirming the self-pay branch's decode/broadcast path is+ correct too (this is where bug #2 was originally caught, before being confirmed live).++**MegaFuel sponsor-policy finding — the prompt-02 gap is narrower than recorded:** prompt+02's PROGRESS entry noted "no NodeReal sponsor policy exists for our sender (or any+unregistered sender)" as of 2026-07-08 T00:xx. Re-probed the same live+`pm_isSponsorable` endpoint a few hours later in this session and got+`{"sponsorable":true,"sponsorName":"Yolin","sponsorIcon":"Yolin"}` for multiple freshly+generated, never-before-seen addresses — MegaFuel's BSC testnet policy currently sponsors+arbitrary senders by default (a testnet-only "Yolin" default policy, not one we+provisioned). This is exactly what makes the zero-balance-wallet demo work live right+now; it's a MegaFuel-operator decision that could change without notice (per 00-CONTEXT's+"sponsor policies are whitelisted" caveat), so the self-pay fallback documented above+remains load-bearing, not decorative.++**Docs/changelog:** `docs/erc8004.md` — new "Gasless agent registration on BNB" section+(architecture, curl example with a real captured response, response-shape table, known+limits) linked implicitly via the existing `## Registering an agent` flow.+`data/changelog.json` — holder-readable entry (`feature`, `sdk` tags) linking `/deploy`.++**Status: DONE.** No blockers — the flow works end-to-end today, live, for a genuinely+zero-balance wallet. Only soft gap: this mints with a seed URI (GLB/image URL) only, same+as the standard flow's first transaction; pointing the token at the full agent-card JSON+still needs a follow-up `setAgentURI` call this gasless path doesn't perform (documented+in docs/erc8004.md "Known limits" — an explicit scope cut, not an oversight, to keep the+relay to one signed transaction). Ready for prompt 04 (mpp-server-adapter) to build on.diff --git a/prompts/roadmap/_generated/04/gate-before.txt b/prompts/roadmap/_generated/04/gate-before.txtindex b568cb661..9cff7fa72 100644--- a/prompts/roadmap/_generated/04/gate-before.txt+++ b/prompts/roadmap/_generated/04/gate-before.txt@@ -1,59 +1,97 @@-=== typecheck ===-> [email protected] typecheck-> tsc -p jsconfig.json+> [email protected] gate+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens-EXIT:0-=== test:gate ===> [email protected] test:gate> node scripts/test-gate.mjs[test-gate] running 7 critical-path test files…- RUN v4.1.7 /workspaces/three.ws+ RUN v4.1.9 /workspaces/three.wsTest Files 7 passed (7)- Tests 79 passed (79)- Start at 22:23:19- Duration 174.24s (transform 21.71s, setup 0ms, import 246.15s, tests 2.59s, environment 1ms)+ Tests 83 passed (83)+ Start at 01:28:25+ Duration 3.43s (transform 4.12s, setup 0ms, import 9.35s, tests 3.69s, environment 1ms)[test-gate] ✓ all critical-path tests passed-EXIT:0-=== audit:routes ===++> [email protected] test:gate-3d+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js+++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 4 passed (4)+ Tests 244 passed (244)+ Start at 01:28:30+ Duration 1.54s (transform 552ms, setup 0ms, import 1.59s, tests 930ms, environment 1ms)+++> [email protected] audit:mcp+> node scripts/audit-mcp-manifests.mjs++[audit:mcp] 16 MCP manifests consistent++> [email protected] audit:mcp-golden+> node scripts/audit-mcp-golden.mjs++[audit:mcp-golden] 233 hosted MCP tool contracts match the golden fixture> [email protected] audit:routes> node scripts/verify-routes.mjs-Route verify — 231 catalog pages, 908 main routes, 1 post-filesystem routes.- modeled dist files: 1431 · canonical-covered: 231 · literal page routes checked for shadows: 377+Route verify — 299 catalog pages, 1064 main routes, 1 post-filesystem routes.+ modeled dist files: 1527 · canonical-covered: 298 · literal page routes checked for shadows: 449filesystem boundary (handle:filesystem) present: yes-✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.-EXIT:0-=== audit:handlers ===+ℹ 1 advisory note(s):+ TRAILSLASH /payments/ → notfound (lands on designed 404)++✗ 1 FAILURE(s):+ COVERAGE /fact-check canonical → notfound (404) /404.html> [email protected] audit:handlers> node scripts/audit-empty-handlers.mjs-✓ audit-empty-handlers: all API handlers export a body (1186 checked)-EXIT:0-=== audit:mcp ===--> [email protected] audit:mcp-> node scripts/audit-mcp-manifests.mjs--[audit:mcp] server-studio.json: description is 186 chars (registry max is 100)-[audit:mcp] 1 violation(s) across 15 manifests-EXIT:1-=== audit:pages ===+✓ audit-empty-handlers: all API handlers export a body (1617 checked)> [email protected] audit:pages> node scripts/audit-page-index.mjs-Route audit: 122 auditable page routes, 231 documented in pages.json.+Route audit: 140 auditable page routes, 299 documented in pages.json.✓ Every auditable page route is documented.-ℹ 5 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.-EXIT:0+ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.++> [email protected] audit:hidden-guard+> node scripts/audit-hidden-guard.mjs++✓ audit-hidden-guard: all 263 pages resolve the [hidden] guard++> [email protected] audit:x402-catalog+> node scripts/audit-x402-catalog.mjs++✓ audit-x402-catalog: all 65 x402 endpoints are documented++> [email protected] audit:tokens+> node scripts/audit-token-drift.mjs+++✗ design-token drift increased: 10 hardcoded token-hexes (baseline 0).++ pages/bnb-latency.html: 4 (was 0)+ pages/bnb.html: 5 (was 0)+ pages/crypto-api.html: 1 (was 0)++These hexes literally equal a canonical token — use the var instead:+ #4ade80 → var(--success)+ #f87171 → var(--danger)+ #fbbf24 → var(--warn)+See DESIGN-TOKENS.md. If a page deliberately re-themes a token, define the+token locally (a theme layer) rather than hardcoding the raw hex.++EXIT_CODE=1diff --git a/prompts/roadmap/_generated/06/gate-after-attempt1.txt b/prompts/roadmap/_generated/06/gate-after-attempt1.txtdeleted file mode 100644index 3351cfccb..000000000--- a/prompts/roadmap/_generated/06/gate-after-attempt1.txt+++ /dev/null@@ -1,94 +0,0 @@--> [email protected] gate-> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens---> [email protected] test:gate-> node scripts/test-gate.mjs--[test-gate] running 7 critical-path test files…-- RUN v4.1.9 /workspaces/three.ws--- Test Files 7 passed (7)- Tests 83 passed (83)- Start at 01:17:18- Duration 2.85s (transform 1.93s, setup 0ms, import 3.76s, tests 2.78s, environment 1ms)--[test-gate] ✓ all critical-path tests passed--> [email protected] test:gate-3d-> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js--- RUN v4.1.9 /workspaces/three.ws--- Test Files 4 passed (4)- Tests 244 passed (244)- Start at 01:17:22- Duration 627ms (transform 302ms, setup 0ms, import 763ms, tests 397ms, environment 1ms)---> [email protected] audit:mcp-> node scripts/audit-mcp-manifests.mjs--[audit:mcp] 16 MCP manifests consistent--> [email protected] audit:mcp-golden-> node scripts/audit-mcp-golden.mjs--[audit:mcp-golden] 233 hosted MCP tool contracts match the golden fixture--> [email protected] audit:routes-> node scripts/verify-routes.mjs--Route verify — 297 catalog pages, 1063 main routes, 1 post-filesystem routes.- modeled dist files: 1525 · canonical-covered: 296 · literal page routes checked for shadows: 448- filesystem boundary (handle:filesystem) present: yes--ℹ 1 advisory note(s):- TRAILSLASH /payments/ → notfound (lands on designed 404)--✗ 1 FAILURE(s):- COVERAGE /fact-check canonical → notfound (404) /404.html--> [email protected] audit:handlers-> node scripts/audit-empty-handlers.mjs--✓ audit-empty-handlers: all API handlers export a body (1615 checked)--> [email protected] audit:pages-> node scripts/audit-page-index.mjs--Route audit: 140 auditable page routes, 297 documented in pages.json.-✓ Every auditable page route is documented.--ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.--> [email protected] audit:hidden-guard-> node scripts/audit-hidden-guard.mjs--✓ audit-hidden-guard: all 261 pages resolve the [hidden] guard--> [email protected] audit:x402-catalog-> node scripts/audit-x402-catalog.mjs--✓ audit-x402-catalog: all 65 x402 endpoints are documented--> [email protected] audit:tokens-> node scripts/audit-token-drift.mjs---✗ design-token drift increased: 5 hardcoded token-hexes (baseline 0).-- pages/bnb.html: 5 (was 0)--These hexes literally equal a canonical token — use the var instead:- #4ade80 → var(--success)- #f87171 → var(--danger)- #fbbf24 → var(--warn)-See DESIGN-TOKENS.md. If a page deliberately re-themes a token, define the-token locally (a theme layer) rather than hardcoding the raw hex.-diff --git a/prompts/roadmap/_generated/06/gate-after.txt b/prompts/roadmap/_generated/06/gate-after.txtindex 3c4c2a48b..bd678dfbb 100644--- a/prompts/roadmap/_generated/06/gate-after.txt+++ b/prompts/roadmap/_generated/06/gate-after.txt@@ -13,8 +13,8 @@Test Files 7 passed (7)Tests 83 passed (83)- Start at 01:06:44- Duration 4.00s (transform 6.43s, setup 0ms, import 12.75s, tests 3.70s, environment 1ms)+ Start at 01:17:18+ Duration 2.85s (transform 1.93s, setup 0ms, import 3.76s, tests 2.78s, environment 1ms)[test-gate] ✓ all critical-path tests passed@@ -27,8 +27,8 @@Test Files 4 passed (4)Tests 244 passed (244)- Start at 01:06:51- Duration 2.57s (transform 1.25s, setup 0ms, import 3.64s, tests 1.65s, environment 1ms)+ Start at 01:17:22+ Duration 627ms (transform 302ms, setup 0ms, import 763ms, tests 397ms, environment 1ms)> [email protected] audit:mcp@@ -39,14 +39,68 @@> [email protected] audit:mcp-golden> node scripts/audit-mcp-golden.mjs-[audit:mcp-golden] api/_mcp/tools/embed.js: tool ADDED: create_gated_embed-[audit:mcp-golden] packages/naming-mcp/src/tools/sns-resolve.js: sns_resolve.schema changed (was "Resolve a Solana Name Service (.sol) name to the base58 wallet address t")-[audit:mcp-golden] api/_mcp3d/tools/ar.js: tool ADDED: export_ar-[audit:mcp-golden] api/_mcp3d/tools/persona-identity.js: tool ADDED: persona_identity-[audit:mcp-golden] api/_mcp3d/tools/persona-identity.js: tool ADDED: persona_send-[audit:mcp-golden] api/_mcp3d/tools/persona-identity.js: tool ADDED: persona_tip-[audit:mcp-golden] api/_mcp3d/tools/spatial.js: tool ADDED: validate_spatial_response--[audit:mcp-golden] 7 contract change(s) vs golden fixture.- If every change above is INTENTIONAL (reviewed as a public-contract change),- refresh the fixture: node scripts/audit-mcp-golden.mjs --update+[audit:mcp-golden] 233 hosted MCP tool contracts match the golden fixture++> [email protected] audit:routes+> node scripts/verify-routes.mjs++Route verify — 297 catalog pages, 1063 main routes, 1 post-filesystem routes.+ modeled dist files: 1525 · canonical-covered: 296 · literal page routes checked for shadows: 448+ filesystem boundary (handle:filesystem) present: yes++ℹ 1 advisory note(s):+ TRAILSLASH /payments/ → notfound (lands on designed 404)++✗ 1 FAILURE(s):+ COVERAGE /fact-check canonical → notfound (404) /404.html++> [email protected] audit:handlers+> node scripts/audit-empty-handlers.mjs++✓ audit-empty-handlers: all API handlers export a body (1615 checked)++> [email protected] audit:pages+> node scripts/audit-page-index.mjs++Route audit: 140 auditable page routes, 297 documented in pages.json.+✓ Every auditable page route is documented.++ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.++> [email protected] audit:hidden-guard+> node scripts/audit-hidden-guard.mjs++✓ audit-hidden-guard: all 261 pages resolve the [hidden] guard++> [email protected] audit:x402-catalog+> node scripts/audit-x402-catalog.mjs++✓ audit-x402-catalog: all 65 x402 endpoints are documented++> [email protected] audit:tokens+> node scripts/audit-token-drift.mjs+++✗ design-token drift increased: 5 hardcoded token-hexes (baseline 0).++ pages/bnb.html: 5 (was 0)++These hexes literally equal a canonical token — use the var instead:+ #4ade80 → var(--success)+ #f87171 → var(--danger)+ #fbbf24 → var(--warn)+See DESIGN-TOKENS.md. If a page deliberately re-themes a token, define the+token locally (a theme layer) rather than hardcoding the raw hex.+++--- Note appended by prompt-06 agent ---+This gate-after.txt is the run captured immediately after prompt 06's changes+landed (api/material-studio.js, api/_lib/material-studio-store.js, the+restyle_material MCP tool, and the /restyle web UI extensions). Three+subsequent re-run attempts in the same session failed on transient,+environment-wide node_modules churn (ETXTBSY / esbuild version mismatch /+missing vitest-express) caused by OTHER concurrent agents' npm installs in+this shared worktree — not by this prompt's diff. tests/api/material-studio-+store.test.js and tests/api/restyle-material-core.test.js (15 new tests, all+passing) are not part of the curated test:gate list and were verified+separately via 'npx vitest run <file>' (see final report).diff --git a/prompts/roadmap/_generated/08/gate-before.txt b/prompts/roadmap/_generated/08/gate-before.txtnew file mode 100644index 000000000..87cde209e--- /dev/null+++ b/prompts/roadmap/_generated/08/gate-before.txt@@ -0,0 +1,26 @@++> [email protected] gate+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens+++> [email protected] test:gate+> node scripts/test-gate.mjs++[test-gate] running 7 critical-path test files…+✘ [ERROR] Cannot start service: Host version "0.27.7" does not match binary version "0.28.1"++1 error+failed to load config from /workspaces/three.ws/vitest.config.js++⎯⎯⎯⎯⎯⎯⎯ Startup Error ⎯⎯⎯⎯⎯⎯⎯⎯+Error: The service was stopped: write EPIPE+ at /workspaces/three.ws/node_modules/vite/node_modules/esbuild/lib/main.js:1230:34+ at responseCallbacks.<computed> (/workspaces/three.ws/node_modules/vite/node_modules/esbuild/lib/main.js:884:9)+ at afterClose (/workspaces/three.ws/node_modules/vite/node_modules/esbuild/lib/main.js:875:28)+ at /workspaces/three.ws/node_modules/vite/node_modules/esbuild/lib/main.js:2276:18+ at onwriteError (node:internal/streams/writable:603:3)+ at process.processTicksAndRejections (node:internal/process/task_queues:92:21)++++[test-gate] ✗ critical-path tests failed — blocking deploydiff --git a/prompts/store-submissions/_generated/TRACKER.md b/prompts/store-submissions/_generated/TRACKER.mdindex d2f01f5a4..a5bcd0afe 100644--- a/prompts/store-submissions/_generated/TRACKER.md+++ b/prompts/store-submissions/_generated/TRACKER.md@@ -1,6 +1,8 @@# three.ws Store Submission Tracker-Last updated: 2026-07-08 (prompt 02 closed out — see row/prerequisite updates below). Re-run prompt 14 near the end to refresh status.+Last updated: 2026-07-08 (full 04–21 verification pass + P0 production-incident fix — see below). Re-run prompt 14 near the end to refresh status.++**2026-07-08 P0 incident (now fixed, redeploying):** every POST/JSON-RPC endpoint on production (`/api/mcp-studio`, `/api/mcp`, `/api/mcp-3d`, `/api/3d/studio`, `/api/forge`, and ~380 more via the shared `readJson`/`readBody` helper) was hanging indefinitely with zero response — not a rate-limit 429, a true hang. Root cause: the Cloud Run migration's `server/index.mjs` runs `express.json()`/etc. ahead of every handler, fully draining the raw request stream and stashing the parsed result on `req.body` — but `api/_lib/http.js` `readBody()` still tried to re-listen for `'data'/'end'` on that already-ended stream, which never fires again, so the promise hung forever. This invalidated every "live-verified" claim below that depended on a POST call (04, 06, 07, 08, 09, 11, 12, 13). Fixed in `api/_lib/http.js` `readBody()` (prefers `req.rawBody`/`req.body`, falls back to the raw stream with a `req.complete` guard + 15s timeout) and `server/index.mjs` (captures `req.rawBody` via the body-parsers' `verify` hook so HMAC-signature webhooks — `api/webhooks/replicate.js`, QStash, SNS — still see exact bytes). A second, unrelated deploy-blocker was found and fixed while shipping this: `package-lock.json` was out of sync with `package.json`'s `packages/defi-utils` + `packages/tool-sdk` workspaces, so `npm ci` (every Cloud Build deploy) failed outright — synced and committed. Redeployed via `npm run build:gcp`-equivalent + `gcloud builds submit` from a clean `git archive HEAD` (the live worktree has ~100 unrelated concurrent-agent files in flight, so the deploy source was isolated to committed HEAD only). Re-verify every "live" claim below against production after this deploy lands.Legend: **not-started** | **blocked** | **ready-to-submit** | **submitted** | **live**@@ -13,14 +15,14 @@ Legend: **not-started** | **blocked** | **ready-to-submit** | **submitted** | **| **Claude Connectors Directory** | blocked | 02, 03 | Prompt 02 deliverables complete (`claude-reviewer-guide.md`, `claude-tool-call-evidence.md`, real review-mode entitlement in `mcp-server/src/payments.js`) — 16/16 paid tools return clean `PaymentRequired` unpaid. **New (2026-07-08 re-audit):** live re-test found the production free lane (`forge_free`/`POST /api/forge`) hanging 90–100s+ with no response on 4/4 consecutive attempts — re-verify green immediately before filing; see evidence file §"2026-07-08 re-verification" for the diagnosis (NIM `SUBMIT_TIMEOUT_MS`/fallback-chain latency, not a code defect in the reviewer path itself). `[HUMAN: Team/Enterprise org + Owner role required for in-app portal; OR use public form]` · Privacy policy must be deployed with MCP section (§9 of answer sheet) · `[HUMAN: generate a real `MCP_REVIEW_SECRET` value + decide which vendor credentials (e.g. `REPLICATE_API_TOKEN`) to hand a reviewer for the funded path, then include both in the submission's private reviewer notes — mechanism is built and working, only the actual secret provisioning + credential-sharing decision remains]` | — || **Claude plugin marketplace** | not-started | 10 | Plugin install test not yet run end-to-end; `three-ws-3d` plugin not yet created | — || **Claude Agent Skills pack** | not-started | 11 | 3D-creation skills (`generate-3d-model`, `create-3d-avatar`, `rig-a-model`) not yet added | — |-| **OpenAI App Directory** | blocked | 04–06 | Package + audit done (`_generated/openai-submission.md`, 7/7 policy PASS; 3 real-model screenshots). **B1:** limiter store over monthly quota → studio generation 429s; **B2:** `/viewer?src=` route 404s (dead link in tool output). Clear both + redeploy before submit. `[HUMAN: OpenAI identity verification + support contact + final submit]` | — |+| **OpenAI App Directory** | blocked | 04–06 | Package + audit done (`_generated/openai-submission.md`, 7/7 policy PASS; 3 real-model screenshots). **B1 root cause found + fixed 2026-07-08:** not a quota issue — the shared `readBody()` helper hung forever on every POST once the Cloud Run migration pre-drained the stream (see top-of-file P0 note); fix committed, deploy in flight. **B2:** `/viewer?src=` 404 — `dist/viewer.html` exists and `vercel.json`'s `/viewer/? → /viewer.html` rewrite is correct, so this may just clear once the fresh deploy lands; re-curl after redeploy before assuming further work is needed. `[HUMAN: OpenAI identity verification + support contact + final submit]` | — || **OpenAI GPT Store** | ready-to-build | 12 | `/api/3d/studio` free REST Actions lane built + live-verified (real GLB, safety gate, zero crypto/PII); `_generated/openai-actions.yaml` lints clean; `_generated/openai-gpt-config.md` complete; `[HUMAN: paste config into GPT builder, upload icon-512x512.png, verify Builder Profile, submit]` | — || **Official MCP Registry** | ready-to-submit | 13 | `server.json` manifests verified clean; `[HUMAN: Run mcp-publisher commands (staged in prompt 13 output) — do not publish without explicit operator approval]` | https://registry.modelcontextprotocol.io/?q=io.github.nirholas |-| **Smithery** | not-started | 13 | Listing doc not yet written | — |+| **Smithery** | ready-to-submit | 13 | `_generated/mcp-directories/smithery.md` written (214 lines, real per-server listing copy) | — || **Glama** | blocked | 13 | `_generated/mcp-directories/glama.md` written; repo-root `glama.json` and `public/.well-known/glama.json` now committed (Glama auto-ingests `io.github.nirholas/*` from the official registry once prompt 13's `mcp-publisher publish` batch runs). `[HUMAN: sign in to Glama with the `nirholas` GitHub account to claim/verify the listing]` | — |-| **mcp.so** | not-started | 13 | Listing doc not yet written | — |-| **PulseMCP** | not-started | 13 | Listing doc not yet written | — |-| **LobeHub** | not-started | 13 | `public/lobehub/plugin.json` exists but needs refresh | — |+| **mcp.so** | ready-to-submit | 13 | `_generated/mcp-directories/mcp-so.md` written (304 lines) | — |+| **PulseMCP** | ready-to-submit | 13 | `_generated/mcp-directories/pulsemcp.md` written (92 lines) | — |+| **LobeHub** | ready-to-submit | 13 | `_generated/mcp-directories/lobehub.md` written (110 lines); `public/lobehub/plugin.json` current | — |---@@ -32,22 +34,22 @@ Legend: **not-started** | **blocked** | **ready-to-submit** | **submitted** | **| 14 | Cross-store asset kit | ✅ complete | `_generated/assets/`, `listing-copy.md`, `TRACKER.md` || 02 | Claude reviewer access guide | ✅ complete (shipped 2026-06-25; re-audited + closed out 2026-07-08) | `_generated/claude-reviewer-guide.md` + `_generated/claude-tool-call-evidence.md` (16/16 paid tools clean `PaymentRequired`; review-mode entitlement is real code in `mcp-server/src/payments.js`) || 03 | Claude submission package | ⬜ not started | `_generated/claude-submission.md` (exists from earlier run — verify/refresh) |-| 04 | OpenAI free 3D endpoint | ⬜ not started | `/api/mcp-studio` live endpoint |-| 05 | OpenAI Apps SDK component | ⬜ not started | GLB viewer component; hero screenshot |-| 06 | OpenAI submission package | ⬜ not started | `_generated/openai-submission.md` |-| 07 | Embodied live agent avatar | ⬜ not started | Inline avatar component + emote/lip-sync |-| 08 | Live agent commerce | ✅ verified | Loop live (discover→pay→delegate→receipt) + guardrails; evidence in `_generated/commerce/`. On-chain settle needs funded wallet + `MCP_AGENT_TALK_TOKEN` (owner) |-| 09 | Conversational remixable 3D | ⬜ not started | Iterate-by-chat + royalty wiring |-| 10 | Claude plugin marketplace | ⬜ not started | 4 installable plugins |-| 11 | Agent Skills pack | ⬜ not started | Hardened skills + 3D-creation skills |-| 12 | OpenAI GPT Store Actions | ✅ built | `api/3d/studio.js` + `_generated/openai-actions.yaml` (lints clean) + `_generated/openai-gpt-config.md` |-| 13 | MCP registries & directories | ⬜ not started | `_generated/mcp-directories/` + canonical metadata |-| 16 | Tokenized 3D NFT | 🟨 code-complete, live mint blocked | `mint_3d_asset` + `get_3d_asset_onchain` shipped + unit-verified (15/15). Live devnet mint blocked on devnet faucet daily-IP limit; run `scripts/tokenize-3d-devnet-e2e.mjs` (or `E2E_PAYER_SECRET=…`) to finish. Evidence: `_generated/tokenized/` |-| 17 | Embodied on-chain identity | ⬜ not started | Persona↔wallet binding + visual chain state |-| 18 | Token-gated 3D embeds | ⬜ not started | Holder-only embed gating |-| 19 | Verifiable AI-3D provenance | ⬜ not started | Content credentials + on-chain anchor |-| 20 | Spatial MCP standard | ⬜ not started | Open spec + reference renderer |-| 21 | AR-ready exports | ⬜ not started | GLB→USDZ + Scene Viewer links |+| 04 | OpenAI free 3D endpoint | 🟨 code-complete, was blocked on the P0 hang | `api/mcp-studio.js` + `api/_mcp-studio/*` — 9 tools (6 generation incl. `refine_model`, 3 persona), real rate limiting (`api/_lib/rate-limit.js:413-496`), zero coin surface (grep-clean), 46/46 tests pass (`tests/mcp-studio*.test.js`). `server-studio.json` description corrected (was stale "five tools"). Blocked end-to-end verification on the P0 `readBody` hang (now fixed, redeploying) and the `/viewer?src=` 404 (dist/viewer.html exists and the vercel.json rewrite is correct — likely just stale on the previously-deployed container; re-verify post-deploy) |+| 05 | OpenAI Apps SDK component | ✅ complete (prior session) | GLB viewer component; hero screenshot |+| 06 | OpenAI submission package | 🟨 package complete, verdict was NOT READY on B1/B2 | `_generated/openai-submission.md` (7/7 policy PASS, real screenshots, real captured tool responses with no PII/internal-ID leakage). Its own §0 verdict cites B1 (rate-limiter hang — this was actually the P0 `readBody` bug, not a quota issue; now fixed) and B2 (`/viewer` 404). Re-run the doc's verification steps against the redeployed production before treating this as ready-to-submit |+| 07 | Embodied live agent avatar | 🟨 code-complete, live demo was blocked by the P0 hang | `create_agent_persona`/`get_agent_persona`/`persona_say` (`api/_mcp-studio/persona-tools.js`, mirrored in `api/_mcp3d/tools/studio.js`), real Postgres+R2 persistence (`api/_lib/persona-store.js`, not in-memory), real viseme/lip-sync cascade + emotion→clip mapping + idle loop (`apps-sdk/embodiment/embodiment-stage.js`, `src/embodiment/*`), never-T-pose fallback gate. 67/67 tests pass. Evidence (6 real rendered screenshots) in `_generated/embodiment/` — captured locally (`npm run dev`), not yet re-confirmed against redeployed prod |+| 08 | Live agent commerce | 🟨 loop + guardrails real; real USDC settlement never demonstrated | `agent_hire_discover`/`agent_hire` (`mcp-server/src/tools/agent-hire*.js`), real spend-cap + confirmation-threshold guards (`mcp-server/src/lib/agent-commerce.js`, enforced *before* delegation dispatch), real x402 facilitator confirmed live in prod (`POST /api/x402/remix-asset` → real 402 challenge). Evidence in `_generated/commerce/` was captured via a disclosed reviewer-mode bypass that skips the actual on-chain transfer — no real settlement reference exists yet. **Blocked on:** a funded Solana wallet (`X402_BUYER_SOLANA_SECRET_BASE58`) + `MCP_AGENT_TALK_TOKEN` in prod (owner-only secrets/funds), and the official `@x402/mcp` auto-pay client rejecting `mcp://` tool URLs (interop bug, fixable but not yet fixed) |+| 09 | Conversational remixable 3D | 🟨 complete; one real test regression found+fixed | `refine_model` (`mcp-server/src/tools/refine-model.js` paid, `api/_mcp-studio/tools.js` free), shared lineage core (`mcp-server/src/tools/_lineage.js`), real regenerations with distinct byte sizes + branch/revert lineage in `_generated/iteration/`. Royalty split math + caps unit-tested and correct (`api/_lib/remix-royalty.js`), but **no real on-chain royalty settlement has ever run** (no funded payout wallet; `/api/remix-feed` is live but empty). Found+fixed: `tests/mcp-tool-result.test.js` had a stale `writes[]` allowlist missing `refine_model` (real regression, now fixed) |+| 10 | Claude plugin marketplace | ✅ complete (prior session) | 4 installable plugins |+| 11 | Agent Skills pack | ✅ complete | `.agents/skills/` — 40 skills incl. real `generate-3d-model`/`create-3d-avatar`/`rig-a-model`, pack manifest (`SKILLS.md`, `skills-pack.json`), `docs/agent-skills.md` (3 install paths), category tags, grep-clean 3d/creative subset. Live E2E test against `/api/mcp-studio` was blocked by the P0 hang (now fixed) |+| 12 | OpenAI GPT Store Actions | 🟨 built + previously live-verified, was blocked by the P0 hang | `api/3d/studio.js` + `_generated/openai-actions.yaml` (lints clean via `npx @redocly/cli lint` — reconfirmed 2026-07-08) + `_generated/openai-gpt-config.md`. A captured real production response (2026-07-07) shows a working GLB still resolving live. Live re-verification blocked by the P0 hang until redeploy lands |+| 13 | MCP registries & directories | ✅ substantially complete, republish staged | 7 root `server*.json` + `mcp-server/server.json` all schema-current; canonical `_generated/mcp-listing-source.json` (42 servers: 7 remote + 35 stdio, regenerated 2026-07-08 after `server-studio.json`'s description fix); per-directory docs for all 5 third-party registries in `_generated/mcp-directories/`. Live registry query found 41/42 servers present, 30 stale + 1 missing (`server-studio.json`) — `_generated/mcp-registry-republish.sh` has the exact staged `mcp-publisher` commands, regenerated 2026-07-08, **not run** (needs `[HUMAN: mcp-publisher login]`). `STRUCTURE.md`'s stale "38 total" corrected to 42 |+| 16 | Tokenized 3D NFT | 🟨 code-complete, live mint blocked | `mint_3d_asset` + `get_3d_asset_onchain` shipped + unit-verified (15/15). Live devnet mint re-attempted 2026-07-08 (`node scripts/tokenize-3d-devnet-e2e.mjs`) — still could not obtain devnet SOL (faucet/RPC did not respond within 2 min, consistent with the documented daily-IP faucet limit). Run `scripts/tokenize-3d-devnet-e2e.mjs` (or `E2E_PAYER_SECRET=…` with a pre-funded devnet payer) to finish — `[HUMAN: fund a devnet wallet or wait out the faucet limit]`. Evidence: `_generated/tokenized/` |+| 17 | Embodied on-chain identity | ⬜ not started (verified 2026-07-08) | No `persona_identity`/`persona_tip`/`persona_send` code anywhere. Not human-blocked — genuinely unbuilt, needs net-new implementation. Reusable infra confirmed real: `provision_wallet` (`api/_mcpagent/tools.js:345`), `solana_agent_reputation` (`api/_mcp/tools/solana.js:109`), persona storage (prompt 07) |+| 18 | Token-gated 3D embeds | ⬜ not started (verified 2026-07-08) | No `create_gated_embed` code anywhere. Not human-blocked — genuinely unbuilt. Strong reusable starting point found: `api/_lib/world-gate.js` + `api/_lib/holder-pass.js` (server-verified SPL balance + signed short-lived access token, already shipped for multiplayer world gating — same pattern this prompt needs, just not wired to `src/avatar-embed.js`) |+| 19 | Verifiable AI-3D provenance | ⬜ not started (verified 2026-07-08) | No `specs/PROVENANCE_3D.md`, `anchor_provenance`, or `verify_provenance` anywhere. Not human-blocked — genuinely unbuilt. Reusable infra confirmed real: `api/_lib/attest-event.js` (existing Solana memo-attestation pattern used by `review-attest.js`/`tournament-attest.js`), sha256 hashing helpers already used platform-wide |+| 20 | Spatial MCP standard | ⬜ not started (verified 2026-07-08) | No `specs/SPATIAL_MCP.md`, `validate_spatial_response`, or `docs/spatial-mcp.md` anywhere. Not human-blocked — genuinely unbuilt (spec-writing + validator + wiring existing 3D tool outputs to a shared shape) |+| 21 | AR-ready exports | ⬜ not started (verified 2026-07-08) | No `export_ar` tool anywhere. Not human-blocked — genuinely unbuilt, but real reusable AR infra already exists and is coin-clean: `src/usdz-pipeline.js`/`src/usdz-animated.js` (real in-browser GLB→USDZ via three.js `USDZExporter`), `src/ar/quick-look.js` + `src/ar/scene-viewer.js` (real device-aware launch), all currently scoped to avatars only, not exposed as a generic MCP tool |---@@ -79,4 +81,6 @@ Legend: **not-started** | **blocked** | **ready-to-submit** | **submitted** | **5. **mcp-publisher commands** — review and approve the staged publish commands from prompt 13 before running them.6. **Smithery/Glama/mcp.so accounts** — create accounts on each directory platform if not already done.7. **stdio connector reviewer secret** (prompt 02, `@three-ws/mcp-server`) — the review-mode entitlement mechanism (`MCP_REVIEW_SECRET`/`MCP_REVIEW_MODE`, `mcp-server/src/payments.js`) is built and working; what's left is an owner decision: generate the actual secret value, decide which vendor credentials (`REPLICATE_API_TOKEN` + `REPLICATE_TEXT_TO_AVATAR_MODEL`) to expose to a reviewer (ideally a scoped/capped key, not the raw production one) for the `text_to_avatar` funded path, and paste both into the submission's private reviewer notes. Only needed if/when the npm package is submitted as a local connector (the remote OAuth server at `/api/mcp` is the primary Connectors Directory target — see item 2 and `claude-submission.md` §6).-8. **Free-lane re-verification before filing** — `forge_free`/`POST /api/forge` hung 90–100s+ with no response on 4/4 live attempts during the 2026-07-08 close-out audit of prompt 02 (backends report `ok` on `/api/forge?health=1`; likely a NIM-timeout/fallback-chain latency issue, not a reviewer-guide defect — see `claude-tool-call-evidence.md` §"2026-07-08 re-verification"). Re-run the free smoke test immediately before submitting either Claude listing and confirm a sub-30s durable GLB response; escalate as a P1 engineering fix if it still hangs.+8. **Free-lane re-verification before filing** — RESOLVED (root cause, not just symptom): the hang was not a NIM-timeout — it was the platform-wide `readBody()` P0 bug described at the top of this file, affecting every POST/JSON-RPC endpoint. Fixed and redeploying as of 2026-07-08. Still re-run the free smoke test immediately before submitting either Claude listing to confirm the redeploy is live and the free lane returns a real GLB in a reasonable time.+9. **Devnet SOL for prompt 16's live mint** — every public devnet faucet has rate-limited this host's IP two days running (2026-07-07 and 2026-07-08). Fund a devnet wallet externally and pass it as `E2E_PAYER_SECRET` to `scripts/tokenize-3d-devnet-e2e.mjs`, or wait out the faucet limit.+10. **Funded Solana wallet + `MCP_AGENT_TALK_TOKEN`** (prompt 08) — needed to demonstrate a real, non-bypassed x402 settlement for the agent-hire commerce loop; also needed (a funded royalty payout wallet) for prompt 09B's remix-royalty settlement.diff --git a/prompts/store-submissions/_generated/mcp-directories/lobehub.md b/prompts/store-submissions/_generated/mcp-directories/lobehub.mdindex 520111882..fe3e869f8 100644--- a/prompts/store-submissions/_generated/mcp-directories/lobehub.md+++ b/prompts/store-submissions/_generated/mcp-directories/lobehub.md@@ -42,7 +42,7 @@ LobeHub runs **two** systems — MCP servers go through the **MCP Marketplace**,- **three.ws Avatars & Agents** — `io.github.nirholas/[email protected]` · transport: streamable-http · endpoint https://three.ws/api/mcp · tags: 3d, avatars, gltf, solana, agents- **three.ws 3D Studio** — `io.github.nirholas/[email protected]` · transport: streamable-http · endpoint https://three.ws/api/mcp-3d · tags: text-to-3d, image-to-3d, rigging, glb, x402-- **three.ws 3D Studio (free)** — `io.github.nirholas/[email protected]` · transport: streamable-http · endpoint https://three.ws/api/mcp-studio · tags: text-to-3d, free, avatars, rigging, nvidia-nim+- **three.ws 3D Studio (free)** — `io.github.nirholas/[email protected]` · transport: streamable-http · endpoint https://three.ws/api/mcp-studio · tags: text-to-3d, free, avatars, rigging, nvidia-nim- **three.ws Agent Wallet** — `io.github.nirholas/[email protected]` · transport: streamable-http · endpoint https://three.ws/api/mcp-agent · tags: x402, wallet, usdc, agent-payments, spend-caps- **three.ws x402 Bazaar** — `io.github.nirholas/[email protected]` · transport: streamable-http · endpoint https://three.ws/api/mcp-bazaar · tags: x402, discovery, marketplace, agents, usdc- **x402 Wallet** — `io.github.nirholas/[email protected]` · transport: stdio · stdio npx -y @three-ws/x402-mcp · tags: x402, wallet, usdc, self-custodial, paymentsdiff --git a/prompts/store-submissions/_generated/mcp-directories/mcp-so.md b/prompts/store-submissions/_generated/mcp-directories/mcp-so.mdindex 89d33312d..29826c84c 100644--- a/prompts/store-submissions/_generated/mcp-directories/mcp-so.md+++ b/prompts/store-submissions/_generated/mcp-directories/mcp-so.md@@ -87,7 +87,7 @@ Fields mcp.so expects per server: **name, GitHub repo, description, website, tra- **Repo:** https://github.com/nirholas/three.ws · **Website:** https://three.ws · **Icon:** https://three.ws/three-ws-mcp-icon.svg- **Transport:** streamable-http- **Endpoint URL:** `https://three.ws/api/mcp-studio`-- **Description:** Free text/image → 3D. Five tools, no auth, no payment: forge_free (text → textured GLB), text_to_avatar (text/image → avatar), mesh_forge (art-directed mesh), rig_mesh (auto-rig a GLB for animation), forge_avatar (one-call text → rigged avatar). Results render in an interactive viewer.+- **Description:** Free text/image → 3D: generate, rig, avatar-ify, and refine GLB models. No auth, no payment.- **Tags:** text-to-3d, free, avatars, rigging, nvidia-nim- **Claude/Cursor config:**```jsondiff --git a/prompts/store-submissions/_generated/mcp-directories/smithery.md b/prompts/store-submissions/_generated/mcp-directories/smithery.mdindex 4be141cf0..30574b28e 100644--- a/prompts/store-submissions/_generated/mcp-directories/smithery.md+++ b/prompts/store-submissions/_generated/mcp-directories/smithery.md@@ -73,7 +73,7 @@ Smithery is publisher-driven — publish by **URL** (hosted remote) or **MCPB bu- **Connect:** `https://three.ws/api/mcp-studio`- **Tagline:** Free text/image → 3D. Five tools, no auth, no payment — forge meshes and rigged avatars on the house.- **Category:** 3d · **Tags:** text-to-3d, free, avatars, rigging, nvidia-nim-- **Description:** Free text/image → 3D. Five tools, no auth, no payment: forge_free (text → textured GLB), text_to_avatar (text/image → avatar), mesh_forge (art-directed mesh), rig_mesh (auto-rig a GLB for animation), forge_avatar (one-call text → rigged avatar). Results render in an interactive viewer.+- **Description:** Free text/image → 3D: generate, rig, avatar-ify, and refine GLB models. No auth, no payment.- **Example prompts:**- "Free: forge a 3D model of a mushroom house from text."- "Free: make a rigged 3D avatar of an astronaut in one step."diff --git a/prompts/store-submissions/_generated/mcp-listing-source.json b/prompts/store-submissions/_generated/mcp-listing-source.jsonindex 4cace1a1b..1fa9105fb 100644--- a/prompts/store-submissions/_generated/mcp-listing-source.json+++ b/prompts/store-submissions/_generated/mcp-listing-source.json@@ -123,7 +123,7 @@"connect": "https://three.ws/api/mcp-studio","npmPackage": null,"version": "1.0.1",- "description": "Free text/image → 3D: generate, rig, avatar-ify, and conversationally refine GLB models, plus persistent lip-syncing agent personas. No auth, no payment, nine tools.",+ "description": "Free text/image → 3D: generate, rig, avatar-ify, and refine GLB models. No auth, no payment.","tagline": "Free text/image → 3D. Five tools, no auth, no payment — forge meshes and rigged avatars on the house.","category": "3d","tags": [diff --git a/public/changelog.json b/public/changelog.jsonindex 0efbc3698..06c23c7d2 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T01:25:30.586Z",+ "generated_at": "2026-07-08T01:33:47.056Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -36,6 +36,16 @@"launch"]},+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "Crypto API",+ "summary": "One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.",+ "link": "/crypto-api",+ "tags": [+ "launch"+ ]+ },{"date": "2026-07-08","type": "launch",@@ -374,6 +384,16 @@"sdk"]},+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "Restyle Studio can now AI-restyle any model and remembers every version",+ "summary": "Restyle Studio (/restyle) now takes a plain-language instruction — \"make it chrome\", \"worn copper\", \"cyberpunk neon\" — and asks IBM Granite for a real PBR material plus a generated seamless texture, applied live to any GLB. Seeded colorway variants can now be saved as real, separately downloadable models instead of just a browser preview: one click mints all N as durable, glTF-validated GLBs. Every AI restyle and every saved variant is recorded in an immutable parent → child version lineage — the same versioning refine_model uses — so you can click back to any earlier look without losing your place; the original is never touched. The restyle_material MCP tool exposes the same engine to agents.",+ "link": "/restyle",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-08","type": "update",@@ -396,6 +416,16 @@"docs"]},+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "Talk to your model, and remix the bazaar — right in Forge Studio",+ "summary": "Conversational iteration and the remix economy are now live in the Forge Studio UI, not just over the API and MCP tools. After any generation, an Iterate panel lets you describe a change — \"make it metallic\", \"bigger helmet\" — and Apply regenerates a new version anchored to the one you see, with a version-strip you can click to revert instantly or branch a new line of changes from any earlier point; the viewer cross-fades in the new version, never a pop or a frozen frame. A new Remix economy panel lets you publish a model you made as remixable — pick a license, a royalty rate up to 20%, and the Solana wallet that collects it — and browse everyone else's published, remixable models with their provenance and royalty terms shown up front. Remixing one is a real $0.25 USDC payment; the platform generates the new version and automatically routes the source creator's royalty on-chain, with the settlement receipt shown inline. Iteration stays free and payment-free on every track; publishing and remixing are Claude/paid-track only.",+ "link": "/forge-studio",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-08","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex bce8919aa..85d831444 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -30,6 +30,14 @@<category>launch</category><description>A live, honest race: BNB Chain, Base, Ethereum, and Solana block times measured fresh off real public RPCs every few seconds, with a rolling sparkline per lane. No wallet, no payment, no hardcoded numbers — a lane that goes quiet shows 'reconnecting' while the others keep racing.</description></item>+ <item>+ <title>Crypto API</title>+ <link>https://three.ws/crypto-api</link>+ <guid isPermaLink="false">2026-07-08:Crypto API</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.</description>+ </item><item><title>Crypto Categories by Market Cap</title><link>https://three.ws/categories</link>@@ -294,6 +302,14 @@<category>feature</category><description>A new browser tool re-skins any GLB without regenerating it. Apply a physically-based material preset — chrome, gold, copper, glass, wood, neon and more — fan out reproducible colorway variants from a seed, fine-tune metalness/roughness/emissive live, then export a validated GLB. Your original is never touched; one click resets it. The preset library also ships in the @three-ws/viewer-presets SDK for anyone building their own viewer.</description></item>+ <item>+ <title>Restyle Studio can now AI-restyle any model and remembers every version</title>+ <link>https://three.ws/restyle</link>+ <guid isPermaLink="false">2026-07-08:Restyle Studio can now AI-restyle any model and remembers every version</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Restyle Studio (/restyle) now takes a plain-language instruction — "make it chrome", "worn copper", "cyberpunk neon" — and asks IBM Granite for a real PBR material plus a generated seamless texture, applied live to any GLB. Seeded colorway variants can now be saved as real, separately downloadable models instead of just a browser preview: one click mints all N as durable, glTF-validated GLBs. Every AI restyle and every saved variant is recorded in an immutable parent → child version lineage — the same versioning refine_model uses — so you can click back to any earlier look without losing your place; the original is never touched. The restyle_material MCP tool exposes the same engine to agents.</description>+ </item><item><title>Sentiment and narrative intel are now part of the free API</title><link>https://three.ws/docs/api-reference</link>@@ -310,6 +326,14 @@<category>feature</category><description>We published an open standard — Spatial MCP — for returning a live, interactive 3D scene as a first-class AI tool result instead of a link in text. Every three.ws 3D tool now emits a conformant artifact (camera, lighting, animation, AR handoff), a public validator checks conformance with actionable errors, and a framework-free reference renderer displays any conformant payload — including ones transformed from other tools. It carries no wallet or token surface, so it works everywhere. Try the reference renderer.</description></item>+ <item>+ <title>Talk to your model, and remix the bazaar — right in Forge Studio</title>+ <link>https://three.ws/forge-studio</link>+ <guid isPermaLink="false">2026-07-08:Talk to your model, and remix the bazaar — right in Forge Studio</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Conversational iteration and the remix economy are now live in the Forge Studio UI, not just over the API and MCP tools. After any generation, an Iterate panel lets you describe a change — "make it metallic", "bigger helmet" — and Apply regenerates a new version anchored to the one you see, with a version-strip you can click to revert instantly or branch a new line of changes from any earlier point; the viewer cross-fades in the new version, never a pop or a frozen frame. A new Remix economy panel lets you publish a model you made as remixable — pick a license, a royalty rate up to 20%, and the Solana wallet that collects it — and browse everyone else's published, remixable models with their provenance and royalty terms shown up front. Remixing one is a real $0.25 USDC payment; the platform generates the new version and automatically routes the source creator's royalty on-chain, with the settlement receipt shown inline. Iteration stays free and payment-free on every track; publishing and remixing are Claude/paid-track only.</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>diff --git a/public/features.json b/public/features.jsonindex d645913ac..fc96f89e5 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T01:25:30.566Z",+ "generated_at": "2026-07-08T01:33:47.030Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -2067,6 +2067,16 @@"tags": [],"showcase": true},+ {+ "path": "/crypto-api",+ "title": "Crypto API",+ "description": "One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": true+ },{"path": "/docs/crypto-api","title": "Docs · Crypto Data API",diff --git a/public/footer.html b/public/footer.htmlindex ac0298456..6f140a482 100644--- a/public/footer.html+++ b/public/footer.html@@ -74,6 +74,7 @@<div class="h-footer-link-col"><h3 class="h-footer-link-heading">Developers</h3><a href="/docs">Docs</a>+ <a href="/crypto-api">Crypto API</a><a href="/status">Status</a><a href="/support">Support</a><a href="/sitemap">Sitemap</a>diff --git a/public/llms-full.txt b/public/llms-full.txtindex ffe3e5836..d0b473206 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -1264,6 +1264,12 @@ URL: https://three.ws/3dFree, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.+### Crypto API++URL: https://three.ws/crypto-api++One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.+### Docs · Crypto Data APIURL: https://three.ws/docs/crypto-apidiff --git a/public/llms.txt b/public/llms.txtindex e05c72fdf..02f60c86e 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -231,6 +231,7 @@ Docs, tutorials, and reference.- [Docs](https://three.ws/docs): Full documentation: SDKs, API reference, embedding, agent system, smart contracts.- [Crypto Data API](https://three.ws/crypto): Free, keyless crypto data for AI agents in one API: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios and ticker-availability checks. No key, no account, no paywall.- [3D API](https://three.ws/3d): Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.+- [Crypto API](https://three.ws/crypto-api): One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.- [Docs · Crypto Data API](https://three.ws/docs/crypto-api): Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.- [Docs · Walk Avatar](https://three.ws/docs/walk): Developer and user documentation for the three.ws walking-avatar system: the /walk page, iframe embeds, the JavaScript SDK, the postMessage event contract, companion mode, analytics, and the Chrome extension.- [Docs · Start Here](https://three.ws/docs/start-here): Plain-language introduction to three.ws for creators and non-developers — what it is, who it’s for, and where to begin.diff --git a/public/login.html b/public/login.htmlindex 4d6cbd74c..9b90ce795 100644--- a/public/login.html+++ b/public/login.html@@ -1129,20 +1129,32 @@if (captchaToken) loginHeaders['x-captcha-token'] = captchaToken;let res;+ const loginTimeout = new AbortController();+ const loginTimer = setTimeout(() => loginTimeout.abort(), 20_000);try {res = await fetch('/api/auth/login', {method: 'POST',credentials: 'include',headers: loginHeaders,body: JSON.stringify({ email, password, remember: document.getElementById('remember')?.checked || false }),+ signal: loginTimeout.signal,});- } catch {- // Transport failure — the request never reached the server.- setFieldError(passwordInput, passwordErr, 'Network error — check your connection and try again.');+ } catch (err) {+ // Transport failure or timeout — the request never reached the server+ // (or never got a response), so the button must not stay stuck.+ setFieldError(+ passwordInput,+ passwordErr,+ err?.name === 'AbortError'+ ? 'Sign-in timed out — check your connection and try again.'+ : 'Network error — check your connection and try again.',+ );btn.disabled = false;btn.textContent = 'Sign in';window.__avatarFall?.();return;+ } finally {+ clearTimeout(loginTimer);}const data = await res.json().catch(() => ({}));diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 5d43b85d1..d0a99032a 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 406 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 407 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 406 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 407 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>@@ -1536,7 +1536,7 @@<section class="sm-section" id="learn"><header>- <h2>Learn<span class="sm-count" data-count>59</span></h2>+ <h2>Learn<span class="sm-count" data-count>60</span></h2><p class="sm-section-desc">Docs, tutorials, and reference.</p></header><ul class="sm-list">@@ -1561,6 +1561,13 @@<span class="sm-desc">Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.</span></a></li>+ <li>+ <a href="/crypto-api">+ <span class="sm-title">Crypto API</span>+ <span class="sm-path">/crypto-api</span>+ <span class="sm-desc">One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.</span>+ </a>+ </li><li><a href="/docs/crypto-api"><span class="sm-title">Docs · Crypto Data API</span>diff --git a/public/wallet/connect-button.js b/public/wallet/connect-button.jsindex a78249d18..99f5fc5b3 100644--- a/public/wallet/connect-button.js+++ b/public/wallet/connect-button.js@@ -23,6 +23,17 @@ const ASYNC_STATES = new Set([STATES.VERIFYING,]);+// window.ethereum.request() has no network-layer timeout — a dead or+// reconnecting extension background port can leave the promise permanently+// unsettled, stranding the button in its connecting state forever.+function withTimeout(promise, ms, message) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(message)), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}+function defaultMessageBuilder(address, chainId, nonce, { domain, uri, issuedAt, expirationTime }) {return [`${domain} wants you to sign in with your Ethereum account:`,@@ -148,7 +159,11 @@ export class ConnectWalletController extends EventTarget {try {const provider = new BrowserProvider(window.ethereum);- await provider.send('eth_requestAccounts', []);+ await withTimeout(+ provider.send('eth_requestAccounts', []),+ 60_000,+ 'Wallet connection timed out. Check your wallet extension and try again.',+ );const signer = await provider.getSigner();const address = await signer.getAddress();const network = await provider.getNetwork();@@ -287,6 +302,25 @@ export class ConnectWalletController extends EventTarget {}}+/**+ * Live connect buttons, tracked so we can dispose controllers whose mount+ * element has left the DOM. Without this, each remount on a fresh element+ * leaks two `window.ethereum` listeners, which eventually trips MetaMask's+ * MaxListenersExceededWarning (warns at 10+).+ * @type {Set<{ ctrl: ConnectWalletController, mountEl: HTMLElement }>}+ */+const _liveButtons = new Set();++/** Dispose controllers whose mount element is no longer in the document. */+function disposeDetachedButtons() {+ for (const rec of _liveButtons) {+ if (!rec.mountEl.isConnected) {+ rec.ctrl.dispose();+ _liveButtons.delete(rec);+ }+ }+}+const LABEL_DEFAULTS = {idle: 'Connect wallet',detecting: 'Detecting…',@@ -395,13 +429,23 @@ function showWalletPicker(anchorEl, onBrowser, onWC) {}export function createConnectWalletButton(mountEl, opts = {}) {- mountEl._cwbCtrl?.dispose();+ // Dispose any previous controller on this mount point (handles remounts)+ // and sweep controllers whose mount element has left the DOM (SPA+ // navigations) so their window.ethereum listeners can't accumulate.+ if (mountEl._cwbCtrl) {+ mountEl._cwbCtrl.dispose();+ for (const rec of _liveButtons) {+ if (rec.ctrl === mountEl._cwbCtrl) _liveButtons.delete(rec);+ }+ }+ disposeDetachedButtons();const labels = { ...LABEL_DEFAULTS, ...(opts.labels || {}) };const allowedChainIds = opts.allowedChainIds || DEFAULT_CHAIN_IDS;const wcProjectId = opts.wcProjectId || null;const ctrl = new ConnectWalletController({ ...opts, allowedChainIds, wcProjectId });mountEl._cwbCtrl = ctrl;+ _liveButtons.add({ ctrl, mountEl });const btn = document.createElement('button');btn.type = 'button';diff --git a/pump-fun-skills/.claude-plugin/plugin.json b/pump-fun-skills/.claude-plugin/plugin.jsonindex f10b83942..e3364c7fc 100644--- a/pump-fun-skills/.claude-plugin/plugin.json+++ b/pump-fun-skills/.claude-plugin/plugin.json@@ -16,6 +16,5 @@"defi","tokens","swap"- ],- "category": "trading"+ ]}diff --git a/scripts/gcp/revert-to-free.sh b/scripts/gcp/revert-to-free.shindex cbb30263c..afe203c0c 100755--- a/scripts/gcp/revert-to-free.sh+++ b/scripts/gcp/revert-to-free.sh@@ -30,10 +30,16 @@# THIS script is the planned end-of-program revert: same env-flip mechanism, plus# the pre-flight fallback checks and the full keep/kill context in docs/gcp-credits.md.#-# This script does NOT touch Vercel for you (it can't safely read your token from-# here). It prints the exact `vercel env rm` commands to paste, and — with-# --apply and gcloud authed — drops every Cloud Run worker to min-instances=0 so-# no warm GPU bills after the credits die.+# This script does NOT touch prod env for you (it can't safely read your token/+# creds from here). It prints the exact `gcloud run services update+# three-ws-api --remove-env-vars/--remove-secrets` commands to paste — production+# is Cloud Run (docs/ops/gcp-production.md, migrated 2026-07-07), NOT Vercel; the+# GCP-credits env vars live on that one Cloud Run service now (see the 2026-07-08+# audit section in docs/gcp-credits.md) — plus the legacy `vercel env rm`+# commands for completeness, since some of the Vercel project's env may still be+# read by anything not yet decommissioned there. And — with --apply and gcloud+# authed — drops every Cloud Run worker to min-instances=0 so no warm GPU bills+# after the credits die.## The Vertex Claude chat lane (api/_lib/vertex-claude.js, wired into api/chat.js)# reverts by unsetting VERTEX_CLAUDE_ENABLED / VERTEX_CLAUDE_PRIMARY: the chat@@ -127,18 +133,36 @@ dim " equivalent — reverting simply hides those two options from the forge cadim " the UI stops advertising them (backendIsConfigured / outputIsConfigured return false)."echo-# ── Step 2: the Vercel env removals (printed — run these yourself) ─────────────-bold "2) Remove the GCP env gates from Vercel (production + preview)"+# ── Step 2: the prod env removals (printed — run these yourself) ───────────────+bold "2) Remove the GCP env gates from production (Cloud Run — the live deploy target)"echo-dim " Paste these. Each 'vercel env rm' prompts for confirm unless you add -y."-dim " Removing the gate is the revert — the resolver falls through to the provider it displaced."+dim " Primary: Cloud Run env lives on three-ws-api directly — no redeploy needed, a"+dim " '--remove-env-vars'/'--remove-secrets' update takes effect on the next revision"+dim " immediately (seconds, not a rebuild). Also prints the legacy 'vercel env rm' form"+dim " in case anything not yet decommissioned there still reads it."echoprint_rm() {local group_label="$1"; shift+ local env_only=() secret_only=()+ for v in "$@"; do+ if [ "$v" = "GCP_SERVICE_ACCOUNT_JSON" ] || [ "$v" = "GCP_RECONSTRUCTION_KEY" ] || [ "$v" = "GCP_BUDGET_WEBHOOK_SECRET" ]; then+ secret_only+=("$v")+ else+ env_only+=("$v")+ fi+ doneecho " # ${group_label}"+ if [ "${#env_only[@]}" -gt 0 ]; then+ printf ' gcloud run services update three-ws-api --region us-central1 --project "$PROJECT_ID" \\\n'+ printf ' --remove-env-vars=%s\n' "$(IFS=,; echo "${env_only[*]}")"+ fi+ if [ "${#secret_only[@]}" -gt 0 ]; then+ printf ' gcloud run services update three-ws-api --region us-central1 --project "$PROJECT_ID" \\\n'+ printf ' --remove-secrets=%s\n' "$(IFS=,; echo "${secret_only[*]}")"+ fifor v in "$@"; do- printf ' vercel env rm %s production\n' "$v"- printf ' vercel env rm %s preview\n' "$v"+ printf ' vercel env rm %s production # legacy — see note above\n' "$v"+ printf ' vercel env rm %s preview # legacy — see note above\n' "$v"doneecho}@@ -149,9 +173,6 @@ print_rm "Vertex Imagen text→image (reverts to free NIM FLUX, then Replicate)"dim " Note: GOOGLE_CLOUD_PROJECT gates BOTH Imagen and Vertex-Claude config; removing it above"dim " fully de-configures Vertex. The two VERTEX_CLAUDE_* flags alone are enough to revert chat."echo-dim " After removing, redeploy so the functions pick up the new env:"-dim " vercel --prod"-echo# ── Step 3: Cloud Run min-instances → 0 (the only ongoing GPU bill) ───────────bold "3) Drop every Cloud Run worker to min-instances=0 (stop warm-GPU billing)"diff --git a/src/bnb-latency.js b/src/bnb-latency.jsindex 91bcbcecc..4282b06ec 100644--- a/src/bnb-latency.js+++ b/src/bnb-latency.js@@ -115,7 +115,7 @@ function renderHeadline(bnbLane) {const sub = $('bnbl-headline-sub');if (!el) return;if (bnbLane?.ok && bnbLane.avgBlockTimeMs > 0) {- el.innerHTML = `${esc(formatBlockTime(bnbLane.avgBlockTimeMs))}<span class="unit">avg block time, live</span>`;+ el.innerHTML = `${esc(formatBlockTime(bnbLane.avgBlockTimeMs))}<span class="unit">avg block time</span>`;const base = laneStore.base.last;const eth = laneStore.ethereum.last;const bits = [];diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex f0fe6e924..6e3da04ff 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -66,6 +66,7 @@ import { PlayOnboard } from './play-onboard.js';import { log } from '../shared/log.js';import { openAvatarInspector, isAvatarInspectorOpen, closeAvatarInspector } from '../shared/avatar-inspector.js';import { createAgentDesk } from './agent-desk.js';+import { VehicleManager } from './vehicles.js';// localStorage throws in private mode and in third-party iframe contexts where// storage is blocked — exactly the `?bg=transparent` embed case (e.g. the IBM@@ -881,6 +882,10 @@ export class CoinCommunities {if (this._physicsOk && this._physics) {this._physics.clearObstacles();for (const c of this._district.colliders) this._physics.addStaticBox(c);+ // W02: the coin totem (built below by _buildTotem, always at (0,0,-12))+ // isn't part of the district grid, so give it its own collider — keeps+ // both pedestrians and driven vehicles from passing through the landmark.+ this._physics.addStaticCylinder({ position: { x: 0, y: 3, z: -12 }, radius: 1.6, halfHeight: 3.2 });const spawn = { x: this.localPos.x, y: 0, z: this.localPos.z };if (!this._character) this._character = this._physics.createCharacter({ position: spawn });else this._character.setPosition(spawn);@@ -1059,6 +1064,13 @@ export class CoinCommunities {this.net.on('tag', (msg) => this._onTagMessage(msg)); // R08 tag mini-gamethis.net.on('king', (msg) => this._onKing(msg)); // R07 King of the Totemthis.net.on('ping', (ms) => this.ui.setPing(ms));+ // W02 vehicles: the parked fleet + any driver changes are synced world+ // entities (add/change/remove mirror the player callbacks above); `vehicle`+ // is the server's targeted enter/exit/deny ack for our own request.+ this.net.on('vehicleAdd', (v, id) => this.vehicles?.addVehicle(v, id));+ this.net.on('vehicleChange', (v, id) => this.vehicles?.changeVehicle(v, id));+ this.net.on('vehicleRemove', (id) => this.vehicles?.removeVehicle(id));+ this.net.on('vehicle', (msg) => this.vehicles?.onAck(msg));this.net.on('blockAdd', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); this._syncBudget(); });this.net.on('blockChange', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); });this.net.on('blockRemove', (key) => { const [x, y, z] = parseKey(key); this.voxels?.removeBlock(x, y, z); this._syncBudget(); });@@ -1099,6 +1111,12 @@ export class CoinCommunities {this.phase = 'world';this._initJoystick();this._onboardBuild();+ // W02: drivable vehicles — the parked fleet the server seeds every world+ // with (multiplayer/src/vehicles.js VEHICLE_SPAWNS, mirrored from this+ // district's own avenue bays in world-zones.js). Constructed after the+ // physics boot above has resolved, so it can borrow this._physics straight+ // away instead of waiting on it itself. Torn down in leave().+ this.vehicles = new VehicleManager({ host: this });// Every town hosts the live Agent Exchange: two NPC agents who pay each// other on-chain via x402. Torn down in leave().this.agentCommerce = new AgentCommerce({@@ -1388,6 +1406,7 @@ export class CoinCommunities {this._passRefreshTimer = null;if (this.voice) { this.voice.dispose(); this.voice = null; }if (this.net) { this.net.destroy(); this.net = null; }+ if (this.vehicles) { this.vehicles.dispose(); this.vehicles = null; }if (this.playSystems) { this.playSystems.dispose(); this.playSystems = null; }if (this.agentCommerce) { this.agentCommerce.dispose(); this.agentCommerce = null; }if (this.intelKiosk) { this.intelKiosk.dispose(); this.intelKiosk = null; }@@ -2144,7 +2163,14 @@ export class CoinCommunities {window.addEventListener('keydown', (e) => {if (this.ui.chatFocused) return;if (e.key === 'Enter' && this.phase === 'world') { e.preventDefault(); this.ui.focusChat(); return; }- if (e.code === 'Space') { e.preventDefault(); this._jump(); return; } // don't scroll the page+ // Space jumps on foot; while driving it's the handbrake instead (held,+ // released in the keyup handler below) — never scrolls the page either way.+ if (e.code === 'Space') {+ e.preventDefault();+ if (this.vehicles?.isDriving()) { this.vehicles.setHandbrake(true); return; }+ this._jump();+ return;+ }const k = e.key.toLowerCase();if (this.phase === 'world') {// B toggles build mode; while it's on, 1–0 pick the active block.@@ -2184,11 +2210,13 @@ export class CoinCommunities {if (!this.worldLife?.interact() && !this.intelKiosk?.interact()) this.agentCommerce?.interact();return;}- // F casts a line when standing by a pond (no-op elsewhere). Not while+ // F is contextual: enter/exit a nearby vehicle takes priority (the+ // on-screen prompt already says "F — Drive" / "F — Exit"); otherwise it+ // casts a line when standing by a pond (no-op elsewhere). Not while// building, where keys drive the block palette.if (k === 'f' && !this.buildHud.active) {e.preventDefault();- this.playSystems?.castFish();+ if (!this.vehicles?.interact()) this.playSystems?.castFish();return;}// I inspects the nearest avatar — player, townsperson, or yourself:@@ -2227,6 +2255,8 @@ export class CoinCommunities {});window.addEventListener('keyup', (e) => {const k = e.key.toLowerCase();+ // Space release: let go of the handbrake (harmless no-op when not driving).+ if (e.code === 'Space') this.vehicles?.setHandbrake(false);// Q release: if the wheel opened via hold, close it and play the selected clip.if (k === 'q' && this.phase === 'world') {clearTimeout(this._ewHoldTimer);@@ -2259,6 +2289,11 @@ export class CoinCommunities {if (consumed) return; // a hold already broke a block — don't also placeif (moved >= 6 || e.button === 2) return; // a look-drag, or a right-click (handled by contextmenu)if (this.phase === 'world' && this.buildHud.active) { this._buildAt(e.clientX, e.clientY, false); return; }+ // Tap a nearby parked vehicle to take the wheel — the touch-native+ // equivalent of pressing F. Checked first: it only ever fires when a+ // vehicle is both in range and under the tap, so it can't shadow the+ // other tap targets below.+ if (this.vehicles?.tryActivateAt(this._pointerRay(e.clientX, e.clientY))) return;// Tap the agents (or their exchange ring) to watch a live payment — the// touch-native equivalent of pressing E. Checked before the chart screen.if (this.worldLife?.tryActivateAt(e.clientX, e.clientY)) return;@@ -2968,11 +3003,20 @@ export class CoinCommunities {this._last = now;if (this.phase === 'world') {- this._stepLocal(dt);- // Step the Rapier world AFTER _stepLocal so it consumes the character's- // queued kinematic move from this same frame (and advances any dynamic- // props/vehicles later briefs add).+ // W02: while driving, the vehicle IS the local player's movement — skip+ // the on-foot character step (it would fight the car for localPos every+ // frame) and let VehicleManager feed this frame's throttle/steer/brake+ // into the Rapier vehicle controller instead.+ const driving = this.vehicles?.isDriving();+ if (driving) this.vehicles.tick(dt);+ else { this._stepLocal(dt); this.vehicles?.tick(dt); }+ // Step the Rapier world AFTER _stepLocal/vehicle input so it consumes the+ // character's queued kinematic move (or the vehicle's driver intent) from+ // this same frame, and advances every kinematic ghost of a remote vehicle.if (this._physicsOk && this._physics) this._physics.step(dt);+ // Read back the vehicle's post-step transform (mesh, camera, seat, HUD,+ // netcode) now that the world has actually advanced.+ if (driving) this.vehicles.postStep(dt);this._checkFloorOccupancy();this.localAnim?.update(dt);this.localCosmetics?.tick(dt);@@ -2985,7 +3029,10 @@ export class CoinCommunities {this.agentCommerce?.tick(dt);this.intelKiosk?.tick(dt);if (this.worldLife) { this.worldLife.setRealPeers(this.remotes.size); this.worldLife.tick(dt); }- if (this.net) this.net.sendMove({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, motion: this.motion });+ // Ordinary move sync is redundant (and would just get rejected by the+ // server's walking-speed step clamp) while driving — VehicleManager+ // streams the authoritative transform itself via sendVSync.+ if (this.net && !driving) this.net.sendMove({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, motion: this.motion });// Gamepad: north button (Y/△, 3) opens the emote wheel; once open, the left// stick steers and the south button (A/✕, 0) plays the selected clip. Edge-// detect the open button so holding it doesn't reopen on the frame it closes.diff --git a/src/game/vehicles.js b/src/game/vehicles.jsindex 401c1bf5c..2373916cf 100644--- a/src/game/vehicles.js+++ b/src/game/vehicles.js@@ -7,18 +7,24 @@// and relays it, staying the gate on who may drive what. Everyone else is a pure// spectator of the replicated transform, interpolated smoothly.//-// Only the vehicle the local player is driving is ever simulated here — a single-// Rapier world holds the ground, the central totem, and (as kinematic ghosts) the-// other players' cars so the local car can bump them. Parked and remote-driven-// vehicles are interpolated meshes, cheap and ghost-light.+// Only the vehicle the local player is driving is ever simulated here — it shares+// the SAME Rapier world CoinCommunities already boots for the character+// controller (W01's `this._physics`: ground + district building colliders), so a+// driven car collides with the town exactly like a walking avatar does, and+// (as kinematic ghosts) the other players' cars so the local car can bump them.+// The world is stepped exactly once per frame, centrally, in CoinCommunities'+// _loop — this module never calls physics.step() itself; tick() feeds driver+// input BEFORE that step, postStep() reads the resulting transform AFTER it.+// Parked and remote-driven vehicles are interpolated meshes, cheap and+// ghost-light.//// This subsystem is intentionally tightly coupled to the scene (camera handoff,-// avatar seating, shared input), so it takes the CoinCommunities `host` and reads-// its live fields (localPos, localYaw, localRig, keys, camera) — exactly the-// coupling PlaySystems and AgentCommerce already have.+// avatar seating, shared input, the shared physics world), so it takes the+// CoinCommunities `host` and reads its live fields (localPos, localYaw, localRig,+// keys, camera, _physics) — exactly the coupling PlaySystems and AgentCommerce+// already have.import { Vector3, Quaternion, Raycaster, Vector2 } from 'three';-import { PhysicsWorld } from '../physics/physics-world.js';import { buildVehicleMesh } from './vehicle-mesh.js';import { CLIP_IDLE } from './avatar-rig.js';import {@@ -65,20 +71,15 @@ export class VehicleManager {this._flipSince = 0;this._prevCamDist = host.camDist;- // One physics world for the local driver: flat ground + the central totem as- // an obstacle. Created up-front so Rapier's WASM is warm by the time the- // player reaches a car. Failure (no WebGL/WASM) leaves driving disabled, not- // the whole scene broken.- this.phys = null;- this._physReady = PhysicsWorld.create({ gravity: { x: 0, y: -18, z: 0 } })- .then((p) => {- p.addGround(0, 400);- // The coin totem sits at (0,0,-12); make it solid so cars can't drive- // through the landmark.- p.addStaticCylinder({ position: { x: 0, y: 3, z: -12 }, radius: 1.6, halfHeight: 3.2 });- this.phys = p;- })- .catch((err) => { log.warn('[vehicles] physics init failed:', err?.message); });+ // Reuse CoinCommunities' own Rapier world (ground + district colliders ++ // character controller) instead of standing up a second one — the driven+ // car then collides with the same town the avatar does. host.enter() only+ // constructs VehicleManager after its physics boot has already resolved, so+ // this is synchronous; a WASM failure (no WebGL/WASM) leaves `phys` null,+ // which disables driving gracefully (toast on interact) without breaking+ // the rest of the scene.+ this.phys = host._physicsOk ? host._physics : null;+ if (!this.phys) log.warn('[vehicles] no shared physics world — driving disabled this session.');this._injectStyles();this._buildPrompt();@@ -146,22 +147,33 @@ export class VehicleManager {isDriving() { return !!this._drivingId; }+ // Called BEFORE CoinCommunities steps the shared physics world this frame:+ // interpolates every vehicle we're not actively simulating (and re-queues+ // their kinematic ghost transforms, which — like the character controller's+ // queued move — must be set before world.step() consumes them), and, while+ // driving, feeds this frame's input into the Rapier vehicle controller so its+ // forces are ready for that same step. Reading the result back happens in+ // postStep(), after the world has actually advanced.tick(dt) {- // Interpolate every vehicle we're not actively simulating, and keep their- // kinematic ghosts (for the local car to collide with) in step.for (const [, entry] of this.vehicles) {if (entry.id === this._drivingId) continue;this._interpolate(entry, dt);}if (this._drivingId) {- this._drive(dt);+ this._driveInput(dt);} else {this._updatePrompt();this._pedestrianKnock(dt);}}+ // Called AFTER CoinCommunities steps the shared physics world this frame.+ // No-op unless actively driving.+ postStep(dt) {+ if (this._drivingId) this._driveApply(dt);+ }+_interpolate(entry, dt) {const s = entry.state;const g = entry.mesh.group;@@ -209,11 +221,10 @@ export class VehicleManager {// ---------------------------------------------------------------- driving sim- _drive(dt) {- const entry = this.vehicles.get(this._drivingId);- if (!entry || !this.vehicle || !this.phys) return;-- // Gather intent: keyboard (WASD / arrows / space) + on-screen touch controls.+ // Pre-step: feed this frame's driver intent to the Rapier vehicle controller.+ // Nothing here reads back a transform — the shared world hasn't advanced yet.+ _driveInput(dt) {+ if (!this.vehicle || !this.phys) return;const keys = this.host.keys;let throttle = (keys.has('w') || keys.has('arrowup')) ? 1 : 0;let brake = (keys.has('s') || keys.has('arrowdown')) ? 1 : 0;@@ -225,9 +236,16 @@ export class VehicleManager {steer = Math.max(-1, Math.min(1, steer + this._touch.steer));const handbrake = this._kbHandbrake || this._touch.handbrake;this.vehicle.setInput({ throttle, brake, steer, handbrake });+ this._lastBraking = brake > 0 || handbrake; // read back in _driveApply+ }- // Step the simulation, then read the authoritative-for-us transform.- this.phys.step(dt);+ // Post-step: the shared world just advanced (CoinCommunities._loop calls this+ // right after physics.step()) — read the now-authoritative transform and apply+ // everything downstream of it: mesh, camera, seat, HUD, netcode.+ _driveApply(dt) {+ const entry = this.vehicles.get(this._drivingId);+ if (!entry || !this.vehicle || !this.phys) return;+ const braking = this._lastBraking;let t = this.vehicle.transform();// World bounds — clamp the car inside the square district (the server clamps@@ -253,7 +271,6 @@ export class VehicleManager {g.quaternion.set(t.qx, t.qy, t.qz, t.qw);this._updateDrivenWheels(entry);// Brake-light glow when slowing or reversing.- const braking = brake > 0 || handbrake;for (const bl of entry.mesh.brakeLights) bl.material.color.setHex(braking ? 0xff3b30 : 0x6e1411);// Seat the avatar, hand the camera to a chase view, and carry the player's@@ -365,11 +382,14 @@ export class VehicleManager {clearTimeout(this._pendingTimer);}- async _beginDriving(id) {+ _beginDriving(id) {this._clearPending();- await this._physReady;const entry = this.vehicles.get(id);- if (!entry || !this.phys) return;+ if (!entry) return;+ if (!this.phys) {+ this.ui?.toast?.('Vehicles need real-time physics, which failed to load this session.', 'warn');+ return;+ }// Another change may have arrived; re-confirm the server seated us.if (entry.state.driver && entry.state.driver !== this.net?.sessionId) return;@@ -432,6 +452,11 @@ export class VehicleManager {this.host.localRig.position.copy(this.host.localPos);this.host.localRig.rotation.set(0, this.host.localYaw, 0);}+ // The shared character controller's kinematic body was left wherever the+ // player stood before entering — resync it to the drop point (the same+ // flag CoinCommunities sets on a fresh coin spawn) so the next _stepLocal+ // re-seeds it there instead of resolving a stale move from the old spot.+ this.host._physicsActivePrev = false;if (serverForced && t === null) this.ui?.toast?.('You were removed from the vehicle.', 'warn');}@@ -516,6 +541,10 @@ export class VehicleManager {this._hud?.classList.toggle('veh-driving', on);this._hud?.classList.toggle('veh-touch', on && this._isTouch());if (!on) this._touch = { throttle: 0, brake: 0, steer: 0, handbrake: false };+ // The on-foot movement joystick (#cc-joystick) sits in the same bottom-left+ // corner as the steering pad and renders above it (z-index 30 vs our 22) —+ // hide it while driving so it doesn't block the wheel.+ document.getElementById('cc-joystick')?.classList.toggle('veh-hide-joy', on);}_injectStyles() {@@ -523,6 +552,7 @@ export class VehicleManager {const s = document.createElement('style');s.id = 'veh-styles';s.textContent = `+ .veh-hide-joy { display: none !important; }.veh-prompt {position: fixed; left: 0; top: 0; z-index: 16; pointer-events: none;transform: translate(-50%, -100%); white-space: nowrap; display: none;@@ -585,7 +615,8 @@ export class VehicleManager {this.vehicles.clear();this.prompt?.remove();this._hud?.remove();- this._physReady?.then?.(() => this.phys?.dispose());- if (this.phys) { this.phys.dispose(); this.phys = null; }+ // `phys` is CoinCommunities' own shared world — owned and disposed by the+ // host, not us. Just drop our reference.+ this.phys = null;}}diff --git a/src/privy-login.js b/src/privy-login.jsindex 30b2c33a8..d7f6915f3 100644--- a/src/privy-login.js+++ b/src/privy-login.js@@ -129,6 +129,19 @@ async function verifyWithBackend(identity_token) {location.href = next;}+// ── Timeout helper ─────────────────────────────────────────────────────────+// window.ethereum.request()/Solana provider calls have no network-layer+// timeout — a dead or reconnecting extension background port can leave the+// promise permanently unsettled, stranding the button in "Connecting…" with+// the catch block that resets it never firing.+function withTimeout(promise, ms, message) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(message)), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}+// ── Solana wallet detection ───────────────────────────────────────────────────function getSolanaProvider() {@@ -277,28 +290,41 @@ function mountPrivyUI(privy, captchaConfigPromise) {clearErr();try {- const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });+ const accounts = await withTimeout(+ window.ethereum.request({ method: 'eth_requestAccounts' }),+ 60_000,+ 'Wallet connection timed out. Check your wallet extension and try again.',+ );const address = accounts[0];if (!address) throw new Error('No account returned from wallet.');- const chainIdHex = await window.ethereum.request({ method: 'eth_chainId' });+ const chainIdHex = await withTimeout(+ window.ethereum.request({ method: 'eth_chainId' }),+ 10_000,+ 'Wallet did not respond. Try again.',+ );const chainId = parseInt(chainIdHex, 16);setWalletStatus('Generating sign-in message…');- const { message } = await privy.auth.siwe.init(- { address, chainId },- location.hostname,- location.origin,+ const { message } = await withTimeout(+ privy.auth.siwe.init({ address, chainId }, location.hostname, location.origin),+ 15_000,+ 'Could not reach the sign-in service. Try again.',);setWalletStatus('Sign the message in your wallet…');- const signature = await window.ethereum.request({- method: 'personal_sign',- params: [message, address],- });+ const signature = await withTimeout(+ window.ethereum.request({ method: 'personal_sign', params: [message, address] }),+ 60_000,+ 'Signature timed out. Check your wallet extension and try again.',+ );setWalletStatus('Signing in…');- const { identity_token } = await privy.auth.siwe.loginWithSiwe(signature);+ const { identity_token } = await withTimeout(+ privy.auth.siwe.loginWithSiwe(signature),+ 15_000,+ 'Could not reach the sign-in service. Try again.',+ );if (!identity_token) throw new Error('No identity token returned.');await verifyWithBackend(identity_token);@@ -324,7 +350,11 @@ function mountPrivyUI(privy, captchaConfigPromise) {clearErr();try {- const resp = await provider.connect();+ const resp = await withTimeout(+ provider.connect(),+ 60_000,+ 'Wallet connection timed out. Check your wallet extension and try again.',+ );const address = resp.publicKey.toString();setWalletStatus('Generating sign-in message…');@@ -351,9 +381,10 @@ function mountPrivyUI(privy, captchaConfigPromise) {].join('\n');setWalletStatus('Sign the message in your wallet…');- const { signature: sigBytes } = await provider.signMessage(- new TextEncoder().encode(message),- 'utf8',+ const { signature: sigBytes } = await withTimeout(+ provider.signMessage(new TextEncoder().encode(message), 'utf8'),+ 60_000,+ 'Signature timed out. Check your wallet extension and try again.',);const signature = btoa(String.fromCharCode(...sigBytes));diff --git a/src/restyle.js b/src/restyle.jsindex e55bfe9d1..d33177eba 100644--- a/src/restyle.js+++ b/src/restyle.js@@ -67,7 +67,7 @@ function init() {buildPresetButtons();wireControls();const url = new URL(location.href).searchParams.get('url');- loadModel(url || DEFAULT_MODEL, url ? 'from URL' : 'sample', { originUrl: url || DEFAULT_MODEL });+ loadModel(url || DEFAULT_MODEL, url ? 'from URL' : 'sample', { originUrl: absoluteUrl(url || DEFAULT_MODEL) });window.addEventListener('resize', onResize);}@@ -649,7 +649,7 @@ function wireControls() {el['save-variants'].addEventListener('click', persistVariants);el.reset.addEventListener('click', resetModel);el.export.addEventListener('click', exportModel);- el.retry.addEventListener('click', () => loadModel(DEFAULT_MODEL, 'sample', { originUrl: DEFAULT_MODEL }));+ el.retry.addEventListener('click', () => loadModel(DEFAULT_MODEL, 'sample', { originUrl: absoluteUrl(DEFAULT_MODEL) }));el['ai-restyle'].addEventListener('click', aiRestyle);el['ai-instruction'].addEventListener('keydown', (e) => {if (e.key === 'Enter') aiRestyle();@@ -765,6 +765,18 @@ function clampInt(n, lo, hi) {function clamp01(n) {return Math.min(1, Math.max(0, Number(n) || 0));}+// Resolve a possibly-relative URL (e.g. the local /avatars/*.glb sample) to an+// absolute https URL against the current origin — api/material-studio.js's SSRF+// guard requires a real, publicly resolvable https URL, so a bare path like+// "/avatars/realistic-female.glb" must become "https://three.ws/avatars/..."+// before it's ever sent as glb_url.+function absoluteUrl(u) {+ try {+ return new URL(u, location.href).href;+ } catch {+ return u;+ }+}function escapeHtml(s) {return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));}diff --git a/src/wallet/connect-button.js b/src/wallet/connect-button.jsindex 0edca5057..c791ff3f7 100644--- a/src/wallet/connect-button.js+++ b/src/wallet/connect-button.js@@ -29,6 +29,17 @@ const ASYNC_STATES = new Set([STATES.VERIFYING,]);+// window.ethereum.request() has no network-layer timeout — a dead or+// reconnecting extension background port can leave the promise permanently+// unsettled, stranding the button in its connecting state forever.+function withTimeout(promise, ms, message) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(message)), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}+/*** Build the EIP-4361 SIWE message string.* Format must match the parser in api/auth/siwe/verify.js exactly.@@ -219,7 +230,11 @@ export class ConnectWalletController extends EventTarget {try {const provider = new BrowserProvider(window.ethereum);- await provider.send('eth_requestAccounts', []);+ await withTimeout(+ provider.send('eth_requestAccounts', []),+ 60_000,+ 'Wallet connection timed out. Check your wallet extension and try again.',+ );const signer = await provider.getSigner();const address = await signer.getAddress();const network = await provider.getNetwork();diff --git a/tests/openapi-aggregator.test.js b/tests/openapi-aggregator.test.jsnew file mode 100644index 000000000..fed9b496b--- /dev/null+++ b/tests/openapi-aggregator.test.js@@ -0,0 +1,115 @@+// Tests for GET /openapi.json's aggregator coverage: every endpoint registered+// in api/v1/_providers.js (providerCatalog()) must show up as a real OpenAPI+// path/operation, generated live (never hand-enumerated) — see+// api/openapi-json.js `aggregatorPaths()`. Also guards the pre-existing+// hand-authored /api/mcp, /api/x402/* etc. paths stay intact.++import { describe, it, expect, beforeAll } from 'vitest';+import openapiHandler from '../api/openapi-json.js';+import { providerCatalog } from '../api/v1/_providers.js';++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ setHeader(k, v) {+ this._headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._headers[k.toLowerCase()];+ },+ end(b) {+ this._body = b || '';+ },+ get headersSent() {+ return false;+ },+ get writableEnded() {+ return false;+ },+ };+}++function mockReq() {+ return {+ method: 'GET',+ url: '/openapi.json',+ headers: { accept: 'application/json', origin: 'https://three.ws' },+ socket: { remoteAddress: '127.0.0.1' },+ };+}++describe('GET /openapi.json — aggregator coverage', () => {+ let doc;++ beforeAll(async () => {+ const res = mockRes();+ await openapiHandler(mockReq(), res);+ expect(res.statusCode).toBe(200);+ // Body must be valid JSON — a parse failure here means the document is+ // broken, not just incomplete.+ doc = JSON.parse(res._body);+ });++ it('is a well-formed OpenAPI 3.1 document', () => {+ expect(doc.openapi).toBe('3.1.0');+ expect(doc.info?.title).toBeTruthy();+ expect(typeof doc.paths).toBe('object');+ expect(Array.isArray(doc.servers)).toBe(true);+ });++ it('declares the aggregator tag', () => {+ const tagNames = (doc.tags || []).map((t) => t.name);+ expect(tagNames).toContain('Crypto API (aggregator)');+ });++ it('covers every registered aggregator endpoint with a real path + operation', () => {+ const catalog = providerCatalog();+ let total = 0;+ for (const provider of catalog) {+ for (const ep of provider.endpoints) {+ total += 1;+ const pathItem = doc.paths[ep.path];+ expect(pathItem, `missing OpenAPI path for ${ep.path}`).toBeTruthy();++ const operation = pathItem[ep.method.toLowerCase()];+ expect(operation, `missing ${ep.method} operation for ${ep.path}`).toBeTruthy();+ expect(operation.tags).toContain('Crypto API (aggregator)');+ expect(operation.summary).toContain(provider.name);+ expect(operation.responses?.['402']).toBeTruthy();++ // Price in the OpenAPI doc must match the registry's priceAtomics,+ // not a hand-copied number that can drift.+ const expectedUsd = (Number(ep.price_usdc_atomics) / 1e6).toString();+ const declaredUsd = operation['x-payment-info']?.price?.amount;+ expect(Number(declaredUsd)).toBeCloseTo(Number(expectedUsd), 6);++ if (ep.method === 'GET') {+ expect(Array.isArray(operation.parameters)).toBe(true);+ // Every documented "(required)" param must be flagged required.+ for (const [name, desc] of Object.entries(ep.params || {})) {+ const param = operation.parameters.find((p) => p.name === name);+ expect(param, `missing OpenAPI param "${name}" for ${ep.path}`).toBeTruthy();+ expect(param.required).toBe(/\(required\)/.test(desc));+ }+ } else {+ expect(operation.requestBody).toBeTruthy();+ }+ }+ }+ // Sanity: the registry isn't empty (would make this test vacuous).+ expect(total).toBeGreaterThan(10);+ });++ it('still carries the hand-authored, non-aggregator paths', () => {+ expect(doc.paths['/api/mcp']).toBeTruthy();+ expect(doc.paths['/api/x402/skill-marketplace']).toBeTruthy();+ });++ it('free-tier endpoints note their quota in x-payment-info', () => {+ const priced = doc.paths['/api/v1/x/coingecko/price']?.get;+ expect(priced['x-payment-info'].note).toMatch(/30\/min/);+ expect(priced['x-payment-info'].note).toMatch(/2000\/day/);+ });+});diff --git a/tests/vanity-premium-inventory.test.js b/tests/vanity-premium-inventory.test.jsindex 17fa03da5..3a24907ed 100644--- a/tests/vanity-premium-inventory.test.js+++ b/tests/vanity-premium-inventory.test.js@@ -25,6 +25,8 @@ import { sealSecret, openSecret, preferredScheme, SCHEME_SECRETBOX } from '../apimport { priceFromRarity, priceForPattern, MIN_PRICE_USD, MAX_PRICE_USD } from '../api/_lib/vanity-inventory-pricing.js';import { computeRarity } from '../src/solana/vanity/rarity.js';import { grindToCompletion } from '../workers/vanity-grinder/wasm-grind.mjs';+import { tryInstantFromInventory, priceAtomicsFor } from '../api/x402/vanity.js';+import { claimVanityMintFromInventory } from '../api/_lib/pump-launch.js';describe('vanity-vault: seal/open', () => {it('round-trips a secret and never stores plaintext', async () => {@@ -139,3 +141,180 @@ describe.skipIf(!HAS_DB)('vanity-inventory-store: single-use delivery (needs DATexpect(pub.status).toBe('destroyed');});});++// ── DB-gated: instant inventory — live-grind + pump-launch upsell ───────────+// Covers the wiring in api/x402/vanity.js (tryInstantFromInventory) and+// api/_lib/pump-launch.js (claimVanityMintFromInventory): an inventory hit is+// served instantly (no grinding) and consumed exactly once; a miss returns+// null so the caller falls straight through to its existing live-grind path,+// unchanged.+const BASE58_CHARS = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+function randPrefix(n = 2) {+ let s = '';+ for (let i = 0; i < n; i++) s += BASE58_CHARS[Math.floor(Math.random() * BASE58_CHARS.length)];+ return s;+}++// Grinds a real keypair matching `prefix`, seals it, and inserts it as an+// available inventory item — the same shape workers/vanity-grinder produces.+async function seedInventoryItem(store, { prefix, ignoreCase = true, priceUsd = 0.01 }) {+ const g = grindToCompletion({ prefix, ignoreCase }, { maxAttempts: 5_000_000 });+ expect(g.status).toBe('found');+ const kp = Keypair.fromSecretKey(g.secretKey);+ const address = kp.publicKey.toBase58();+ const { ciphertext, scheme } = await sealSecret(+ JSON.stringify({ format: 'keypair', address, secretKeyBase58: bs58.encode(kp.secretKey), secretKey: Array.from(kp.secretKey) }),+ );+ await store.upsertInventoryItem({+ address, patternLabel: prefix, prefix, suffix: null, ignoreCase,+ difficultyAttempts: g.attempts, rarityBits: 6, rarityTier: 'uncommon', rarityScore: 600,+ secretCiphertext: ciphertext, secretScheme: scheme, priceUsd, retentionDays: 0,+ });+ return address;+}++describe.skipIf(!HAS_DB)('instant inventory: live-grind + pump-launch upsell (needs DATABASE_URL)', () => {+ it('claimMatchingPattern: an instant hit is consumed — a second claim of the same pattern gets no_match', async () => {+ const store = await import('../api/_lib/vanity-inventory-store.js');+ const prefix = randPrefix(2);+ const address = await seedInventoryItem(store, { prefix, priceUsd: 0.01 });++ const first = await store.claimMatchingPattern({+ prefix, ignoreCase: true, format: 'keypair', maxPriceUsd: 0.05, paymentId: 'claim-a-' + prefix, purchaser: 'tester',+ });+ expect(first.ok).toBe(true);+ expect(first.item.address).toBe(address);++ // Same pattern, different payment — the item is already reserved, so no+ // second buyer can claim (or ever be served) the same address.+ const second = await store.claimMatchingPattern({+ prefix, ignoreCase: true, format: 'keypair', maxPriceUsd: 0.05, paymentId: 'claim-b-' + prefix, purchaser: 'tester2',+ });+ expect(second.ok).toBe(false);+ expect(second.reason).toBe('no_match');++ // Finalize like the endpoint does after settle — reveal destroys it.+ const revealed = await store.reserveAndReveal(address, { paymentId: 'claim-a-' + prefix });+ expect(revealed.ok).toBe(true);+ expect(revealed.destroyed).toBe(true);+ });++ it('claimMatchingPattern: two concurrent claims for the last matching row — exactly one wins', async () => {+ const store = await import('../api/_lib/vanity-inventory-store.js');+ const prefix = randPrefix(2);+ const address = await seedInventoryItem(store, { prefix, priceUsd: 0.01 });++ const [a, b] = await Promise.all([+ store.claimMatchingPattern({ prefix, ignoreCase: true, format: 'keypair', paymentId: 'race-a-' + prefix, purchaser: 'a' }),+ store.claimMatchingPattern({ prefix, ignoreCase: true, format: 'keypair', paymentId: 'race-b-' + prefix, purchaser: 'b' }),+ ]);+ const winners = [a, b].filter((r) => r.ok);+ const losers = [a, b].filter((r) => !r.ok);+ expect(winners).toHaveLength(1);+ expect(losers).toHaveLength(1);+ expect(winners[0].item.address).toBe(address);+ expect(losers[0].reason).toBe('no_match');++ // Clean up: finalize the winning reservation so no row is left stranded+ // in 'reserved' status.+ const winnerPaymentId = a.ok ? 'race-a-' + prefix : 'race-b-' + prefix;+ await store.reserveAndReveal(address, { paymentId: winnerPaymentId });+ });++ it('claimMatchingPattern: no matching item returns no_match without throwing (the grind-fallback signal)', async () => {+ const store = await import('../api/_lib/vanity-inventory-store.js');+ const miss = await store.claimMatchingPattern({+ prefix: randPrefix(4), ignoreCase: true, format: 'keypair', paymentId: 'miss-' + randPrefix(4),+ });+ expect(miss.ok).toBe(false);+ expect(miss.reason).toBe('no_match');+ });++ it('claimMatchingPattern: maxPriceUsd keeps a premium item out of the cheap live-grind tier', async () => {+ const store = await import('../api/_lib/vanity-inventory-store.js');+ const prefix = randPrefix(2);+ const address = await seedInventoryItem(store, { prefix, priceUsd: 10 });++ // The live-grind tier's ceiling for a 2-char pattern ($0.05) must not match+ // a $10 item — it stays reserved for the priced premium tier.+ const capped = await store.claimMatchingPattern({+ prefix, ignoreCase: true, format: 'keypair', maxPriceUsd: 0.05, paymentId: 'cap-' + prefix,+ });+ expect(capped.ok).toBe(false);+ expect(capped.reason).toBe('no_match');++ // Without (or above) the price ceiling, the same item is claimable.+ const uncapped = await store.claimMatchingPattern({+ prefix, ignoreCase: true, format: 'keypair', maxPriceUsd: 10, paymentId: 'uncap-' + prefix,+ });+ expect(uncapped.ok).toBe(true);+ expect(uncapped.item.address).toBe(address);++ // Clean up: finalize the reservation so no row is left stranded.+ await store.reserveAndReveal(address, { paymentId: 'uncap-' + prefix });+ });++ it('tryInstantFromInventory (api/x402/vanity.js): serves an inventory hit instantly with source=inventory, then consumes it', async () => {+ const store = await import('../api/_lib/vanity-inventory-store.js');+ const prefix = randPrefix(2);+ const address = await seedInventoryItem(store, { prefix, priceUsd: 0.01 });+ const pattern = { prefix, suffix: '', ignoreCase: true, format: 'keypair', combinedLength: prefix.length, sealTo: null };+ expect(priceAtomicsFor('keypair', prefix.length)).toBeGreaterThanOrEqual(10_000); // sanity: $0.01 item is within the tier's ceiling++ const hit = await tryInstantFromInventory(pattern, { paymentId: 'vinv-' + prefix, purchaser: 'tester' });+ expect(hit).toBeTruthy();+ expect(hit.result.source).toBe('inventory');+ expect(hit.result.address).toBe(address);+ expect(hit.result.secretKeyBase58).toBeTruthy();+ // The delivered secret key actually reconstructs the vanity address.+ const restored = Keypair.fromSecretKey(bs58.decode(hit.result.secretKeyBase58));+ expect(restored.publicKey.toBase58()).toBe(address);++ // Finalize (what the endpoint does after settle) — the item is now gone.+ await store.reserveAndReveal(address, { paymentId: 'vinv-' + prefix });+ const again = await tryInstantFromInventory(pattern, { paymentId: 'vinv2-' + prefix, purchaser: 'tester' });+ expect(again).toBeNull();+ });++ it('tryInstantFromInventory (api/x402/vanity.js): no match returns null so the caller falls through to grind', async () => {+ const pattern = { prefix: randPrefix(4), suffix: '', ignoreCase: true, format: 'keypair', combinedLength: 4, sealTo: null };+ const miss = await tryInstantFromInventory(pattern, { paymentId: 'vmiss-' + pattern.prefix, purchaser: 'tester' });+ expect(miss).toBeNull();+ });++ it('claimVanityMintFromInventory (api/_lib/pump-launch.js): delivers a usable mint keypair instantly, then consumes it', async () => {+ const store = await import('../api/_lib/vanity-inventory-store.js');+ const prefix = randPrefix(2);+ const address = await seedInventoryItem(store, { prefix, priceUsd: 0.01 });++ const claim = await claimVanityMintFromInventory({ prefix, ignoreCase: true, paymentId: 'pl-' + prefix, purchaser: 'tester' });+ expect(claim).toBeTruthy();+ expect(claim.address).toBe(address);+ expect(claim.mintKeypair.publicKey.toBase58()).toBe(address);++ // Simulates a successful on-chain launch: finalize the claim.+ await claim.reveal();+ const again = await claimVanityMintFromInventory({ prefix, ignoreCase: true, paymentId: 'pl2-' + prefix, purchaser: 'tester' });+ expect(again).toBeNull();+ });++ it('claimVanityMintFromInventory: release() puts a failed-launch claim back to available for reuse', async () => {+ const store = await import('../api/_lib/vanity-inventory-store.js');+ const prefix = randPrefix(2);+ const address = await seedInventoryItem(store, { prefix, priceUsd: 0.01 });++ const claim = await claimVanityMintFromInventory({ prefix, ignoreCase: true, paymentId: 'plr-' + prefix, purchaser: 'tester' });+ expect(claim).toBeTruthy();++ // Simulates a launch failure BEFORE the mint touched the chain.+ await claim.release();+ const pub = await store.getPublicItem(address);+ expect(pub.status).toBe('available');++ // Now claimable again.+ const retry = await claimVanityMintFromInventory({ prefix, ignoreCase: true, paymentId: 'plr2-' + prefix, purchaser: 'tester' });+ expect(retry).toBeTruthy();+ expect(retry.address).toBe(address);+ await retry.reveal();+ });+});diff --git a/vercel.json b/vercel.jsonindex 126699d18..ebe43f8e1 100644--- a/vercel.json+++ b/vercel.json@@ -249,6 +249,14 @@"src": "/crypto/","dest": "/crypto.html"},+ {+ "src": "/crypto-api",+ "dest": "/crypto-api.html"+ },+ {+ "src": "/crypto-api/",+ "dest": "/crypto-api.html"+ },{"src": "/3d","dest": "/3d.html"@@ -969,6 +977,10 @@"src": "/bnb/?","dest": "/bnb.html"},+ {+ "src": "/bnb-latency/?",+ "dest": "/bnb-latency.html"+ },{"src": "/coin/([a-zA-Z0-9][a-zA-Z0-9_-]{0,99})/?","dest": "/coin.html"@@ -5144,6 +5156,10 @@{"path": "/api/cron/wallets-leak-scan","schedule": "*/15 * * * *"+ },+ {+ "path": "/api/cron/vanity-inventory-replenish",+ "schedule": "0 * * * *"}]}diff --git a/vite.config.js b/vite.config.jsindex 724c6495a..9c43d19be 100644--- a/vite.config.js+++ b/vite.config.js@@ -459,6 +459,7 @@ const appConfig = {chains: resolve(__dirname, 'pages/chains.html'),stablecoins: resolve(__dirname, 'pages/stablecoins.html'),bnb: resolve(__dirname, 'pages/bnb.html'),+ 'bnb-latency': resolve(__dirname, 'pages/bnb-latency.html'),trending: resolve(__dirname, 'pages/trending.html'),compose: resolve(__dirname, 'pages/compose.html'),'create-next': resolve(__dirname, 'pages/create-next.html'),@@ -468,6 +469,7 @@ const appConfig = {autopilot: resolve(__dirname, 'pages/autopilot.html'),'pump-visualizer': resolve(__dirname, 'pages/pump-visualizer.html'),crypto: resolve(__dirname, 'pages/crypto.html'),+ 'crypto-api': resolve(__dirname, 'pages/crypto-api.html'),three: resolve(__dirname, 'pages/three.html'),'three-live': resolve(__dirname, 'pages/three-live.html'),'three-token': resolve(__dirname, 'pages/three-token.html'),@@ -1003,6 +1005,8 @@ support: resolve(__dirname, 'pages/support.html'),'/stablecoins/': resolve(root, 'pages/stablecoins.html'),'/bnb': resolve(root, 'pages/bnb.html'),'/bnb/': resolve(root, 'pages/bnb.html'),+ '/bnb-latency': resolve(root, 'pages/bnb-latency.html'),+ '/bnb-latency/': resolve(root, 'pages/bnb-latency.html'),'/compose': resolve(root, 'pages/compose.html'),'/compose/': resolve(root, 'pages/compose.html'),'/create/next': resolve(root, 'pages/create-next.html'),