Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(bnb-vault): vault UI (/vault) — browse, buy, unlock, view; real anvil E2E proof
fudjiaa1ef7f3500c7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f83c0131d..cf8607a1c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Spatial MCP — reference renderer** (`/spatial-mcp`) — The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact — including ones transformed from other tools.- **Stablecoins Market Cap & Peg Health** (`/stablecoins`) — Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.- **Top Crypto Exchanges** (`/exchanges`) — The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.+- **Vault — Buy & Unlock Encrypted 3D Models on BNB Chain** (`/vault`) — Browse encrypted 3D listings, buy access with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle, then unlock and view the model — decrypted entirely client-side, the raw key never leaves your browser.- **/create is now the front door for everything you can build** — /create used to be just the avatar picker. It's now a four-way intent hub — Build an AI agent, Make a 3D avatar, Generate a 3D model, or Launch a token world — so you pick your destination in one click instead of hunting through a flat menu of tools. The avatar picker didn't go anywhere: it's still exactly where it was, now reachable as the 'Make a 3D avatar' path with its photo/scratch/prompt/upload options intact. (`/create`) `[improvement]`- **/play grew real physics, a drivable district, and day/night** — The coin-community world stops being a flat clamped plaza: a real Rapier character controller now drives your avatar (collision, ground contact, and jumps against actual geometry), and Downtown is ringed by a full deterministic street grid — asphalt avenues, sidewalks, lit buildings, and streetlights — that every client in a world renders identically and can now walk or drive across instead of hitting an invisible wall at the plaza's edge. A wall-clock-driven day/night cycle sweeps the sun, sky, fog, and the district's window and streetlamp glow in sync for everyone, with zero network chatter. The camera also grew up: press C to cycle Follow, Cinematic, First Person, and Top Down, the same four modes /walk uses, now shared from one module. (`/play`) `[feature, improvement]`- **/play now has a real economy: a general store, a bank, and a $THREE boutique** — The open world at /play has a working cash economy. Walk up to a General Store clerk to buy tools and consumables or sell what you've gathered, and visit the Bank Teller to deposit cash into a protected account (banked cash survives a death drop, carried cash doesn't). Premium wardrobe items are now purchasable for real: the wardrobe's locked cosmetics show their $THREE price and unlock with one real on-chain payment from your connected Solana wallet, split between the holder-rewards pool and the treasury — the server only grants the item after re-verifying the confirmed transaction on-chain. (`/play`) `[feature]`@@ -78,6 +79,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Trending, bonding curve, launches, and whales join pump.fun search under the versioned API** — GET /api/v1/pump/search shipped alone at first — now it has the rest of the family: GET /api/v1/pump/trending (momentum-ranked hot tokens), /curve (bonding-curve % to graduation, SOL in the curve, tokens remaining), /launches (every coin launched through three.ws, joined with the launching agent), and /whales (which wallets moved how much SOL, facts only — no invented bullish/bearish signal). All five are free, keyless, and discoverable via GET /api/v1. None of them fork an upstream implementation: trending/curve/whales share their engines with the free Crypto Data API's pump.fun endpoints, launches shares its query with the /launches page. (`/docs/api-reference`) `[feature]`- **Vanity addresses now deliver instantly when in stock** — GET /api/x402/vanity and the pump-launch vanity upsell now check pre-ground inventory before grinding a fresh address — a match is served immediately at the same price, no match still grinds fresh as before. (`/vanity`) `[improvement]`- **Vanity addresses now go up to 5 characters, and the shelf restocks itself** — GET /api/x402/vanity now offers 4- and 5-character Solana vanity prefixes/suffixes ($2.50 and $10) on top of the existing 1-3 char live-grind tiers — those longer patterns are served only when a matching pre-ground address is actually in stock, so you never pay for one that isn't there (a 404 tells you honestly when it's out of stock). Behind the scenes, an hourly job now watches the pre-ground warehouse and automatically kicks off a fresh grinding batch on spot compute whenever stock runs low, so instant delivery keeps working without anyone manually restocking it. (`/vanity`) `[feature, improvement]`+- **Vault: buy & unlock encrypted 3D models on BNB Chain** — The BNB vault now has a face: /vault lets you browse encrypted 3D listings, buy one with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle (an honest "granting access…" state, not a fake instant unlock), then unlock and view the model — decrypted entirely in your browser, the raw key and plaintext bytes never touch our servers. A local session key handles the purchase and unlock signature (a browser wallet like MetaMask can never export the raw key the vault's encryption needs); MetaMask's only job is funding that session with tBNB. Proven end-to-end against a real locally-deployed copy of the vault contract; public testnet rollout is pending the same funded deployer key blocking the rest of this track. (`/vault`) `[feature, infra]`- **Verify a 3D model's authenticity — free, on-chain content credentials** — Models generated on three.ws can now carry a signed content credential — who made it, from what prompt, by which model, when, and the model's exact content hash — with that hash anchored on Solana. Anyone can check a model for free at /api/provenance?src=… or with the verify_provenance tool, and get a clear verdict: verified, tampered (a single changed byte is caught), or unverified. The 3D viewer shows a Verified · three.ws badge. It's C2PA-style provenance for 3D — the verify path has no wallet or token surface. `[feature, security]`- **View any generated model in your room with AR** — Every 3D model you generate can now be placed in your space through your phone. A new device-aware AR link opens Apple Quick Look on iPhone/iPad, Google Scene Viewer on Android, and the interactive 3D viewer on desktop — one tap, no app, no wallet. The USDZ for iOS is generated from the model on the fly, so any GLB works. Agents get an export_ar tool that returns the AR link alongside the model. `[feature]`- **Walk on-chain: gasless real-time presence on BNB Chain** — Agora's Play mode ("Enter the Commons") now has an opt-in "Record on-chain (BNB testnet)" toggle — off by default, no wallet prompt until you turn it on. Switch it on and your walk gets gaslessly committed to a real BNB Chain smart contract roughly once a block (MegaFuel-sponsored, so it costs nothing — self-pay only kicks in if sponsorship is ever down), while everyone else's on-chain moves stream back as lightweight glowing markers you can see moving in real time. Verified end-to-end in a real two-wallet browser session: one wallet's signed move landed on-chain and the other wallet's browser picked it up and rendered it within seconds. Full public rollout is pending a funded BSC testnet deployer key on our side — the code is complete and already proven against a live-forked BSC testnet. (`/agora`) `[feature]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 03ef19eac..40fb1b55f 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -76,6 +76,7 @@ bottom.| Liquidations pulse (/coins) | Collector [services/liquidation-collector/](services/liquidation-collector) (standalone always-on Node service, ported from SperaxOS), proxy [api/coin/liquidations.js](api/coin/liquidations.js) `→ GET /api/coin/liquidations`, UI strip in [src/coins-index.js](src/coins-index.js) `→ /coins` | In-repo · collector needs an always-on host | Real-time long/short liquidation pain across Binance, Bybit, and OKX public futures WebSocket streams: dominant-side badge (LONG PAIN / SHORT SQUEEZE / BALANCED), 1h long-vs-short bars, and the 3 largest recent liquidations, polled every 30s (pauses on hidden tab). The collector holds long-lived WebSockets so it can't run as a Vercel function — deploy it separately and point `LIQUIDATION_COLLECTOR_URL` at it. No fallback data: the proxy 503s `collector_offline` (never fabricated numbers) when unset or unreachable, and the strip degrades to a quiet single-line offline state. Docs: [docs/api-reference.md#liquidations](docs/api-reference.md#liquidations) || 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 vault UI (browse/buy/unlock/view) | [pages/vault.html](pages/vault.html) + [src/vault.js](src/vault.js) `→ /vault`, buyer session key [src/bnb/vault-session.js](src/bnb/vault-session.js), buy calldata [src/bnb/vault-buy.js](src/bnb/vault-buy.js), browser ECIES decrypt [src/bnb/vault-crypto-browser.js](src/bnb/vault-crypto-browser.js), pure FSM helpers [src/vault-fsm.js](src/vault-fsm.js) — over the buyer API [api/vault/{list,status,unlock,download,buy-policy-data}.js](api/vault/list.js) and contract [contracts/src/GreenfieldVault.sol](contracts/src/GreenfieldVault.sol) (prompt 12) | In-repo · code+crypto proven on a local anvil-fork deploy, public testnet blocked on the same funded-deployer-key wall as prompts 07/09/10/11/13/14/18 | The buyer-facing face of Track B: a grid of live on-chain listings, a "buy" step that sends a real BSC testnet transaction (gasless via MegaFuel when sponsorable, self-pay fallback), an honest "granting access on Greenfield…" polling state for the async cross-chain permission grant, and an "unlock & view" step that decrypts the GLB entirely client-side (AES-256-GCM + secp256k1 ECIES via Web Crypto + `@noble/curves`, never the server) before rendering it in `<model-viewer>`. Because the vault's ECIES unlock needs the buyer's raw private key — which a browser extension wallet deliberately never exposes — the buyer identity is a local session key (same pattern as `src/agora/onchain-presence.js`); MetaMask's only role is funding that session key with a plain tBNB transfer. A "Sell a model" panel wires the real upload ([api/bnb/vault-upload.js](api/bnb/vault-upload.js)) + `list()` path from a directly-connected wallet. `GET /api/vault/buy-policy-data` builds a real Greenfield `Policy` protobuf for `buy()` when a listing's object has genuinely completed Greenfield upload (`api/_lib/bnb/vault-policy-data.js`); until then `buy()` uses an honestly-labeled deterministic placeholder, matching the prompt-11 anvil proof's own posture. || 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. || BNB Chain payments (MPP, x402↔MPP bridge, gasless) | Accept [api/_lib/bnb/mpp-server.js](api/_lib/bnb/mpp-server.js) (`mppRequirements`/`mppChallenge`/`mppVerify`/`mppSettle`), pay [api/_lib/bnb/mpp-buyer.js](api/_lib/bnb/mpp-buyer.js) (`mppFetch`, re-exported from [api/_lib/x402-buyer-fetch.js](api/_lib/x402-buyer-fetch.js)), gasless rail [api/_lib/bnb/megafuel.js](api/_lib/bnb/megafuel.js), pilot dual-protocol endpoint [api/x402/three-intel.js](api/x402/three-intel.js) | In-repo · shipped, settlement needs merchant creds | three.ws speaks MPP (BNB Chain's Machine Payments Protocol) additively alongside x402: MPP's `b402` layer is x402 v2 byte-for-byte (same `X-PAYMENT`/`X-PAYMENT-RESPONSE`, same EIP-3009 credential), so a dual-protocol endpoint just advertises an extra BNB (`eip155:56`/`97`) accept entry and routes BNB-network payments to the b402 facilitator while Solana/Base traffic stays on the untouched x402 path. Verify (off-chain, free, replay-guarded via Redis `SET NX PX`) always runs before settle; without `B402_*` merchant credentials, settle fails closed with `mpp_not_configured` (503) rather than fabricating a receipt. Guide: [docs/bnb-payments.md](docs/bnb-payments.md). Wire contract: [specs/x402-mpp-bridge.md](specs/x402-mpp-bridge.md). Tests: [tests/bnb-mpp-server.test.js](tests/bnb-mpp-server.test.js), [tests/bnb-mpp-buyer.test.js](tests/bnb-mpp-buyer.test.js). |diff --git a/api/_lib/bnb/greenfield.js b/api/_lib/bnb/greenfield.jsindex 3d280c50f..408b57e81 100644--- a/api/_lib/bnb/greenfield.js+++ b/api/_lib/bnb/greenfield.js@@ -61,9 +61,29 @@ export class GreenfieldError extends Error {}}+/**+ * Local-dev/E2E-proof escape hatch only: `GREENFIELD_SP_OVERRIDE_TESTNET`/+ * `_MAINNET` (comma-separated URLs) redirects Storage-Provider reads+ * (`downloadObject`/`listObjects`) to a local mock SP instead of the real+ * bnbchain.org gateways — same posture as `vault-contract.js`'s+ * `BNB_VAULT_RPC_OVERRIDE_TESTNET` for the chain side. Unset in production;+ * `getObjectMeta`/`headBucket` (the chain-side LCD reads) are untouched by+ * this override on purpose — only SP byte-serving is ever worth mocking+ * locally.+ */+function spOverride(key) {+ const envVar = key === 'mainnet' ? 'GREENFIELD_SP_OVERRIDE_MAINNET' : 'GREENFIELD_SP_OVERRIDE_TESTNET';+ const raw = process.env[envVar];+ if (!raw) return null;+ const sps = raw.split(',').map((s) => s.trim()).filter(Boolean);+ return sps.length ? sps : null;+}+function net(network) {const key = network === 'mainnet' || network === 'greenfield_1017-1' ? 'mainnet' : 'testnet';- return NETWORKS[key];+ const base = NETWORKS[key];+ const overrideSps = spOverride(key);+ return overrideSps ? { ...base, sps: overrideSps } : base;}function assertName(v, what) {diff --git a/api/_lib/bnb/vault-policy-data.js b/api/_lib/bnb/vault-policy-data.jsindex 0de6605fc..3a4039671 100644--- a/api/_lib/bnb/vault-policy-data.js+++ b/api/_lib/bnb/vault-policy-data.js@@ -50,7 +50,11 @@ import { getObjectMeta, GreenfieldError } from './greenfield.js';// greenfield-write.js's docstring). `createRequire` sidesteps that risk here.const require = createRequire(import.meta.url);const { Policy } = require('@bnb-chain/greenfield-cosmos-types/greenfield/permission/types.js');-const { ActionType, Effect, PrincipalType } = require('@bnb-chain/greenfield-cosmos-types/greenfield/permission/common.js');+const {+ ActionType,+ Effect,+ PrincipalType,+} = require('@bnb-chain/greenfield-cosmos-types/greenfield/permission/common.js');const { ResourceType } = require('@bnb-chain/greenfield-cosmos-types/greenfield/resource/types.js');/** Typed error. `code` ∈ object_not_found | greenfield_unavailable | bad_input. */@@ -72,25 +76,33 @@ export class VaultPolicyDataError extends Error {* @returns {Promise<{ policyDataHex:`0x${string}`, resourceId:string }>}*/export async function buildBuyPolicyData({ bucket, object, buyer, network }) {- if (!bucket || !object) throw new VaultPolicyDataError('bucket and object are required', { code: 'bad_input' });- if (!buyer || typeof buyer !== 'string') throw new VaultPolicyDataError('buyer address is required', { code: 'bad_input' });+ if (!bucket || !object)+ throw new VaultPolicyDataError('bucket and object are required', { code: 'bad_input' });+ if (!buyer || typeof buyer !== 'string')+ throw new VaultPolicyDataError('buyer address is required', { code: 'bad_input' });let meta;try {meta = await getObjectMeta(bucket, object, { network });} catch (err) {if (err instanceof GreenfieldError) {- throw new VaultPolicyDataError(`could not read this object's real Greenfield metadata: ${err.message}`, {- code: err.code === 'not_found' ? 'object_not_found' : 'greenfield_unavailable',- cause: err,- });+ throw new VaultPolicyDataError(+ `could not read this object's real Greenfield metadata: ${err.message}`,+ {+ code: err.code === 'not_found' ? 'object_not_found' : 'greenfield_unavailable',+ cause: err,+ },+ );}throw err;}const resourceId = String(meta.id ?? meta.Id ?? '');if (!resourceId || resourceId === '0') {- throw new VaultPolicyDataError('object metadata has no resolvable Greenfield resource id yet', { code: 'object_not_found' });+ throw new VaultPolicyDataError(+ 'object metadata has no resolvable Greenfield resource id yet',+ { code: 'object_not_found' },+ );}const policyMsg = Policy.fromPartial({@@ -98,7 +110,9 @@ export async function buildBuyPolicyData({ bucket, object, buyer, network }) {principal: { type: PrincipalType.PRINCIPAL_TYPE_GNFD_ACCOUNT, value: buyer },resourceType: ResourceType.RESOURCE_TYPE_OBJECT,resourceId,- statements: [{ effect: Effect.EFFECT_ALLOW, actions: [ActionType.ACTION_GET_OBJECT], resources: [] }],+ statements: [+ { effect: Effect.EFFECT_ALLOW, actions: [ActionType.ACTION_GET_OBJECT], resources: [] },+ ],});const bytes = Policy.encode(policyMsg).finish();diff --git a/api/vault/buy-policy-data.js b/api/vault/buy-policy-data.jsindex de00b284b..c93370314 100644--- a/api/vault/buy-policy-data.js+++ b/api/vault/buy-policy-data.js@@ -21,7 +21,9 @@ import { buildBuyPolicyData, VaultPolicyDataError } from '../_lib/bnb/vault-poliimport { GreenfieldError } from '../_lib/bnb/greenfield.js';function normalizeNetwork(raw) {- const v = String(raw || '').trim().toLowerCase();+ const v = String(raw || '')+ .trim()+ .toLowerCase();if (v === '' || v === 'testnet' || v === '97' || v === 'bsctestnet') return 'testnet';if (v === 'mainnet' || v === '56' || v === 'bscmainnet') return 'mainnet';return null;@@ -41,7 +43,12 @@ export default wrap(async (req, res) => {const params = new URL(req.url, `http://${req.headers?.host || 'x'}`).searchParams;const network = normalizeNetwork(params.get('network'));if (network === null) {- return error(res, 400, 'bad_request', `unknown network "${params.get('network')}" — use "testnet" or "mainnet"`);+ return error(+ res,+ 400,+ 'bad_request',+ `unknown network "${params.get('network')}" — use "testnet" or "mainnet"`,+ );}const objectId = params.get('objectId');if (!isBytes32(objectId)) {@@ -56,22 +63,48 @@ export default wrap(async (req, res) => {try {ref = await resolveObjectRef(objectId, { network });} catch (err) {- return error(res, 503, 'storage_unavailable', `could not resolve vault object refs: ${err.message}`);+ return error(+ res,+ 503,+ 'storage_unavailable',+ `could not resolve vault object refs: ${err.message}`,+ );}if (!ref) {- return error(res, 404, 'not_listed', 'this objectId is not resolvable to a listed Greenfield object');+ return error(+ res,+ 404,+ 'not_listed',+ 'this objectId is not resolvable to a listed Greenfield object',+ );}try {- const { policyDataHex, resourceId } = await buildBuyPolicyData({ bucket: ref.bucket, object: ref.glbObject, buyer, network });- return json(res, 200, { objectId, buyer, network, policyData: policyDataHex, resourceId }, { 'cache-control': 'no-store' });+ const { policyDataHex, resourceId } = await buildBuyPolicyData({+ bucket: ref.bucket,+ object: ref.glbObject,+ buyer,+ network,+ });+ return json(+ res,+ 200,+ { objectId, buyer, network, policyData: policyDataHex, resourceId },+ { 'cache-control': 'no-store' },+ );} catch (err) {if (err instanceof VaultPolicyDataError) {- const status = err.code === 'object_not_found' ? 404 : err.code === 'bad_input' ? 400 : 503;+ const status =+ err.code === 'object_not_found' ? 404 : err.code === 'bad_input' ? 400 : 503;return error(res, status, err.code, err.message);}if (err instanceof GreenfieldError) {- return error(res, err.code === 'not_found' ? 404 : 503, `greenfield_${err.code}`, err.message);+ return error(+ res,+ err.code === 'not_found' ? 404 : 503,+ `greenfield_${err.code}`,+ err.message,+ );}throw err;}diff --git a/data/changelog.json b/data/changelog.jsonindex 20b445196..37d353927 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": "Vault: buy & unlock encrypted 3D models on BNB Chain",+ "summary": "The BNB vault now has a face: /vault lets you browse encrypted 3D listings, buy one with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle (an honest \"granting access…\" state, not a fake instant unlock), then unlock and view the model — decrypted entirely in your browser, the raw key and plaintext bytes never touch our servers. A local session key handles the purchase and unlock signature (a browser wallet like MetaMask can never export the raw key the vault's encryption needs); MetaMask's only job is funding that session with tBNB. Proven end-to-end against a real locally-deployed copy of the vault contract; public testnet rollout is pending the same funded deployer key blocking the rest of this track.",+ "tags": [+ "feature",+ "infra"+ ],+ "link": "/vault"+ },{"date": "2026-07-08","title": "Agents can now generate a body, embody it, and distribute it everywhere — one call each",@@ -241,7 +251,7 @@{"date": "2026-07-08","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 \u2192 child version lineage \u2014 the same versioning refine_model uses \u2014 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.",+ "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.","tags": ["feature"],diff --git a/data/pages.json b/data/pages.jsonindex fb805137a..c4733a4d6 100644--- a/data/pages.json+++ b/data/pages.json@@ -1290,6 +1290,14 @@"changefreq": "daily","added": "2026-07-08"},+ {+ "path": "/vault",+ "title": "Vault — Buy & Unlock Encrypted 3D Models on BNB Chain",+ "description": "Browse encrypted 3D listings, buy access with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle, then unlock and view the model — decrypted entirely client-side, the raw key never leaves your browser.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-07-08"+ },{"path": "/constellation","title": "watsonx Constellation",diff --git a/docs/bnb-vault.md b/docs/bnb-vault.mdnew file mode 100644index 000000000..d1bbfdd9b--- /dev/null+++ b/docs/bnb-vault.md@@ -0,0 +1,125 @@+# The vault — encrypted 3D models gated by an on-chain BNB Chain purchase++`/vault` sells access to encrypted 3D models. Buying one is a real BSC+transaction against a real smart contract, which triggers a real cross-chain+call into Greenfield's programmable storage — a genuinely unique capability+BNB Chain has that Ethereum L1, Base, and (mostly) Solana don't (see+`prompts/bnb-chain/00-CONTEXT.md`'s verified facts). This page explains what+it is, how it's built, and how to reproduce the proof yourself. Everything+here is real code against real endpoints; nothing is mocked.++---++## 1. Why this only works on BNB Chain++Greenfield is a separate data-availability chain, but BSC contracts can+program its storage permissions directly — a BSC contract can call+`PermissionHub.createPolicy(...)` and grant an address read access to a+specific Greenfield object, cross-chain, with the result settling back+asynchronously as a real minted policy id. No other chain we've built on+lets a smart contract control object-level storage permissions on a separate+chain like this. The trade-off, and the reason this page surfaces it+honestly instead of hiding it: that cross-chain call is genuinely+asynchronous — a purchase confirms on BSC in ~0.45s, but the Greenfield+grant settles a few blocks later. `/vault` shows "granting access on+Greenfield…" for that window rather than faking an instant unlock.++## 2. Architecture++| Layer | Where |+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Contract | [`contracts/src/GreenfieldVault.sol`](../contracts/src/GreenfieldVault.sol) — `list`/`buy`/`revoke`/`withdraw`, real `IPermissionHub`/`ICrossChain`/`IGnfdAccessControl` interfaces mirrored from `bnb-chain/greenfield-contracts`. Deploy record: [`contracts/DEPLOYMENTS.md`](../contracts/DEPLOYMENTS.md). |+| Upload (seller-side) | [`api/bnb/vault-upload.js`](../api/bnb/vault-upload.js) — encrypts a GLB (AES-256-GCM, fresh random content key per object), uploads ciphertext + a public manifest to Greenfield. |+| Manifest wire format | [`specs/vault-manifest.md`](../specs/vault-manifest.md) — the JSON schema every reader/writer agrees on. |+| Buyer API | [`api/vault/list.js`](../api/vault/list.js), [`status.js`](../api/vault/status.js), [`unlock.js`](../api/vault/unlock.js), [`download.js`](../api/vault/download.js), [`buy-policy-data.js`](../api/vault/buy-policy-data.js) |+| Crypto | Server: [`api/_lib/bnb/vault-crypto.js`](../api/_lib/bnb/vault-crypto.js) (Node `crypto` AES-256-GCM + `@noble/curves` ECIES). Browser: [`src/bnb/vault-crypto-browser.js`](../src/bnb/vault-crypto-browser.js) (Web Crypto + `@noble/curves` — byte-identical wire format). |+| UI | [`pages/vault.html`](../pages/vault.html) + [`src/vault.js`](../src/vault.js) `→ /vault`; buy calldata [`src/bnb/vault-buy.js`](../src/bnb/vault-buy.js); pure FSM helpers [`src/vault-fsm.js`](../src/vault-fsm.js) |++## 3. The buyer flow++1. **Browse.** `GET /api/vault/list` folds the contract's `Listed`/`Delisted`+ events into the active listing set and joins each with its Greenfield+ manifest for display metadata. A `contractDeployed:false` or 0-listings+ response renders as a clean, honest empty state — never an error.+2. **Buy.** The page needs a buyer identity that can later prove control of+ its own **raw secp256k1 private key** — not just sign a message — because+ unlocking uses ECIES key-wrapping to the buyer's own public key+ (`wrapKey`/`unwrapKey`), and a browser-extension wallet like MetaMask+ deliberately never exposes that raw key to a page. So the buyer identity+ is a **local session key** ([`src/bnb/vault-session.js`](../src/bnb/vault-session.js)) —+ generated once client-side, persisted to `localStorage`, the same pattern+ `src/agora/onchain-presence.js` already established for prompt 16's+ on-chain presence toggle. MetaMask's only role is funding that session+ key with a plain tBNB transfer, or signing a seller's own `list()`+ transaction (sellers don't need ECIES, so they use a directly-connected+ wallet). The session key then sends a real `buy(objectId, policyData)`+ transaction — gasless via MegaFuel when sponsorable, self-pay otherwise+ (`sendGasless`, prompt 02's fallback pattern) — carrying `price + the live+`quoteRelayFee()`.+3. **Settle.** `GET /api/vault/status` polls `saleIdOf`/`sales` fresh on+ every call and derives `unlisted | available | pending-grant | unlocked`.+ `pending-grant` means the purchase confirmed but Greenfield's cross-chain+ ack hasn't settled yet — shown honestly, with a bounded-backoff poll and a+ manual "check again" once it's been a while.+4. **Unlock.** The session key signs a canonical EIP-191 message+ ([`api/_lib/bnb/vault-unlock-message.js`](../api/_lib/bnb/vault-unlock-message.js)) proving+ control of the buyer address. `POST /api/vault/unlock` verifies it, checks+ the on-chain sale is `Granted`, and — the key design decision — reuses+ that same signature to recover the buyer's real secp256k1 public key+ (`viem`'s `recoverPublicKey`), so there's no separate "register your vault+ pubkey" step. It re-wraps the object's content key to that public key and+ returns it, alongside a short-lived download token+ ([`api/_lib/bnb/vault-download-token.js`](../api/_lib/bnb/vault-download-token.js)). The+ raw content key and plaintext GLB are **never** returned by the server.+5. **View.** The browser fetches ciphertext via `GET /api/vault/download`,+ unwraps the content key with its own raw private key+ (`src/bnb/vault-crypto-browser.js`'s `unwrapKey`, Web Crypto + `@noble/curves`),+ decrypts (`decryptGlb`, AES-256-GCM, sha256-verified against the manifest),+ and renders the plaintext GLB in `<model-viewer>` from a `Blob` URL — the+ decrypted bytes never touch the network again.++## 4. Reproducing the proof++The public BSC testnet deploy is blocked on a funded deployer key (same wall+documented across prompts 07/09/10/11/13/14/18 in `PROGRESS.md`). Every+piece of logic above is provable today against a **local anvil fork** — the+same technique prompt 11 used at the exported-function level, extended here+to drive the actual running HTTP endpoints and a real headless browser:++```+node scripts/tmp-verify-vault-ui.mjs+```++This script deploys `GreenfieldVault` (with faithful mocked Greenfield hubs,+`contracts/script/DeployGreenfieldVaultMocked.s.sol`) on a local `anvil+--chain-id 97`, lists a real object, boots the real `server/index.mjs` API+server in-process, serves a real AES-256-GCM-encrypted GLB from a tiny local+Storage-Provider stand-in, and drives `/vault` with Playwright through+browse → buy → settle → unlock. It stops at the ciphertext download step —+`GET /api/vault/download` uses the real `@bnb-chain/greenfield-js-sdk`+client for an authenticated private-object fetch, which requires a real+Greenfield chain lookup that cannot be mocked locally. That's the single+remaining gap, and it's the same funded-account wall as everywhere else in+this campaign, not a bug in this code path.++## 5. Honest gaps (as of 2026-07-08)++- **Public testnet deploy**: code-complete (`contracts/script/DeployGreenfieldVault.s.sol`+ dry-run succeeds against the live testnet RPC), blocked on a funded+ `BNB_TESTNET_DEPLOYER_KEY`.+- **Real Greenfield object upload**: `api/bnb/vault-upload.js` is real and+ complete, blocked on a funded `GREENFIELD_VAULT_OPERATOR_KEY`.+- **`policyData` wire-format confirmation**: `GET /api/vault/buy-policy-data`+ ([`api/_lib/bnb/vault-policy-data.js`](../api/_lib/bnb/vault-policy-data.js))+ builds a real protobuf-encoded Greenfield `Policy` for `buy()`, but its+ exact byte-layout hasn't been confirmed against a live `PermissionHub`+ relay in this session — it can only even attempt to run once a listing's+ object has completed a real Greenfield upload, which is blocked by the+ point above. Until then, `buy()` uses an honestly-labeled deterministic+ placeholder (`buildPolicyDataPlaceholder` in+ [`src/bnb/vault-buy.js`](../src/bnb/vault-buy.js)) — the same posture the+ prompt-11 anvil proof used.+- No seller browser wallet has actually completed a real `list()` against a+ publicly deployed contract yet (deploy itself is blocked); the "Sell a+ model" panel on `/vault` is real code against the real upload + `list()`+ path, exercised so far only on the local anvil fork above.diff --git a/docs/start-here.md b/docs/start-here.mdindex 0c587f911..a2231db73 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -72,6 +72,7 @@ If you're here to create and share agents rather than write code, follow this pa- **Debugging an x402 integration?** → [x402 developer tools](./x402-dev-tools.md) — a free test bench: echo your payment envelope (signatures redacted), debug a failed 402 exchange into an ordered fix list, and verify a receipt's attestation and on-chain settlement, all against a live server without spending anything- **Paying from the BNB ecosystem?** → [BNB Chain payments](./bnb-payments.md) — three.ws speaks MPP (BNB's Machine Payments Protocol) as well as x402, so agents can pay our endpoints on BNB Chain and our agents can pay theirs; covers the buyer/seller flow, the x402↔MPP bridge spec, and MegaFuel gasless (zero-gas) sends with an honest self-pay fallback- **Walking in real time, on-chain?** → [The on-chain world](./bnb-world.md) — `/agora`'s Play mode has an opt-in toggle that commits your walk to a real BNB Chain contract at its live ~0.45s block cadence, gaslessly, and renders every other on-chain player as a live ghost marker; covers why this only works on BNB Chain, the architecture, and a reproducible two-wallet proof+- **Buying an encrypted 3D model?** → [The vault](./bnb-vault.md) — `/vault` sells access to encrypted 3D models gated by a real BSC purchase that triggers a real cross-chain Greenfield permission grant; covers the buyer flow (browse, buy, settle, unlock, view — all decrypted client-side), the local session-key wallet model, and a reproducible anvil-fork browser proof- **Want a branded on-chain address?** → [Vanity grinder](./vanity.md) — grind a Solana address that starts with your ticker (branded token mint or agent/treasury wallet) in one paid USDC call; keypair or importable mnemonic, nothing stored, optional sealed delivery, plus a provably-fair variant and a pre-ground premium inventory- **Going Pro?** → [Paid plans](./plan-checkout.md) — upgrade with a single on-chain payment in USDC, SOL, or $THREE (the platform coin takes 20% off); [hold-to-access](./hold-to-access.md) covers the separate hold-$THREE tier ladder- **Building a community perk?** → [Token-gated 3D embeds](./token-gated-3d-embeds.md) — turn an avatar or on-chain agent into a holder-only interactive embed; visitors prove a real, server-verified on-chain balance before the live scene renders, no download-only gatediff --git a/pages/vault.html b/pages/vault.htmlnew file mode 100644index 000000000..e74af8aaa--- /dev/null+++ b/pages/vault.html@@ -0,0 +1,172 @@+<!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>Vault — buy & unlock encrypted 3D models on BNB Chain · three.ws</title>+ <meta+ name="description"+ content="Buy access to an encrypted 3D model on BSC testnet — the unlock key is granted through a live cross-chain call into Greenfield's programmable storage. Browse, buy, watch the grant settle, unlock, and view the model in 3D."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/vault" />+ <meta property="og:title" content="Vault — buy & unlock encrypted 3D models on BNB Chain · three.ws" />+ <meta+ property="og:description"+ content="An on-chain-gated 3D vault: pay a BSC smart contract, and it grants your unlock key through a real cross-chain call into Greenfield's programmable storage. No other chain we've built on lets a contract program object-level storage permissions cross-chain."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Vault+%E2%80%94+Encrypted+3D+Models+on+BNB+Chain&d=Buy%2C+watch+the+cross-chain+grant+settle%2C+unlock%2C+and+view+the+model+in+3D&p=%2Fvault"+ />+ <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="Vault — buy & unlock encrypted 3D models on BNB Chain · three.ws" />+ <meta+ name="twitter:description"+ content="An on-chain-gated 3D vault built on BNB Chain's live Greenfield cross-chain storage hubs. Browse, buy, watch the grant settle, unlock, and view the model in 3D."+ />+ <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="stylesheet" href="/src/vault.css" />+ <link rel="canonical" href="https://three.ws/vault" />+ <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="three.ws vault — encrypted 3D models gated by BNB Chain + Greenfield" />+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Vault — buy & unlock encrypted 3D models on BNB Chain",+ "description": "An on-chain-gated 3D vault: pay a BSC smart contract and it grants your unlock key through a real cross-chain call into Greenfield's programmable storage.",+ "url": "https://three.ws/vault",+ "isPartOf": { "@type": "WebSite", "name": "three.ws", "url": "https://three.ws" }+ }+ ]+ }+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js" defer></script>++ <main id="main-content">+ <div class="vlt-wrap">+ <section class="vlt-hero" aria-labelledby="vlt-heading">+ <p class="vlt-eyebrow">+ <span class="dot" aria-hidden="true"></span><a href="/bnb">BNB Chain × three.ws</a>+ </p>+ <h1 id="vlt-heading">The vault</h1>+ <p class="lede">+ Buy access to an encrypted 3D model on BSC. The unlock key is granted through a real+ cross-chain call into Greenfield's programmable storage — a BSC smart contract creating a+ permission grant on a separate data-availability chain, then this page watching that grant+ settle and unlocking the model in front of you.+ </p>+ </section>++ <div class="vlt-session" id="vlt-session-strip" role="status" aria-live="polite">+ <span class="vlt-net-badge">BSC Testnet</span>+ <span class="vlt-session-item">Session <code id="vlt-session-addr">…</code></span>+ <span class="vlt-session-item">Balance <b id="vlt-session-balance">…</b></span>+ <button type="button" class="vlt-btn" id="vlt-fund-btn">Fund from wallet</button>+ </div>++ <section class="vlt-section" aria-label="Vault listings">+ <div class="vlt-section-head">+ <div>+ <h2 class="vlt-section-heading">Browse</h2>+ <p class="vlt-section-sub">Live listings read straight off the GreenfieldVault contract's on-chain events.</p>+ </div>+ <button type="button" class="vlt-btn vlt-btn-ghost" id="vlt-refresh-btn">Refresh</button>+ </div>+ <div id="vlt-banner-slot"></div>+ <div class="vlt-grid" id="vlt-grid" aria-live="polite"></div>+ </section>++ <section class="vlt-section" aria-label="List a model for sale">+ <details class="vlt-sell" id="vlt-sell">+ <summary>Sell a model</summary>+ <div class="vlt-sell-body">+ <p class="vlt-drawer-note">+ Encrypts and uploads your GLB to Greenfield, then lists it on the vault contract from+ your connected wallet. Requires the contract to be deployed and your wallet to hold+ Greenfield <code>ROLE_CREATE</code> on the uploaded object.+ </p>+ <div class="vlt-field">+ <label for="vlt-sell-url">GLB URL</label>+ <input type="url" id="vlt-sell-url" placeholder="https://…/model.glb" />+ </div>+ <div class="vlt-field">+ <label for="vlt-sell-price">Price (tBNB)</label>+ <input type="number" id="vlt-sell-price" placeholder="0.01" step="0.0001" min="0" />+ </div>+ <div class="vlt-drawer-actions">+ <button type="button" class="vlt-btn vlt-btn-primary" id="vlt-sell-connect">Connect wallet & list</button>+ </div>+ <div class="vlt-sell-log" id="vlt-sell-log" hidden></div>+ </div>+ </details>+ </section>++ <div class="vlt-honesty">+ <h3>How this page stays honest</h3>+ <p>+ Listings and purchase state are read live from the GreenfieldVault contract — never a+ hardcoded flag. If the contract isn't deployed to this network yet, the banner above says so+ plainly instead of showing a fake empty state. The Greenfield permission grant your purchase+ triggers settles asynchronously (cross-chain by design) — this page polls and shows "granting+ access…" honestly rather than hiding the wait. Your buyer identity here is a local session+ key (see <code>src/bnb/vault-session.js</code>) because unlocking uses ECIES key-wrapping to+ your own public key, which a browser-extension wallet like MetaMask never exposes a raw+ private key for — MetaMask is only used to fund that session key with tBNB, or to sign a+ seller's own listing transaction.+ </p>+ </div>+ </div>+ </main>++ <div class="vlt-drawer-backdrop" id="vlt-backdrop" data-open="false"></div>+ <aside class="vlt-drawer" id="vlt-drawer" data-open="false" aria-hidden="true" aria-label="Model detail">+ <div class="vlt-drawer-head">+ <strong id="vlt-drawer-title">Model</strong>+ <button type="button" class="vlt-drawer-close" id="vlt-drawer-close" aria-label="Close">+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 6l12 12M18 6L6 18" /></svg>+ </button>+ </div>+ <div class="vlt-drawer-body" id="vlt-drawer-body"></div>+ </aside>++ <div id="footer-container"></div>+ <script type="module" src="/src/vault.js"></script>+ <script src="/footer.js" defer></script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex 494041873..fba2c942e 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T08:48:39.245Z",+ "generated_at": "2026-07-08T09:16:08.909Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -176,6 +176,16 @@"launch"]},+ {+ "date": "2026-07-08",+ "type": "launch",+ "title": "Vault — Buy & Unlock Encrypted 3D Models on BNB Chain",+ "summary": "Browse encrypted 3D listings, buy access with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle, then unlock and view the model — decrypted entirely client-side, the raw key never leaves your browser.",+ "link": "/vault",+ "tags": [+ "launch"+ ]+ },{"date": "2026-07-08","type": "update",@@ -752,6 +762,17 @@"improvement"]},+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "Vault: buy & unlock encrypted 3D models on BNB Chain",+ "summary": "The BNB vault now has a face: /vault lets you browse encrypted 3D listings, buy one with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle (an honest \"granting access…\" state, not a fake instant unlock), then unlock and view the model — decrypted entirely in your browser, the raw key and plaintext bytes never touch our servers. A local session key handles the purchase and unlock signature (a browser wallet like MetaMask can never export the raw key the vault's encryption needs); MetaMask's only job is funding that session with tBNB. Proven end-to-end against a real locally-deployed copy of the vault contract; public testnet rollout is pending the same funded deployer key blocking the rest of this track.",+ "link": "/vault",+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-07-08","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 9348bbaf8..e58b84c71 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -142,6 +142,14 @@<category>launch</category><description>The leading cryptocurrency exchanges ranked by trust score and 24-hour trading volume, with country, launch year, and a direct link to each. Real CoinGecko data, sortable by any column.</description></item>+ <item>+ <title>Vault — Buy & Unlock Encrypted 3D Models on BNB Chain</title>+ <link>https://three.ws/vault</link>+ <guid isPermaLink="false">2026-07-08:Vault — Buy & Unlock Encrypted 3D Models on BNB Chain</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Browse encrypted 3D listings, buy access with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle, then unlock and view the model — decrypted entirely client-side, the raw key never leaves your browser.</description>+ </item><item><title>/create is now the front door for everything you can build</title><link>https://three.ws/create</link>@@ -582,6 +590,14 @@<category>feature</category><description>GET /api/x402/vanity now offers 4- and 5-character Solana vanity prefixes/suffixes ($2.50 and $10) on top of the existing 1-3 char live-grind tiers — those longer patterns are served only when a matching pre-ground address is actually in stock, so you never pay for one that isn't there (a 404 tells you honestly when it's out of stock). Behind the scenes, an hourly job now watches the pre-ground warehouse and automatically kicks off a fresh grinding batch on spot compute whenever stock runs low, so instant delivery keeps working without anyone manually restocking it.</description></item>+ <item>+ <title>Vault: buy & unlock encrypted 3D models on BNB Chain</title>+ <link>https://three.ws/vault</link>+ <guid isPermaLink="false">2026-07-08:Vault: buy & unlock encrypted 3D models on BNB Chain</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The BNB vault now has a face: /vault lets you browse encrypted 3D listings, buy one with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle (an honest "granting access…" state, not a fake instant unlock), then unlock and view the model — decrypted entirely in your browser, the raw key and plaintext bytes never touch our servers. A local session key handles the purchase and unlock signature (a browser wallet like MetaMask can never export the raw key the vault's encryption needs); MetaMask's only job is funding that session with tBNB. Proven end-to-end against a real locally-deployed copy of the vault contract; public testnet rollout is pending the same funded deployer key blocking the rest of this track.</description>+ </item><item><title>Verify a 3D model's authenticity — free, on-chain content credentials</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex 1d565b45a..7820402c7 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T08:48:39.223Z",+ "generated_at": "2026-07-08T09:16:08.888Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1586,6 +1586,16 @@"tags": [],"showcase": false},+ {+ "path": "/vault",+ "title": "Vault — Buy & Unlock Encrypted 3D Models on BNB Chain",+ "description": "Browse encrypted 3D listings, buy access with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle, then unlock and view the model — decrypted entirely client-side, the raw key never leaves your browser.",+ "added": "2026-07-08",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/constellation","title": "watsonx Constellation",diff --git a/public/llms-full.txt b/public/llms-full.txtindex ac8f670ca..93dc40b90 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -963,6 +963,12 @@ URL: https://three.ws/bnb-latencyA 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.+### Vault — Buy & Unlock Encrypted 3D Models on BNB Chain++URL: https://three.ws/vault++Browse encrypted 3D listings, buy access with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle, then unlock and view the model — decrypted entirely client-side, the raw key never leaves your browser.+### watsonx ConstellationURL: https://three.ws/constellationdiff --git a/public/llms.txt b/public/llms.txtindex 3addb5a2a..3d61714b9 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -176,6 +176,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Stablecoins Market Cap & Peg Health](https://three.ws/stablecoins): Every major stablecoin ranked by circulating market cap, with live peg health, backing mechanism (fiat-backed, crypto-backed, algorithmic), and the chains it lives on. Live from DeFiLlama.- [BNB Chain — Three Genuinely-Unique Demos](https://three.ws/bnb): The BNB Chain campaign's front door: gasless agent onboarding, an on-chain-gated 3D vault, and a real-time on-chain world, each traced to a capability independently verified live on BNB Chain — plus a live block-time widget proving the ~0.45s block claim on every page load. Cards auto-light-up from coming-soon to live as each track ships.- [BNB Chain Live Block Race — 0.45s vs Base, Ethereum, Solana](https://three.ws/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.+- [Vault — Buy & Unlock Encrypted 3D Models on BNB Chain](https://three.ws/vault): Browse encrypted 3D listings, buy access with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle, then unlock and view the model — decrypted entirely client-side, the raw key never leaves your browser.- [watsonx Constellation](https://three.ws/constellation): Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.- [x402 Bazaar](https://three.ws/bazaar): Search and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click.- [x402 Live Demo (IBM × three.ws)](https://three.ws/ibm/x402-demo): A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.diff --git a/public/nav-data.js b/public/nav-data.jsindex 10be65e6b..76fd1a133 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -150,6 +150,11 @@ export const NAV_GROUPS = [href: '/bnb',desc: 'Gasless agent onboarding, an on-chain vault, and a real-time on-chain world — live 0.45s block proof',},+ {+ title: 'Vault',+ href: '/vault',+ desc: 'Buy encrypted 3D models gated by a real on-chain BNB Chain purchase — unlock and view in 3D',+ },{title: 'All pages',href: '/sitemap',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 9996901b1..c96300cde 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 409 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 410 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 409 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 410 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>@@ -718,7 +718,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>99</span></h2>+ <h2>Crypto<span class="sm-count" data-count>100</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -1212,6 +1212,13 @@<span class="sm-desc">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.</span></a></li>+ <li>+ <a href="/vault">+ <span class="sm-title">Vault — Buy & Unlock Encrypted 3D Models on BNB Chain</span>+ <span class="sm-path">/vault</span>+ <span class="sm-desc">Browse encrypted 3D listings, buy access with a real BSC testnet transaction, watch the cross-chain Greenfield permission grant settle, then unlock and view the model — decrypted entirely client-side, the raw key never leaves your browser.</span>+ </a>+ </li><li><a href="/constellation"><span class="sm-title">watsonx Constellation</span>diff --git a/scripts/tmp-verify-vault-ui.mjs b/scripts/tmp-verify-vault-ui.mjsnew file mode 100644index 000000000..f02a1c20f--- /dev/null+++ b/scripts/tmp-verify-vault-ui.mjs@@ -0,0 +1,480 @@+#!/usr/bin/env node+// Real, end-to-end browser proof for /vault (prompt 12) against a genuinely+// deployed GreenfieldVault on a local anvil fork — the same anvil-fork+// technique prompt 11 established, extended here to drive the REAL running+// HTTP endpoints (api/vault/*) and a REAL headless browser (Playwright)+// through the REAL page (pages/vault.html + src/vault.js), not a+// reimplementation of either. Throwaway verification script — not committed+// product code, deleted after use per CLAUDE.md repo-hygiene rules.+//+// What this proves for real:+// - GET /api/vault/list resolves a real on-chain Listed event to a card.+// - The buyer session key (src/bnb/vault-session.js) signs and sends a+// real buy() transaction against real deployed bytecode (self-pay path;+// MegaFuel sponsorship is naturally unreachable from an anvil chain id,+// so sendGasless's own fallback exercises for real too).+// - GET /api/vault/status polls and reflects real on-chain state+// (pending-grant -> unlocked) after a script-driven relayer call+// (playing the same role test/GreenfieldVault.t.sol's harness does).+// - POST /api/vault/unlock verifies a real EIP-191 signature, reads real+// on-chain Granted state, fetches a real (locally-mocked-SP) manifest,+// and returns a REAL ECIES-wrapped content key computed against the+// buyer's REAL recovered public key.+// - The browser's unwrapKey (src/bnb/vault-crypto-browser.js) correctly+// unwraps that real wrapped key using Web Crypto + @noble/curves.+// - GET /api/vault/download is proven to fail HONESTLY: it uses the full+// Greenfield SDK (real LCD chain lookup for a private-object ECDSA+// fetch), which cannot be mocked without a real Greenfield devnet — the+// same funded-account wall blocking 07/09/10/11/13/14/18. This is the+// expected, single remaining gap, not a bug.++import { spawn, execFileSync } from 'node:child_process';+import { createServer } from 'node:http';+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import net from 'node:net';++const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+const CONTRACTS_DIR = path.join(ROOT, 'contracts');++const ANVIL_PORT = 8555;+const ANVIL_RPC = `http://127.0.0.1:${ANVIL_PORT}`;+const API_PORT = 8091;+const VITE_PORT = 3100;+const SP_PORT = 9098;+const SP_HOST = `127.0.0.1.nip.io`; // wildcard DNS -> 127.0.0.1, lets bucket.<host> resolve++// Anvil's deterministic default accounts — parsed live from anvil's own+// startup banner (below) rather than transcribed, so a copy/paste slip can+// never silently produce an invalid key.+const ANVIL = { deployer: null, seller: null };++const results = [];+function log(step, ok, detail) {+ const line = `[${ok ? 'PASS' : 'FAIL'}] ${step}${detail ? ' — ' + detail : ''}`;+ console.log(line);+ results.push({ step, ok, detail });+}++function sleep(ms) {+ return new Promise((r) => setTimeout(r, ms));+}++async function waitForPort(port, host = '127.0.0.1', timeoutMs = 20000) {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ const ok = await new Promise((resolve) => {+ const sock = net.createConnection({ port, host }, () => {+ sock.end();+ resolve(true);+ });+ sock.on('error', () => resolve(false));+ });+ if (ok) return true;+ await sleep(250);+ }+ return false;+}++async function waitForHttp(url, timeoutMs = 20000) {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ try {+ const res = await fetch(url);+ if (res.status < 500) return true;+ } catch {+ /* not up yet */+ }+ await sleep(300);+ }+ return false;+}++const children = [];+function spawnTracked(cmd, args, opts) {+ const child = spawn(cmd, args, { ...opts, stdio: opts.stdio || 'pipe' });+ children.push(child);+ return child;+}++async function main() {+ // ── 1. anvil ──────────────────────────────────────────────────────────+ const anvil = spawnTracked('anvil', ['--chain-id', '97', '--port', String(ANVIL_PORT)], {+ cwd: ROOT,+ });+ let anvilOut = '';+ anvil.stdout.on('data', (d) => (anvilOut += d));+ anvil.stderr.on('data', (d) => (anvilOut += d));+ const anvilUp = await waitForPort(ANVIL_PORT);+ log('anvil --chain-id 97 up', anvilUp, anvilUp ? ANVIL_RPC : anvilOut.slice(0, 300));+ if (!anvilUp) return finish(1);+ for (let i = 0; i < 20 && !anvilOut.includes('Private Keys'); i++) await sleep(250); // let the startup banner finish printing+ const [addrSection, keySection] = anvilOut.split('Private Keys');+ const addrs = [...addrSection.matchAll(/^\(\d+\)\s+(0x[0-9a-fA-F]{40})\b/gm)].map((m) => m[1]);+ const keys = [...(keySection || '').matchAll(/^\(\d+\)\s+(0x[0-9a-fA-F]{64})\b/gm)].map(+ (m) => m[1],+ );+ ANVIL.deployer = { address: addrs[0], key: keys[0] };+ ANVIL.seller = { address: addrs[1], key: keys[1] };+ log(+ 'parsed anvil accounts from banner',+ !!(ANVIL.deployer.key && ANVIL.seller.key),+ `deployer=${ANVIL.deployer.address} seller=${ANVIL.seller.address}`,+ );+ if (!ANVIL.deployer.key || !ANVIL.seller.key) return finish(1);++ // ── 2. deploy GreenfieldVault (mocked hubs) via the real deploy script ──+ let deployOut;+ try {+ deployOut = execFileSync(+ 'forge',+ [+ 'script',+ 'script/DeployGreenfieldVaultMocked.s.sol:DeployGreenfieldVaultMocked',+ '--rpc-url',+ ANVIL_RPC,+ '--private-key',+ ANVIL.deployer.key,+ '--broadcast',+ ],+ { cwd: CONTRACTS_DIR, encoding: 'utf8', stdio: 'pipe' },+ );+ } catch (err) {+ log('forge script deploy', false, err.stdout || err.message);+ return finish(1);+ }+ const vaultAddr = /GreenfieldVault \(mocked hubs\):\s*(0x[0-9a-fA-F]{40})/.exec(deployOut)?.[1];+ const permHubAddr = /MockPermissionHub:\s*(0x[0-9a-fA-F]{40})/.exec(deployOut)?.[1];+ const objAccessAddr = /MockGnfdAccessControl:\s*(0x[0-9a-fA-F]{40})/.exec(deployOut)?.[1];+ log(+ 'forge script deploy',+ !!(vaultAddr && permHubAddr && objAccessAddr),+ `vault=${vaultAddr} permHub=${permHubAddr} objAccess=${objAccessAddr}`,+ );+ if (!vaultAddr) return finish(1);++ // ── 3. env for the in-process API server ────────────────────────────────+ process.env.GREENFIELD_VAULT_ADDRESS_TESTNET = vaultAddr;+ process.env.BNB_VAULT_RPC_OVERRIDE_TESTNET = ANVIL_RPC;+ process.env.GREENFIELD_VAULT_BUCKET_TESTNET = 'three-ws-vault-testnet';+ process.env.GREENFIELD_SP_OVERRIDE_TESTNET = `http://${SP_HOST}:${SP_PORT}`;+ process.env.JWT_SECRET = process.env.JWT_SECRET || 'tmp-verify-vault-ui-secret-not-for-prod';+ process.env.PORT = String(API_PORT);+ process.env.NODE_ENV = process.env.NODE_ENV || 'development';++ // ── 4. tiny mock Storage Provider — real HTTP, serves a real manifest ++ // real AES-256-GCM ciphertext produced by the REAL encryptGlb ──────+ const { encryptGlb } = await import(path.join(ROOT, 'api/_lib/bnb/vault-crypto.js'));+ const { deriveObjectId, storeVaultObjectIndex, vaultKeyCacheKey } = await import(+ path.join(ROOT, 'api/_lib/bnb/vault-store.js')+ );+ const { cacheSet } = await import(path.join(ROOT, 'api/_lib/cache.js'));+ const { encryptSecret } = await import(path.join(ROOT, 'api/_lib/secret-box.js'));++ const glbBytes = readFileSync(path.join(ROOT, 'public/accessories/glasses-shades.glb'));+ const enc = encryptGlb(glbBytes);+ const bucket = process.env.GREENFIELD_VAULT_BUCKET_TESTNET;+ const glbObject = `vaults/${ANVIL.seller.address.toLowerCase()}/e2e-proof.glb.enc`;+ const manifestObject = `vaults/${ANVIL.seller.address.toLowerCase()}/e2e-proof.manifest.json`;+ const objectId = deriveObjectId(bucket, glbObject);+ const priceWei = 10_000_000_000_000_000n; // 0.01 tBNB++ const manifest = {+ version: 1,+ glbObjectRef: { bucket, object: glbObject },+ encryption: {+ alg: 'AES-256-GCM',+ iv: enc.iv.toString('hex'),+ authTag: enc.authTag.toString('hex'),+ },+ sha256: enc.sha256OfPlaintext,+ priceAtomic: priceWei.toString(),+ sellerAddress: ANVIL.seller.address,+ contract: { address: vaultAddr, chainId: 97 },+ createdAt: new Date().toISOString(),+ };+ const manifestBytes = Buffer.from(JSON.stringify(manifest, null, 2));++ const spServer = createServer((req, res) => {+ const p = decodeURIComponent(req.url.replace(/^\//, ''));+ if (p === glbObject) {+ res.writeHead(200, {+ 'content-type': 'application/octet-stream',+ 'content-length': enc.ciphertext.length,+ });+ res.end(enc.ciphertext);+ return;+ }+ if (p === manifestObject) {+ res.writeHead(200, {+ 'content-type': 'application/json',+ 'content-length': manifestBytes.length,+ });+ res.end(manifestBytes);+ return;+ }+ res.writeHead(404).end('not found');+ });+ await new Promise((resolve) => spServer.listen(SP_PORT, resolve));+ children.push({ kill: () => spServer.close() });+ log(+ 'mock Storage Provider up',+ true,+ `${process.env.GREENFIELD_SP_OVERRIDE_TESTNET} serving real AES-256-GCM ciphertext (${enc.ciphertext.length}B) + manifest`,+ );++ // ── 5. populate the in-process objectId index + the encrypted content-key+ // record (same cache singleton the real running API server reads —+ // this is the off-chain glue vault-upload.js normally writes) ─────+ await storeVaultObjectIndex(objectId, {+ bucket,+ glbObject,+ manifestObject,+ sellerAddress: ANVIL.seller.address,+ });+ const contentKeyCiphertext = await encryptSecret(enc.contentKey.toString('base64'));+ await cacheSet(+ vaultKeyCacheKey(bucket, glbObject),+ {+ contentKeyCiphertext,+ sellerAddress: ANVIL.seller.address,+ createdAt: new Date().toISOString(),+ },+ 3600,+ );+ log(+ 'objectId index + content-key record populated (in-process cache)',+ true,+ `objectId=${objectId}`,+ );++ // ── 6. on-chain setup: grantRole + list() from the seller ───────────────+ const {+ createWalletClient,+ createPublicClient,+ http,+ parseAbi,+ keccak256,+ toBytes: viemToBytes,+ } = await import('viem');+ const { privateKeyToAccount } = await import('viem/accounts');+ const chain = {+ id: 97,+ name: 'anvil-97',+ nativeCurrency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 },+ rpcUrls: { default: { http: [ANVIL_RPC] } },+ };+ const pub = createPublicClient({ chain, transport: http() });+ const sellerAccount = privateKeyToAccount(ANVIL.seller.key);+ const sellerWallet = createWalletClient({ account: sellerAccount, chain, transport: http() });+ const deployerAccount = privateKeyToAccount(ANVIL.deployer.key);+ const deployerWallet = createWalletClient({+ account: deployerAccount,+ chain,+ transport: http(),+ });++ const accessAbi = parseAbi([+ 'function grantRole(bytes32 role, address grantee, uint256) external',+ ]);+ const ROLE_CREATE = keccak256(viemToBytes('ROLE_CREATE'));+ const grantHash = await sellerWallet.writeContract({+ address: objAccessAddr,+ abi: accessAbi,+ functionName: 'grantRole',+ args: [ROLE_CREATE, vaultAddr, 0n],+ });+ await pub.waitForTransactionReceipt({ hash: grantHash });++ const vaultAbi = parseAbi([+ 'function list(bytes32 objectId, uint256 price, address seller) external',+ ]);+ const listHash = await sellerWallet.writeContract({+ address: vaultAddr,+ abi: vaultAbi,+ functionName: 'list',+ args: [objectId, priceWei, sellerAccount.address],+ });+ await pub.waitForTransactionReceipt({ hash: listHash });+ log('seller grantRole + list() on real deployed contract', true, `list tx ${listHash}`);++ // ── 7. boot the REAL api server IN THIS PROCESS (shares the cache+ // singleton with step 5 — a separate process would not) ─────────+ await import(path.join(ROOT, 'server/index.mjs'));+ const apiUp = await waitForHttp(`http://127.0.0.1:${API_PORT}/api/vault/list?network=testnet`);+ log('real api server (server/index.mjs) up in-process', apiUp, `:${API_PORT}`);+ if (!apiUp) return finish(1);++ // sanity: the real endpoint resolves our real on-chain listing+ const listRes = await fetch(+ `http://127.0.0.1:${API_PORT}/api/vault/list?network=testnet&contractAddress=${vaultAddr}`,+ );+ const listBody = await listRes.json();+ log(+ 'GET /api/vault/list resolves the real listing',+ listBody.listings?.some((l) => l.objectId === objectId),+ JSON.stringify(listBody).slice(0, 300),+ );++ // ── 8. Vite dev server, proxying /api to the server we just booted ──────+ process.env.DEV_API_PROXY = `http://127.0.0.1:${API_PORT}`;+ const vite = spawnTracked('npx', ['vite', '--port', String(VITE_PORT), '--strictPort'], {+ cwd: ROOT,+ env: process.env,+ });+ let viteOut = '';+ vite.stdout.on('data', (d) => (viteOut += d));+ vite.stderr.on('data', (d) => (viteOut += d));+ const viteUp = await waitForHttp(`http://127.0.0.1:${VITE_PORT}/vault`, 30000);+ log('vite dev server up', viteUp, viteUp ? `:${VITE_PORT}` : viteOut.slice(-500));+ if (!viteUp) return finish(1);++ // ── 9. drive the REAL page with Playwright ───────────────────────────────+ const { chromium } = await import('playwright');+ const browser = await chromium.launch();+ const page = await browser.newPage();+ const consoleErrors = [];+ page.on('console', (msg) => {+ if (msg.type() === 'error') consoleErrors.push(msg.text());+ });+ page.on('pageerror', (err) => consoleErrors.push(String(err)));++ const pageUrl = `http://127.0.0.1:${VITE_PORT}/vault?devRpc=${encodeURIComponent(ANVIL_RPC)}&contractAddress=${vaultAddr}`;+ await page.goto(pageUrl, { waitUntil: 'networkidle' });+ log('page loaded', true, pageUrl);++ await page.waitForSelector('.vlt-card', { timeout: 15000 }).catch(() => {});+ const cardCount = await page.locator('.vlt-card').count();+ log('listing card rendered in the real grid', cardCount > 0, `${cardCount} card(s)`);++ await page.locator('.vlt-card').first().click();+ await page.waitForSelector('#vlt-drawer[data-open="true"]', { timeout: 5000 }).catch(() => {});+ const drawerOpen = (await page.locator('#vlt-drawer').getAttribute('data-open')) === 'true';+ log('detail drawer opens', drawerOpen);++ await page.waitForTimeout(1000); // let refreshStatus() settle+ const sessionAddr = await page.locator('#vlt-session-addr').getAttribute('title');+ log(+ 'session key generated client-side',+ !!sessionAddr && sessionAddr.startsWith('0x'),+ sessionAddr,+ );++ // Fund the session address directly from anvil's deployer (substitutes for+ // clicking through a real MetaMask popup, which Playwright cannot drive+ // without a real installed extension — the funding TX itself is still real).+ const fundHash = await deployerWallet.sendTransaction({+ to: sessionAddr,+ value: 50_000_000_000_000_000n,+ }); // 0.05 tBNB+ await pub.waitForTransactionReceipt({ hash: fundHash });+ log('session funded from anvil deployer', true, `fund tx ${fundHash}`);++ // Re-open the drawer so refreshSessionBalance() picks up the new balance.+ await page.locator('#vlt-drawer-close').click();+ await page.locator('.vlt-card').first().click();+ await page.waitForTimeout(800);++ const buyBtn = page.locator('#vlt-buy-btn');+ const buyVisible = await buyBtn.isVisible().catch(() => false);+ log('Buy button visible after funding', buyVisible);+ if (buyVisible) {+ await buyBtn.click();+ await page+ .waitForSelector('.vlt-step[data-state="done"]', { timeout: 20000 })+ .catch(() => {});+ const doneSteps = await page.locator('.vlt-step[data-state="done"]').count();+ log(+ 'real buy() tx confirmed (step 1 marked done)',+ doneSteps >= 1,+ `${doneSteps} step(s) done`,+ );+ }++ // Read the real on-chain saleId, then play the relayer: settle the grant.+ const saleAbi = parseAbi(['function saleIdOf(bytes32, address) view returns (uint256)']);+ let saleId = 0n;+ for (let i = 0; i < 20 && saleId === 0n; i++) {+ saleId = await pub.readContract({+ address: vaultAddr,+ abi: saleAbi,+ functionName: 'saleIdOf',+ args: [objectId, sessionAddr],+ });+ if (saleId === 0n) await sleep(500);+ }+ log('real on-chain saleId observed', saleId !== 0n, `saleId=${saleId}`);++ if (saleId !== 0n) {+ const permAbi = parseAbi([+ 'function settleCreatePolicy(uint256 policyId, uint32 status) external',+ ]);+ const settleHash = await deployerWallet.writeContract({+ address: permHubAddr,+ abi: permAbi,+ functionName: 'settleCreatePolicy',+ args: [saleId, 0],+ });+ await pub.waitForTransactionReceipt({ hash: settleHash });+ log(+ 'relayer settles the Greenfield grant (real PolicyGranted)',+ true,+ `settle tx ${settleHash}`,+ );+ }++ // Wait for the page's own poll (or force one) to observe Granted -> unlocked.+ await page+ .locator('#vlt-refresh-detail-btn')+ .click({ timeout: 3000 })+ .catch(() => {});+ await page.waitForSelector('#vlt-unlock-btn', { timeout: 20000 }).catch(() => {});+ const unlockVisible = await page+ .locator('#vlt-unlock-btn')+ .isVisible()+ .catch(() => false);+ log('page observes real Granted state -> shows Unlock button', unlockVisible);++ if (unlockVisible) {+ await page.locator('#vlt-unlock-btn').click();+ await page.waitForTimeout(4000);+ const note = await page+ .locator('.vlt-drawer-note')+ .last()+ .textContent()+ .catch(() => '');+ const viewerAppeared = (await page.locator('#vlt-viewer').count()) > 0;+ log(+ 'unlock attempt result',+ true,+ viewerAppeared+ ? `model-viewer rendered — full decrypt succeeded: "${note}"`+ : `stopped at: "${note}" (expected: download.js needs a real Greenfield SDK object, same funded-account wall as 07/09/10/11/13/14/18)`,+ );+ }++ log('zero console errors', consoleErrors.length === 0, consoleErrors.slice(0, 5).join(' | '));++ await page.screenshot({ path: '/tmp/vault-proof-final.png', fullPage: true }).catch(() => {});+ await browser.close();+ return finish(0);+}++function finish(code) {+ console.log('\n=== SUMMARY ===');+ for (const r of results) console.log(`${r.ok ? '✓' : '✗'} ${r.step}`);+ for (const c of children) {+ try {+ c.kill?.('SIGKILL');+ } catch {+ /* already dead */+ }+ }+ setTimeout(() => process.exit(code), 300);+}++main().catch((err) => {+ console.error('FATAL', err);+ finish(1);+});diff --git a/src/bnb/vault-buy.js b/src/bnb/vault-buy.jsnew file mode 100644index 000000000..f375cafe8--- /dev/null+++ b/src/bnb/vault-buy.js@@ -0,0 +1,157 @@+/**+ * Browser-side write helpers for `GreenfieldVault.sol` (prompt 10) — the+ * buyer/seller wallet calls the contract directly (per prompt 10's design:+ * "buying/listing/revoking happen from the buyer's/seller's own wallet+ * directly against the contract... not relayed through this server" — see+ * `api/_lib/bnb/vault-contract.js`'s module doc). This file only builds+ * calldata + reads the live relay-fee quote; it never holds or signs with a+ * key itself — the caller supplies a viem `Account`/`WalletClient`+ * (`vault-session.js`'s ephemeral buyer key, or a connected browser wallet+ * for the seller-listing flow).+ */++import { encodeFunctionData, parseAbi, encodeAbiParameters } from 'viem';+import { getPublicClient } from '../../api/_lib/bnb/chains.js';+import { quoteRelayFee, vaultClient } from '../../api/_lib/bnb/vault-contract.js';+import { sendGasless } from '../../api/_lib/bnb/megafuel.js';++/** Mirrors `contracts/src/GreenfieldVault.sol`'s external write surface exactly. */+export const GREENFIELD_VAULT_WRITE_ABI = parseAbi([+ 'function list(bytes32 objectId, uint256 price, address seller) external',+ 'function delist(bytes32 objectId) external',+ 'function buy(bytes32 objectId, bytes calldata policyData) external payable returns (uint256 saleId)',+ 'function revoke(uint256 saleId) external payable',+ 'function withdraw() external returns (uint256 amount)',+]);++/**+ * `policyData` is meant to be the real Greenfield `PermissionHub.createPolicy`+ * payload — a GNFD protobuf-encoded principal/resource/statement set built+ * off-chain against the object's real Greenfield resource id (see+ * `IPermissionHub.sol`'s doc comment). Building that encoder needs a REAL+ * Greenfield-mirrored object to encode a resource id for — which needs the+ * same funded Greenfield write path blocked across this whole campaign (07/+ * 09/10/11/13 PROGRESS entries). Byte-perfect GNFD protobuf is also not+ * something to guess at without a way to verify it against a live+ * PermissionHub. Until that unblocks, this returns a structurally-valid,+ * non-empty, deterministic placeholder (satisfies `buy()`'s `EmptyPolicyData`+ * guard) — the exact same posture the prompt-11 anvil E2E proof used+ * (`0xdeadbeef`), just object/buyer-scoped so two different purchases never+ * collide. Documented honestly in docs/bnb-vault.md; NOT wired to decode into+ * anything on a real PermissionHub yet.+ * @param {`0x${string}`} objectId @param {`0x${string}`} buyer+ * @returns {`0x${string}`}+ */+export function buildPolicyDataPlaceholder(objectId, buyer) {+ return encodeAbiParameters(+ [{ type: 'bytes32' }, { type: 'address' }, { type: 'string' }],+ [objectId, buyer, 'three.ws/vault/v1-placeholder'],+ );+}++/**+ * Resolve the `policyData` bytes for a `buy()` call: try the REAL+ * `GET /api/vault/buy-policy-data` first (real protobuf-encoded GNFD+ * `Policy`, see `api/_lib/bnb/vault-policy-data.js` — only succeeds for a+ * listing whose object has genuinely completed Greenfield upload+mirroring),+ * and fall back to `buildPolicyDataPlaceholder` on any 404/503 (true for+ * every listing today, per that module's own docstring — same funding wall+ * as everywhere else in this campaign). Progressive enhancement: zero+ * behavior change today, automatically starts using real bytes the moment a+ * listing's object is genuinely uploaded.+ * @param {{ objectId:`0x${string}`, buyer:`0x${string}`, network:'testnet'|'mainnet' }} p+ * @returns {Promise<`0x${string}`>}+ */+export async function resolvePolicyData({ objectId, buyer, network }) {+ try {+ const res = await fetch(+ `/api/vault/buy-policy-data?objectId=${objectId}&buyer=${buyer}&network=${network}`,+ {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(6000),+ },+ );+ if (res.ok) {+ const body = await res.json();+ if (body?.policyData) return body.policyData;+ }+ } catch {+ /* real path unavailable — honest fallback below */+ }+ return buildPolicyDataPlaceholder(objectId, buyer);+}++/**+ * Live-quote the BNB the buyer must send on top of `priceAtomic` for `buy()`+ * to cover the cross-chain relay fee — read fresh, never cached (fees drift+ * with BSC gas price).+ * @param {'testnet'|'mainnet'} network+ * @param {`0x${string}`} contractAddress+ * @param {{ client?: import('viem').PublicClient }} [opts]+ */+export async function quoteBuyRelayFee(network, contractAddress, opts = {}) {+ const client = opts.client || vaultClient(network);+ return quoteRelayFee(client, contractAddress);+}++/**+ * Send `buy(objectId, policyData)` from the buyer's session account, gasless+ * via MegaFuel when sponsorable (self-pay fallback always available — the+ * `msg.value` itself is never sponsored, only the gas fee).+ * @param {object} p+ * @param {import('viem').Account} p.account buyer's signer (vault-session.js)+ * @param {'testnet'|'mainnet'} p.network+ * @param {`0x${string}`} p.contractAddress+ * @param {`0x${string}`} p.objectId+ * @param {bigint} p.priceAtomic listing price, in wei+ * @param {{ publicClient?: import('viem').PublicClient }} [opts]+ * @returns {Promise<{ hash:`0x${string}`, mode:'sponsored'|'self-pay' }>}+ */+export async function sendBuyTx(+ { account, network, contractAddress, objectId, priceAtomic },+ opts = {},+) {+ const policyData =+ opts.policyData || (await resolvePolicyData({ objectId, buyer: account.address, network }));+ const client = opts.publicClient || vaultClient(network);+ const { total: relayFeeTotal } = await quoteRelayFee(client, contractAddress);+ const value = priceAtomic + relayFeeTotal;+ const data = encodeFunctionData({+ abi: GREENFIELD_VAULT_WRITE_ABI,+ functionName: 'buy',+ args: [objectId, policyData],+ });+ return sendGasless(+ chainNetworkKey(network),+ { account, tx: { to: contractAddress, value, data } },+ { publicClient: client },+ );+}++/**+ * Send `list(objectId, price, seller)` from the seller's own wallet (a+ * connected browser wallet — sellers hold no session key; only buyers do,+ * per vault-session.js's doc comment). No gasless path here on purpose: a+ * seller's browser wallet signs+sends directly, same as any other on-chain+ * write this platform doesn't relay.+ * @param {import('viem').WalletClient} walletClient connected seller wallet client (already on the right chain)+ * @param {`0x${string}`} contractAddress+ * @param {`0x${string}`} objectId+ * @param {bigint} priceAtomic+ * @param {`0x${string}`} seller+ */+export async function sendListTx(walletClient, contractAddress, objectId, priceAtomic, seller) {+ return walletClient.writeContract({+ address: contractAddress,+ abi: GREENFIELD_VAULT_WRITE_ABI,+ functionName: 'list',+ args: [objectId, priceAtomic, seller],+ account: seller,+ });+}++function chainNetworkKey(network) {+ return network === 'mainnet' ? 'bscMainnet' : 'bscTestnet';+}++export { getPublicClient };diff --git a/src/vault-crypto-browser.js b/src/vault-crypto-browser.jsdeleted file mode 100644index b67af6594..000000000--- a/src/vault-crypto-browser.js+++ /dev/null@@ -1,147 +0,0 @@-/**- * Browser-side counterpart to `api/_lib/bnb/vault-crypto.js` (prompts 08/12):- * unwrap a vault content key and decrypt a GLB, entirely client-side, so the- * plaintext model bytes and the raw content key never touch the network- * after `POST /api/vault/unlock` returns the wrapped bundle.- *- * Byte-for-byte the SAME wire format as the server module (ECIES: ephemeral- * secp256k1 ECDH -> HKDF-SHA256 -> AES-256-GCM) — verified by- * `tests/bnb-vault-crypto-browser.test.js`, which wraps with the server's- * real `wrapKey` and unwraps here. Two deliberate substitutions for- * browser-only APIs (CLAUDE.md: never hand-roll a primitive a library- * already provides):- * - ECDH + HKDF: `@noble/curves`/`@noble/hashes` — already a pinned- * workspace dependency, pure JS, identical behavior in Node and the- * browser (this is exactly why the server module picked them too).- * - AES-256-GCM: the browser's native `crypto.subtle` (Web Crypto API)- * instead of Node's `node:crypto` (unavailable in the browser). Web- * Crypto's `AES-GCM` expects the auth tag APPENDED to the ciphertext- * (not passed separately like Node's `createDecipheriv`/`setAuthTag`) —- * `concatCiphertextAndTag` below bridges that difference; the actual- * bytes on the wire are identical either way (GCM's tag is always the- * trailing 16 bytes of the sealed box).- */--import { secp256k1 } from '@noble/curves/secp256k1.js';-import { hkdf } from '@noble/hashes/hkdf.js';-import { sha256 } from '@noble/hashes/sha2.js';--const AES_KEY_LEN = 32;-const GCM_IV_LEN = 12;-const GCM_TAG_LEN = 16;-const ECDH_SECRET_LEN = 32;-// Must match api/_lib/bnb/vault-crypto.js's ECIES_HKDF_INFO exactly — a-// mismatch here would silently derive a different wrap key and every unwrap-// would fail with a (correct, but confusing) auth_failed.-const ECIES_HKDF_INFO = 'three.ws/bnb-vault/ecies/v1';--export class VaultCryptoBrowserError extends Error {- /** @param {string} message @param {{ code?: string, cause?: unknown }} [info] */- constructor(message, info = {}) {- super(message);- this.name = 'VaultCryptoBrowserError';- this.code = info.code || 'vault_crypto_error';- if (info.cause) this.cause = info.cause;- }-}--/** Coerce a hex string (with or without `0x`) or Uint8Array into a Uint8Array. */-function toBytes(input, label) {- if (input instanceof Uint8Array) return input;- if (typeof input === 'string') {- const hex = input.startsWith('0x') ? input.slice(2) : input;- if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) {- throw new VaultCryptoBrowserError(`${label} must be a Uint8Array or hex string`, { code: 'bad_input' });- }- const out = new Uint8Array(hex.length / 2);- for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);- return out;- }- throw new VaultCryptoBrowserError(`${label} must be a Uint8Array or hex string`, { code: 'bad_input' });-}--function assertLen(bytes, len, label) {- if (bytes.length !== len) {- throw new VaultCryptoBrowserError(`${label} must be ${len} bytes, got ${bytes.length}`, { code: 'bad_length' });- }- return bytes;-}--function concatBytes(...arrs) {- const total = arrs.reduce((n, a) => n + a.length, 0);- const out = new Uint8Array(total);- let off = 0;- for (const a of arrs) {- out.set(a, off);- off += a.length;- }- return out;-}--/**- * Unwrap a content key previously wrapped by the server's `wrapKey`, using- * the recipient's raw secp256k1 private key (hex or bytes). Wrong key derives- * a different AES key — the GCM tag check fails and this throws- * `VaultCryptoBrowserError{code:'auth_failed'}`, never silently returning- * garbage bytes.- * @param {{ ephemeralPublicKey: string|Uint8Array, iv: string|Uint8Array, authTag: string|Uint8Array, ciphertext: string|Uint8Array }} wrapped- * @param {string|Uint8Array} recipientPrivKey- * @returns {Promise<Uint8Array>} the original 32-byte content key- */-export async function unwrapKey(wrapped, recipientPrivKey) {- const privKey = assertLen(toBytes(recipientPrivKey, 'recipientPrivKey'), AES_KEY_LEN, 'recipientPrivKey');- const ephemeralPub = toBytes(wrapped.ephemeralPublicKey, 'ephemeralPublicKey');- const iv = assertLen(toBytes(wrapped.iv, 'iv'), GCM_IV_LEN, 'iv');- const authTag = assertLen(toBytes(wrapped.authTag, 'authTag'), GCM_TAG_LEN, 'authTag');- const ciphertext = toBytes(wrapped.ciphertext, 'ciphertext');-- let shared;- try {- shared = secp256k1.getSharedSecret(privKey, ephemeralPub, true);- } catch (err) {- throw new VaultCryptoBrowserError('invalid recipient private key or ephemeral public key', { code: 'bad_ecdh_input', cause: err });- }- const sharedX = shared.subarray(1, 1 + ECDH_SECRET_LEN);- const wrapKeyBytes = hkdf(sha256, sharedX, undefined, ECIES_HKDF_INFO, AES_KEY_LEN);-- const cryptoKey = await crypto.subtle.importKey('raw', wrapKeyBytes, { name: 'AES-GCM' }, false, ['decrypt']);- try {- const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, tagLength: GCM_TAG_LEN * 8 }, cryptoKey, concatBytes(ciphertext, authTag));- return new Uint8Array(plaintext);- } catch (err) {- throw new VaultCryptoBrowserError('key-unwrap authentication failed — wrong recipient key or tampered wrapped key', { code: 'auth_failed', cause: err });- }-}--/**- * Decrypt a GLB envelope client-side. Verifies the GCM auth tag (tampered- * ciphertext or wrong key throws `VaultCryptoBrowserError{code:'auth_failed'}`)- * and, if given, the plaintext's sha256 against the manifest's recorded value.- * @param {{ ciphertext: string|Uint8Array, contentKey: string|Uint8Array, iv: string|Uint8Array, authTag: string|Uint8Array }} envelope- * @param {{ expectedSha256?: string }} [opts]- * @returns {Promise<Uint8Array>} the original glbBytes- */-export async function decryptGlb({ ciphertext, contentKey, iv, authTag }, opts = {}) {- const key = assertLen(toBytes(contentKey, 'contentKey'), AES_KEY_LEN, 'contentKey');- const nonce = assertLen(toBytes(iv, 'iv'), GCM_IV_LEN, 'iv');- const tag = assertLen(toBytes(authTag, 'authTag'), GCM_TAG_LEN, 'authTag');- const ct = toBytes(ciphertext, 'ciphertext');-- const cryptoKey = await crypto.subtle.importKey('raw', key, { name: 'AES-GCM' }, false, ['decrypt']);- let plaintext;- try {- const buf = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce, tagLength: GCM_TAG_LEN * 8 }, cryptoKey, concatBytes(ct, tag));- plaintext = new Uint8Array(buf);- } catch (err) {- throw new VaultCryptoBrowserError('GCM authentication failed — ciphertext or key tampered/incorrect', { code: 'auth_failed', cause: err });- }-- if (opts.expectedSha256) {- const digest = await crypto.subtle.digest('SHA-256', plaintext);- const actual = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');- if (actual !== opts.expectedSha256) {- throw new VaultCryptoBrowserError('decrypted plaintext sha256 does not match the manifest', { code: 'sha256_mismatch' });- }- }- return plaintext;-}diff --git a/src/vault.css b/src/vault.cssnew file mode 100644index 000000000..f4d0fe631--- /dev/null+++ b/src/vault.css@@ -0,0 +1,660 @@+/* /vault page styles (prompt 12) — paired with pages/vault.html + src/vault.js. */++.vlt-wrap {+ max-width: 1180px;+ margin: 0 auto;+ padding: 0 24px 96px;+}+@media (max-width: 600px) {+ .vlt-wrap {+ padding: 0 16px 96px;+ }+}++/* ── Hero ─────────────────────────────────────────────────────────────── */+.vlt-hero {+ padding: 64px 0 28px;+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+}+.vlt-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;+}+.vlt-eyebrow a {+ color: inherit;+ text-decoration: none;+}+.vlt-eyebrow a:hover,+.vlt-eyebrow a:focus-visible {+ text-decoration: underline;+}+.vlt-eyebrow .dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: #f0b90b;+}+.vlt-hero h1 {+ font-family: var(--font-display, 'Space Grotesk', system-ui, sans-serif);+ font-size: clamp(30px, 4.6vw, 48px);+ font-weight: 700;+ letter-spacing: -0.03em;+ line-height: 1.08;+ margin: 0 0 16px;+ max-width: 20ch;+}+.vlt-hero p.lede {+ font-size: 16px;+ line-height: 1.65;+ color: var(--ink-dim, #888);+ margin: 0;+ max-width: 66ch;+}++/* ── Session strip ────────────────────────────────────────────────────── */+.vlt-session {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 10px 18px;+ padding: 16px 20px;+ margin: 24px 0 0;+ 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));+ font-size: 13px;+}+.vlt-session-item {+ display: flex;+ align-items: center;+ gap: 6px;+ color: var(--ink-dim, #888);+}+.vlt-session-item b,+.vlt-session-item code {+ color: var(--ink, #e8e8e8);+ font-weight: 600;+}+.vlt-session-item code {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ padding: 2px 6px;+ border-radius: 5px;+}+.vlt-net-badge {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 11px;+ font-weight: 600;+ padding: 3px 9px;+ border-radius: 999px;+ background: rgba(240, 185, 11, 0.12);+ color: #f0b90b;+ border: 1px solid rgba(240, 185, 11, 0.24);+}++/* ── Buttons ──────────────────────────────────────────────────────────── */+.vlt-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 8px 16px;+ border-radius: var(--radius-control, 10px);+ background: var(--surface-3, rgba(255, 255, 255, 0.08));+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ color: var(--ink, #e8e8e8);+ font-size: 13px;+ font-weight: 500;+ font-family: inherit;+ cursor: pointer;+ text-decoration: none;+ transition:+ background 0.14s,+ border-color 0.14s,+ transform 0.1s;+ margin-left: auto;+}+.vlt-btn:hover {+ background: rgba(255, 255, 255, 0.12);+ border-color: rgba(255, 255, 255, 0.22);+}+.vlt-btn:active {+ transform: translateY(1px);+}+.vlt-btn:focus-visible {+ outline: 2px solid #f0b90b;+ outline-offset: 2px;+}+.vlt-btn[disabled] {+ opacity: 0.5;+ cursor: default;+ pointer-events: none;+}+.vlt-btn-primary {+ background: #f0b90b;+ border-color: #f0b90b;+ color: #09090b;+ font-weight: 650;+ margin-left: 0;+}+.vlt-btn-primary:hover {+ background: #ffcb2e;+ border-color: #ffcb2e;+}+.vlt-btn-ghost {+ background: transparent;+ border-color: var(--stroke, rgba(255, 255, 255, 0.08));+}+a.vlt-btn {+ margin-left: 0;+}++/* ── Section headings ─────────────────────────────────────────────────── */+.vlt-section {+ padding: 44px 0 8px;+}+.vlt-section-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 16px;+ margin-bottom: 22px;+}+.vlt-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;+}+.vlt-section-sub {+ font-size: 13px;+ color: var(--ink-dim, #888);+ margin: 4px 0 0;+}++/* ── Contract banner (undeployed / chain-unavailable) ───────────────────── */+.vlt-banner {+ display: flex;+ align-items: flex-start;+ gap: 12px;+ padding: 16px 18px;+ border-radius: var(--radius-card, 14px);+ border: 1px solid rgba(240, 185, 11, 0.25);+ background: rgba(240, 185, 11, 0.07);+ font-size: 13px;+ line-height: 1.6;+ color: var(--ink, #e8e8e8);+ margin-bottom: 24px;+}+.vlt-banner svg {+ flex-shrink: 0;+ width: 18px;+ height: 18px;+ margin-top: 1px;+ color: #f0b90b;+}+.vlt-banner p {+ margin: 0;+ color: var(--ink-dim, #888);+}+.vlt-banner strong {+ color: var(--ink, #e8e8e8);+}+.vlt-banner 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;+}++/* ── Grid + cards ─────────────────────────────────────────────────────── */+.vlt-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));+ gap: 18px;+ min-height: 80px;+}+.vlt-card {+ display: flex;+ flex-direction: column;+ gap: 12px;+ padding: 0;+ 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));+ overflow: hidden;+ text-align: left;+ cursor: pointer;+ font-family: inherit;+ color: inherit;+ transition:+ border-color 0.18s,+ transform 0.18s,+ box-shadow 0.18s;+}+.vlt-card:hover,+.vlt-card:focus-visible {+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14));+ transform: translateY(-2px);+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.3);+}+.vlt-card:focus-visible {+ outline: 2px solid #f0b90b;+ outline-offset: -2px;+}+.vlt-card-art {+ aspect-ratio: 4 / 3;+ display: flex;+ align-items: center;+ justify-content: center;+ background: linear-gradient(135deg, rgba(240, 185, 11, 0.14), rgba(240, 185, 11, 0.03));+ color: rgba(240, 185, 11, 0.7);+}+.vlt-card-art svg {+ width: 40px;+ height: 40px;+}+.vlt-card-body {+ padding: 4px 16px 16px;+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.vlt-card-title {+ font-size: 14px;+ font-weight: 600;+ color: var(--ink, #e8e8e8);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.vlt-card-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ font-size: 12.5px;+ color: var(--ink-dim, #888);+}+.vlt-card-row code {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11.5px;+}+.vlt-card-price {+ font-family: var(--font-mono, ui-monospace, monospace);+ color: var(--ink, #e8e8e8);+ font-weight: 600;+}+.vlt-badge {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 10.5px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ padding: 3px 8px;+ border-radius: 999px;+ flex-shrink: 0;+}+.vlt-badge::before {+ content: '';+ width: 5px;+ height: 5px;+ border-radius: 50%;+}+.vlt-badge[data-state='locked'] {+ 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));+}+.vlt-badge[data-state='locked']::before {+ background: var(--ink-dim, #888);+}+.vlt-badge[data-state='pending-grant'] {+ background: rgba(240, 185, 11, 0.12);+ color: #f0b90b;+ border: 1px solid rgba(240, 185, 11, 0.24);+}+.vlt-badge[data-state='pending-grant']::before {+ background: #f0b90b;+ animation: vlt-pulse 1.4s ease-in-out infinite;+}+.vlt-badge[data-state='unlocked'] {+ background: rgba(74, 222, 128, 0.1);+ color: var(--success, #4ade80);+ border: 1px solid rgba(74, 222, 128, 0.2);+}+.vlt-badge[data-state='unlocked']::before {+ background: var(--success, #4ade80);+}+@keyframes vlt-pulse {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.35;+ }+}++/* ── Skeleton / empty / error states ─────────────────────────────────── */+.vlt-skel {+ aspect-ratio: 4 / 3;+ border-radius: var(--radius-card, 14px);+ background: linear-gradient(+ 100deg,+ var(--surface-1, rgba(255, 255, 255, 0.03)) 30%,+ var(--surface-2, rgba(255, 255, 255, 0.06)) 50%,+ var(--surface-1, rgba(255, 255, 255, 0.03)) 70%+ );+ background-size: 200% 100%;+ animation: vlt-shimmer 1.5s ease-in-out infinite;+}+@media (prefers-reduced-motion: reduce) {+ .vlt-skel,+ .vlt-badge[data-state='pending-grant']::before,+ .vlt-spinner {+ animation: none;+ }+}+@keyframes vlt-shimmer {+ 0% {+ background-position: 200% 0;+ }+ 100% {+ background-position: -200% 0;+ }+}+.vlt-empty,+.vlt-error {+ grid-column: 1 / -1;+ display: flex;+ flex-direction: column;+ align-items: center;+ text-align: center;+ gap: 12px;+ padding: 56px 24px;+ border: 1px dashed var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-radius: var(--radius-card, 14px);+ color: var(--ink-dim, #888);+}+.vlt-empty svg,+.vlt-error svg {+ width: 34px;+ height: 34px;+ opacity: 0.5;+}+.vlt-empty h3,+.vlt-error h3 {+ margin: 0;+ font-size: 15px;+ color: var(--ink, #e8e8e8);+}+.vlt-empty p,+.vlt-error p {+ margin: 0;+ font-size: 13px;+ max-width: 44ch;+}++/* ── Detail drawer ────────────────────────────────────────────────────── */+.vlt-drawer-backdrop {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.55);+ backdrop-filter: blur(2px);+ z-index: 200;+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.2s;+}+.vlt-drawer-backdrop[data-open='true'] {+ opacity: 1;+ pointer-events: auto;+}+.vlt-drawer {+ position: fixed;+ top: 0;+ right: 0;+ bottom: 0;+ width: min(480px, 100vw);+ background: var(--bg, #09090b);+ border-left: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ z-index: 201;+ display: flex;+ flex-direction: column;+ transform: translateX(100%);+ transition: transform 0.24s cubic-bezier(0.2, 0.8, 0.2, 1);+ overflow-y: auto;+}+.vlt-drawer[data-open='true'] {+ transform: translateX(0);+}+.vlt-drawer-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 18px 20px;+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+}+.vlt-drawer-close {+ width: 32px;+ height: 32px;+ border-radius: 8px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ color: var(--ink, #e8e8e8);+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+}+.vlt-drawer-close:hover {+ background: var(--surface-2, rgba(255, 255, 255, 0.06));+}+.vlt-drawer-close:focus-visible {+ outline: 2px solid #f0b90b;+}+.vlt-drawer-body {+ padding: 20px;+ display: flex;+ flex-direction: column;+ gap: 18px;+ flex: 1;+}+model-viewer#vlt-viewer,+.vlt-drawer-body model-viewer {+ width: 100%;+ aspect-ratio: 1 / 1;+ border-radius: var(--radius-card, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+}+.vlt-detail-meta {+ display: flex;+ flex-direction: column;+ gap: 6px;+ font-size: 13px;+}+.vlt-detail-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ color: var(--ink-dim, #888);+}+.vlt-detail-row b {+ color: var(--ink, #e8e8e8);+}+.vlt-detail-row code {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11.5px;+ color: var(--ink, #e8e8e8);+}+.vlt-progress {+ display: flex;+ flex-direction: column;+ gap: 10px;+}+.vlt-step {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ font-size: 13px;+ color: var(--ink-dim, #888);+}+.vlt-step[data-state='done'] {+ color: var(--ink, #e8e8e8);+}+.vlt-step[data-state='active'] {+ color: #f0b90b;+}+.vlt-step-dot {+ width: 16px;+ height: 16px;+ border-radius: 50%;+ border: 2px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ flex-shrink: 0;+ margin-top: 1px;+}+.vlt-step[data-state='done'] .vlt-step-dot {+ border-color: var(--success, #4ade80);+ background: var(--success, #4ade80);+}+.vlt-step[data-state='active'] .vlt-step-dot {+ border-color: #f0b90b;+ animation: vlt-pulse 1.2s ease-in-out infinite;+}+.vlt-drawer-actions {+ display: flex;+ flex-direction: column;+ gap: 10px;+}+.vlt-drawer-note {+ font-size: 12px;+ color: var(--ink-dim, #888);+ line-height: 1.6;+ margin: 0;+}+.vlt-drawer-note[data-tone='error'] {+ color: var(--danger, #ef4444);+}+.vlt-drawer-note[data-tone='success'] {+ color: var(--success, #4ade80);+}++/* ── Sell panel ───────────────────────────────────────────────────────── */+.vlt-sell {+ 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));+}+.vlt-sell summary {+ cursor: pointer;+ padding: 16px 20px;+ font-size: 14px;+ font-weight: 600;+ list-style: none;+ display: flex;+ align-items: center;+ gap: 8px;+}+.vlt-sell summary::-webkit-details-marker {+ display: none;+}+.vlt-sell summary::after {+ content: '+';+ margin-left: auto;+ font-size: 18px;+ color: var(--ink-dim, #888);+}+.vlt-sell[open] summary::after {+ content: '−';+}+.vlt-sell summary:focus-visible {+ outline: 2px solid #f0b90b;+ outline-offset: 2px;+ border-radius: 6px;+}+.vlt-sell-body {+ padding: 0 20px 20px;+ display: flex;+ flex-direction: column;+ gap: 12px;+}+.vlt-field {+ display: flex;+ flex-direction: column;+ gap: 5px;+}+.vlt-field label {+ font-size: 12px;+ color: var(--ink-dim, #888);+}+.vlt-field input {+ padding: 9px 12px;+ border-radius: var(--radius-control, 10px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ background: var(--surface-2, rgba(255, 255, 255, 0.04));+ color: var(--ink, #e8e8e8);+ font-family: inherit;+ font-size: 13px;+}+.vlt-field input:focus-visible {+ outline: 2px solid #f0b90b;+ outline-offset: 1px;+}+.vlt-sell-log {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11.5px;+ color: var(--ink-dim, #888);+ white-space: pre-wrap;+ word-break: break-all;+ max-height: 160px;+ overflow-y: auto;+ padding: 10px 12px;+ border-radius: 8px;+ background: var(--surface-2, rgba(255, 255, 255, 0.04));+}++/* ── Honesty footer ───────────────────────────────────────────────────── */+.vlt-honesty {+ margin-top: 44px;+ padding: 20px 22px;+ 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));+ font-size: 12.5px;+ line-height: 1.65;+ color: var(--ink-dim, #888);+}+.vlt-honesty h3 {+ margin: 0 0 8px;+ font-size: 13px;+ color: var(--ink, #e8e8e8);+}+.vlt-honesty 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;+}++@media (max-width: 600px) {+ .vlt-drawer {+ width: 100vw;+ }+}diff --git a/src/vault.js b/src/vault.jsnew file mode 100644index 000000000..a3920edec--- /dev/null+++ b/src/vault.js@@ -0,0 +1,647 @@+// /vault — browse, buy, unlock, and view encrypted 3D models gated by a+// BNB Chain purchase (prompt 12, BNB Chain campaign Track B).+//+// Wallet model (see src/bnb/vault-session.js's docstring for the full+// rationale): the vault's unlock key delivery is ECIES over secp256k1 —+// recovering the wrapped content key needs the buyer's RAW private key,+// which a browser-extension wallet (MetaMask) deliberately never exposes.+// So the actual "buyer" identity for buy() + the unlock signature + the+// client-side decrypt is a local session key (src/bnb/vault-session.js,+// same pattern src/agora/onchain-presence.js already established on this+// platform). MetaMask's ONLY role on the buy side is funding that session+// key with a plain native-token transfer. Sellers, by contrast, use a+// directly-connected MetaMask wallet (no ECIES involved in list()).+//+// Flow: browse (GET /list) -> select -> connect/fund session -> buy() on+// GreenfieldVault -> poll GET /status ("granting access on Greenfield…" is+// surfaced honestly, never hidden) -> POST /unlock -> unwrap the content key+// + download ciphertext (GET /download) -> decrypt client-side -> render in+// <model-viewer>.++import { escapeHtml as esc } from './shared/coin-format.js';+import {+ createPublicClient,+ createWalletClient,+ http,+ custom,+ formatEther,+ parseEther,+} from 'viem';+import {+ buildVaultUnlockMessage,+ generateUnlockNonce,+} from '../api/_lib/bnb/vault-unlock-message.js';+import {+ getVaultSessionAccount,+ getVaultSessionPrivateKey,+ resetVaultSession,+} from './bnb/vault-session.js';+import { quoteBuyRelayFee, sendBuyTx, sendListTx } from './bnb/vault-buy.js';+import { unwrapKey, decryptGlb } from './bnb/vault-crypto-browser.js';+import {+ deriveListingState,+ nextFlowStep,+ formatBnbAtomic,+ truncateAddress,+ pollDelayMs,+} from './vault-fsm.js';++const $ = (id) => document.getElementById(id);+const qs = new URLSearchParams(location.search);++// Dev/E2E-proof escape hatches ONLY — mirror the server's own `?contractAddress=`+// override (api/vault/list.js) and `BNB_VAULT_RPC_OVERRIDE_TESTNET` (vault-contract.js).+// Unset in normal use; a real visitor's URL never carries these.+const DEV_RPC = qs.get('devRpc') || '';+const DEV_CONTRACT = qs.get('contractAddress') || '';++const BSC_TESTNET = {+ id: 97,+ name: 'BNB Smart Chain Testnet',+ nativeCurrency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 },+ rpcUrls: { default: { http: [DEV_RPC || 'https://data-seed-prebsc-1-s1.bnbchain.org:8545'] } },+ blockExplorers: { default: { name: 'BscScan', url: 'https://testnet.bscscan.com' } },+ testnet: true,+};++const NETWORK = 'testnet';+const POLL_ATTEMPTS_BEFORE_MANUAL = 12; // ~90s of bounded backoff before "still settling"++const state = {+ listings: [],+ listStatus: 'loading', // loading | ready | empty | error+ listError: null,+ contractAddress: null,+ contractDeployed: false,+ session: null, // { address, balance }+ detail: null, // { listing, flow, pollAttempt, glbBlobUrl, glbFilename }+ message: null, // { tone, text }+};++const publicClient = createPublicClient({ chain: BSC_TESTNET, transport: http() });++function apiUrl(path, extra = {}) {+ const u = new URL(path, location.origin);+ u.searchParams.set('network', NETWORK);+ if (DEV_CONTRACT) u.searchParams.set('contractAddress', DEV_CONTRACT);+ for (const [k, v] of Object.entries(extra)) if (v != null) u.searchParams.set(k, v);+ return u.toString();+}++const svgAlert =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="12" r="9" /><path d="M12 8v5M12 16h.01" /></svg>';++// ── Session (buyer identity) ────────────────────────────────────────────++async function refreshSessionBalance() {+ const account = getVaultSessionAccount();+ let balance = state.session?.balance ?? 0n;+ try {+ balance = await publicClient.getBalance({ address: account.address });+ } catch {+ /* RPC hiccup — keep the last known balance rather than showing 0 */+ }+ state.session = { address: account.address, balance };+ $('vlt-session-addr').textContent = truncateAddress(account.address);+ $('vlt-session-addr').title = account.address;+ $('vlt-session-balance').textContent = `${formatEther(balance)} tBNB`;+}++/** Connect MetaMask (or any EIP-1193 injected wallet) purely to fund the session key with a plain native-token transfer. */+async function fundSessionFromWallet() {+ if (!window.ethereum) {+ alert(+ 'No browser wallet detected — install MetaMask, or fund your session address directly from the BSC testnet faucet:\n' ++ state.session.address,+ );+ return;+ }+ const amountStr = prompt(+ 'How much tBNB to send to your vault session address? (e.g. 0.02)',+ '0.02',+ );+ if (!amountStr) return;+ let amount;+ try {+ amount = parseEther(amountStr);+ } catch {+ alert('Enter a valid tBNB amount, e.g. 0.02');+ return;+ }+ const btn = $('vlt-fund-btn');+ const prevLabel = btn.textContent;+ btn.disabled = true;+ btn.textContent = 'Funding…';+ try {+ const walletClient = createWalletClient({+ chain: BSC_TESTNET,+ transport: custom(window.ethereum),+ });+ const [from] = await walletClient.requestAddresses();+ try {+ await walletClient.switchChain({ id: BSC_TESTNET.id });+ } catch (switchErr) {+ if (+ switchErr?.code === 4902 ||+ /Unrecognized chain/i.test(String(switchErr?.message))+ ) {+ await walletClient.addChain({ chain: BSC_TESTNET });+ await walletClient.switchChain({ id: BSC_TESTNET.id });+ } else {+ throw switchErr;+ }+ }+ const hash = await walletClient.sendTransaction({+ account: from,+ chain: BSC_TESTNET,+ to: state.session.address,+ value: amount,+ });+ btn.textContent = 'Confirming…';+ await publicClient.waitForTransactionReceipt({ hash });+ await refreshSessionBalance();+ } catch (err) {+ alert(+ `Funding failed: ${err?.shortMessage || err?.message || 'wallet rejected the transaction'}`,+ );+ } finally {+ btn.disabled = false;+ btn.textContent = prevLabel;+ }+}++// ── Browse ───────────────────────────────────────────────────────────────++function renderBanner() {+ const el = $('vlt-banner-slot');+ if (state.contractDeployed !== false || state.listStatus === 'loading') {+ el.innerHTML = '';+ return;+ }+ el.innerHTML = `<div class="vlt-banner" role="status">${svgAlert}<p><strong>The GreenfieldVault contract isn't deployed on this network yet.</strong> This is the honest state until BNB testnet deploy funding lands — see <code>contracts/DEPLOYMENTS.md</code>.</p></div>`;+}++async function loadListings() {+ state.listStatus = 'loading';+ renderGrid();+ try {+ const res = await fetch(apiUrl('/api/vault/list'), {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(10000),+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const body = await res.json();+ state.contractAddress = body.contractAddress;+ state.contractDeployed = body.contractDeployed;+ state.listings = body.listings || [];+ state.listStatus = state.listings.length ? 'ready' : 'empty';+ } catch (err) {+ state.listStatus = 'error';+ state.listError = err.message;+ }+ renderBanner();+ renderGrid();+}++function listingCard(listing) {+ const name = listing.glbObjectRef?.object?.split('/').pop() || 'Untitled model';+ return `+ <button type="button" class="vlt-card" data-object-id="${esc(listing.objectId)}">+ <div class="vlt-card-art" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4"><path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z" /><path d="M3 7l9 5 9-5M12 12v10" /></svg>+ </div>+ <div class="vlt-card-body">+ <div class="vlt-card-title" title="${esc(name)}">${esc(name)}</div>+ <div class="vlt-card-row"><span class="vlt-card-price">${esc(formatBnbAtomic(listing.priceAtomic))}</span><span class="vlt-badge" data-state="locked">Locked</span></div>+ <div class="vlt-card-row">Seller <code>${esc(truncateAddress(listing.seller))}</code></div>+ </div>+ </button>+ `;+}++function renderGrid() {+ const el = $('vlt-grid');+ if (state.listStatus === 'loading') {+ el.innerHTML = Array.from({ length: 6 })+ .map(() => '<div class="vlt-skel" aria-hidden="true"></div>')+ .join('');+ return;+ }+ if (state.listStatus === 'error') {+ el.innerHTML = `<div class="vlt-error" role="alert">${svgAlert}<h3>Couldn't load vault listings</h3><p>${esc(state.listError || 'the API is unreachable')}</p></div>`;+ return;+ }+ if (state.listStatus === 'empty') {+ el.innerHTML = `<div class="vlt-empty">${svgAlert}<h3>${state.contractDeployed ? 'No models listed yet' : 'Nothing to browse yet'}</h3><p>${+ state.contractDeployed+ ? 'List yours below — encrypt, upload to Greenfield, and list on the vault contract.'+ : 'Once the vault contract is deployed and a seller lists a model, it shows up here automatically.'+ }</p></div>`;+ return;+ }+ el.innerHTML = state.listings.map(listingCard).join('');+ el.querySelectorAll('[data-object-id]').forEach((card) =>+ card.addEventListener('click', () => {+ const listing = state.listings.find((l) => l.objectId === card.dataset.objectId);+ if (listing) openDetail(listing);+ }),+ );+}++// ── Detail drawer: buy → settle → unlock → view ─────────────────────────++function openDrawer() {+ $('vlt-backdrop').dataset.open = 'true';+ $('vlt-drawer').dataset.open = 'true';+ $('vlt-drawer').setAttribute('aria-hidden', 'false');+ $('vlt-drawer-close').focus();+}++function closeDrawer() {+ stopPolling();+ $('vlt-backdrop').dataset.open = 'false';+ $('vlt-drawer').dataset.open = 'false';+ $('vlt-drawer').setAttribute('aria-hidden', 'true');+ if (state.detail?.glbBlobUrl) URL.revokeObjectURL(state.detail.glbBlobUrl);+ state.detail = null;+}++function stopPolling() {+ if (state.detail?.pollTimer) clearTimeout(state.detail.pollTimer);+ if (state.detail) state.detail.pollTimer = null;+}++async function openDetail(listing) {+ state.detail = {+ listing,+ flow: 'available',+ pollAttempt: 0,+ glbBlobUrl: null,+ glbFilename: null,+ note: null,+ noteTone: 'info',+ };+ $('vlt-drawer-title').textContent = listing.glbObjectRef?.object?.split('/').pop() || 'Model';+ openDrawer();+ renderDetail();+ await refreshSessionBalance();+ await refreshStatus();+}++async function refreshStatus() {+ const d = state.detail;+ if (!d) return;+ try {+ const res = await fetch(+ apiUrl('/api/vault/status', {+ objectId: d.listing.objectId,+ buyer: state.session.address,+ }),+ {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(10000),+ },+ );+ const body = await res.json();+ if (!res.ok) throw new Error(body?.message || `HTTP ${res.status}`);+ const derived = deriveListingState({+ contractDeployed: body.contractDeployed,+ listingActive: body.listing?.active,+ saleId: body.saleId,+ saleStatus: body.saleStatus,+ });+ const step = nextFlowStep({+ walletConnected: true,+ listingState: derived,+ hasDecrypted: !!d.glbBlobUrl,+ });+ d.flow = step === 'buy' ? 'available' : step;+ if (d.flow === 'pending-grant') schedulePoll();+ else stopPolling();+ } catch (err) {+ d.note = `Couldn't read purchase status: ${err.message}`;+ d.noteTone = 'error';+ }+ renderDetail();+}++function schedulePoll() {+ const d = state.detail;+ if (!d) return;+ stopPolling();+ if (d.pollAttempt >= POLL_ATTEMPTS_BEFORE_MANUAL) {+ renderDetail(); // shows the "still settling — check back" manual-refresh state+ return;+ }+ d.pollTimer = setTimeout(() => {+ if (!state.detail) return; // drawer closed meanwhile+ d.pollAttempt += 1;+ refreshStatus();+ }, pollDelayMs(d.pollAttempt));+}++async function buyListing() {+ const d = state.detail;+ if (!d) return;+ d.note = 'Preparing purchase…';+ d.noteTone = 'info';+ renderDetail();+ try {+ const account = getVaultSessionAccount();+ const priceAtomic = BigInt(d.listing.priceAtomic);+ const { total: relayFeeTotal } = await quoteBuyRelayFee(NETWORK, state.contractAddress, {+ client: publicClient,+ });+ const needed = priceAtomic + relayFeeTotal;+ if (state.session.balance < needed) {+ d.note = `Session needs ${formatEther(needed)} tBNB (price + relay fee) — currently has ${formatEther(state.session.balance)}. Fund it above first.`;+ d.noteTone = 'error';+ renderDetail();+ return;+ }+ d.note = 'Confirming purchase on-chain…';+ renderDetail();+ const { hash, mode } = await sendBuyTx(+ {+ account,+ network: NETWORK,+ contractAddress: state.contractAddress,+ objectId: d.listing.objectId,+ priceAtomic,+ },+ { publicClient },+ );+ d.note = `Purchase tx ${mode === 'sponsored' ? '(gasless via MegaFuel) ' : ''}submitted: ${truncateAddress(hash)} — waiting for confirmation…`;+ renderDetail();+ await publicClient.waitForTransactionReceipt({ hash });+ d.flow = 'pending-grant';+ d.note = 'Purchase confirmed on-chain. Granting access on Greenfield…';+ d.noteTone = 'success';+ d.pollAttempt = 0;+ renderDetail();+ await refreshSessionBalance();+ schedulePoll();+ } catch (err) {+ d.note = `Purchase failed: ${err?.shortMessage || err?.message || 'wallet rejected the transaction'}`;+ d.noteTone = 'error';+ renderDetail();+ }+}++async function unlockAndView() {+ const d = state.detail;+ if (!d) return;+ d.note = 'Signing unlock request…';+ d.noteTone = 'info';+ renderDetail();+ try {+ const account = getVaultSessionAccount();+ const message = buildVaultUnlockMessage({+ objectId: d.listing.objectId,+ buyer: account.address,+ network: NETWORK,+ nonce: generateUnlockNonce(),+ issuedAt: new Date().toISOString(),+ });+ const signature = await account.signMessage({ message });++ d.note = 'Verifying purchase and fetching your wrapped key…';+ renderDetail();+ const res = await fetch('/api/vault/unlock', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ objectId: d.listing.objectId,+ buyer: account.address,+ network: NETWORK,+ message,+ signature,+ }),+ signal: AbortSignal.timeout(15000),+ });+ const body = await res.json();+ if (!res.ok) throw new Error(body?.message || `HTTP ${res.status}`);+ if (body.state === 'pending-grant') {+ d.note = body.pollHint || 'Still settling — try again shortly.';+ d.noteTone = 'info';+ d.flow = 'pending-grant';+ renderDetail();+ schedulePoll();+ return;+ }++ d.note = 'Unwrapping content key…';+ renderDetail();+ const contentKey = await unwrapKey(body.wrappedKey, getVaultSessionPrivateKey());++ d.note = 'Downloading encrypted model…';+ renderDetail();+ const dl = await fetch(+ `/api/vault/download?objectId=${d.listing.objectId}&network=${NETWORK}&buyer=${account.address}&token=${encodeURIComponent(body.downloadToken)}`,+ { signal: AbortSignal.timeout(60000) },+ );+ if (!dl.ok) {+ const errBody = await dl.json().catch(() => ({}));+ throw new Error(errBody?.message || `download failed (HTTP ${dl.status})`);+ }+ const ciphertext = new Uint8Array(await dl.arrayBuffer());++ d.note = 'Decrypting…';+ renderDetail();+ const plaintext = await decryptGlb(+ {+ ciphertext,+ contentKey,+ iv: body.manifest?.encryption?.iv,+ authTag: body.manifest?.encryption?.authTag,+ },+ { expectedSha256: body.manifest?.sha256 },+ );++ const blob = new Blob([plaintext], { type: 'model/gltf-binary' });+ d.glbBlobUrl = URL.createObjectURL(blob);+ d.glbFilename = (d.listing.glbObjectRef?.object || 'vault-model').split('/').pop();+ d.flow = 'viewing';+ d.note = 'Unlocked — model decrypted and sha256-verified locally.';+ d.noteTone = 'success';+ renderDetail();+ } catch (err) {+ d.note = `Unlock failed: ${err.message || 'unknown error'} — likely the wrong key or corrupted ciphertext.`;+ d.noteTone = 'error';+ renderDetail();+ }+}++const STEP_LABELS = [+ { key: 'buy', label: 'Purchase confirmed on-chain' },+ { key: 'grant', label: 'Greenfield permission granted' },+ { key: 'unlock', label: 'Key unwrapped & model decrypted' },+];++function stepState(stepKey, flow) {+ const order = { available: 0, pending: 0, 'pending-grant': 1, unlocked: 2, viewing: 3 };+ const idx = order[flow] ?? 0;+ const target = { buy: 1, grant: 2, unlock: 3 }[stepKey];+ if (idx >= target) return 'done';+ if (idx === target - 1) return 'active';+ return 'pending';+}++function renderDetail() {+ const d = state.detail;+ const el = $('vlt-drawer-body');+ if (!d || !el) return;++ const progressHtml = `<div class="vlt-progress">${STEP_LABELS.map(+ (s) =>+ `<div class="vlt-step" data-state="${stepState(s.key, d.flow)}"><span class="vlt-step-dot" aria-hidden="true"></span>${esc(s.label)}</div>`,+ ).join('')}</div>`;++ let actionHtml = '';+ let viewerHtml = '';+ if (d.flow === 'available') {+ actionHtml = `<button type="button" class="vlt-btn vlt-btn-primary" id="vlt-buy-btn">Buy for ${esc(formatBnbAtomic(d.listing.priceAtomic))} (+ relay fee)</button>`;+ } else if (d.flow === 'pending-grant') {+ const stuck = d.pollAttempt >= POLL_ATTEMPTS_BEFORE_MANUAL;+ actionHtml = stuck+ ? `<button type="button" class="vlt-btn" id="vlt-refresh-detail-btn">Check again</button>`+ : `<button type="button" class="vlt-btn" disabled>Granting access…</button>`;+ } else if (d.flow === 'unlocked') {+ actionHtml = `<button type="button" class="vlt-btn vlt-btn-primary" id="vlt-unlock-btn">Unlock & view</button>`;+ } else if (d.flow === 'viewing') {+ actionHtml = `<a class="vlt-btn vlt-btn-primary" id="vlt-download-btn" download="${esc(d.glbFilename || 'model.glb')}" href="${d.glbBlobUrl}">Download GLB</a>`;+ viewerHtml = `<model-viewer id="vlt-viewer" src="${d.glbBlobUrl}" camera-controls auto-rotate shadow-intensity="1" alt="Unlocked 3D model"></model-viewer>`;+ } else if (d.flow === 'unlisted') {+ actionHtml = `<p class="vlt-drawer-note">This listing is no longer active.</p>`;+ }++ el.innerHTML = `+ ${viewerHtml}+ <div class="vlt-detail-meta">+ <div class="vlt-detail-row"><span>Price</span><b>${esc(formatBnbAtomic(d.listing.priceAtomic))}</b></div>+ <div class="vlt-detail-row"><span>Seller</span><code>${esc(truncateAddress(d.listing.seller))}</code></div>+ ${d.listing.sha256 ? `<div class="vlt-detail-row"><span>sha256</span><code>${esc(d.listing.sha256.slice(0, 16))}…</code></div>` : ''}+ </div>+ ${progressHtml}+ <div class="vlt-drawer-actions">+ ${actionHtml}+ ${d.note ? `<p class="vlt-drawer-note" data-tone="${d.noteTone || 'info'}">${esc(d.note)}</p>` : ''}+ </div>+ `;+ $('vlt-buy-btn')?.addEventListener('click', buyListing);+ $('vlt-unlock-btn')?.addEventListener('click', unlockAndView);+ $('vlt-refresh-detail-btn')?.addEventListener('click', () => {+ d.pollAttempt = 0;+ refreshStatus();+ });+}++// ── Sell panel ───────────────────────────────────────────────────────────++function sellLog(text) {+ const el = $('vlt-sell-log');+ el.hidden = false;+ el.textContent += (el.textContent ? '\n' : '') + text;+ el.scrollTop = el.scrollHeight;+}++async function connectAndList() {+ const glbUrl = $('vlt-sell-url').value.trim();+ const priceStr = $('vlt-sell-price').value.trim();+ if (!glbUrl || !priceStr) {+ alert('Enter a GLB URL and a price first.');+ return;+ }+ if (!window.ethereum) {+ alert('No browser wallet detected — install MetaMask to list a model.');+ return;+ }+ let priceWei;+ try {+ priceWei = parseEther(priceStr);+ } catch {+ alert('Enter a valid tBNB price, e.g. 0.01');+ return;+ }+ $('vlt-sell-log').textContent = '';+ const btn = $('vlt-sell-connect');+ btn.disabled = true;+ try {+ const walletClient = createWalletClient({+ chain: BSC_TESTNET,+ transport: custom(window.ethereum),+ });+ const [seller] = await walletClient.requestAddresses();+ sellLog(`Connected: ${seller}`);+ try {+ await walletClient.switchChain({ id: BSC_TESTNET.id });+ } catch (switchErr) {+ if (switchErr?.code === 4902) {+ await walletClient.addChain({ chain: BSC_TESTNET });+ await walletClient.switchChain({ id: BSC_TESTNET.id });+ } else throw switchErr;+ }++ sellLog('Uploading + encrypting GLB on Greenfield…');+ const upRes = await fetch('/api/bnb/vault-upload', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ glbUrl,+ sellerAddress: seller,+ priceAtomic: priceWei.toString(),+ network: NETWORK,+ }),+ signal: AbortSignal.timeout(60000),+ });+ const upBody = await upRes.json();+ if (!upRes.ok) throw new Error(upBody?.message || `upload failed (HTTP ${upRes.status})`);+ sellLog(`Uploaded — objectId ${upBody.objectId}`);++ if (!state.contractDeployed) {+ sellLog(+ 'GreenfieldVault is not deployed on this network yet — the object is encrypted and stored, but cannot be listed until deploy funding lands.',+ );+ return;+ }++ sellLog('Listing on GreenfieldVault…');+ const hash = await sendListTx(+ walletClient,+ state.contractAddress,+ upBody.objectId,+ priceWei,+ seller,+ );+ sellLog(`list() submitted: ${hash} — waiting for confirmation…`);+ await publicClient.waitForTransactionReceipt({ hash });+ sellLog('Listed. Refreshing the grid…');+ await loadListings();+ } catch (err) {+ sellLog(`Failed: ${err?.shortMessage || err?.message || String(err)}`);+ } finally {+ btn.disabled = false;+ }+}++// ── Boot ─────────────────────────────────────────────────────────────────++function init() {+ $('vlt-fund-btn')?.addEventListener('click', fundSessionFromWallet);+ $('vlt-refresh-btn')?.addEventListener('click', loadListings);+ $('vlt-drawer-close')?.addEventListener('click', closeDrawer);+ $('vlt-backdrop')?.addEventListener('click', closeDrawer);+ document.addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && $('vlt-drawer').dataset.open === 'true') closeDrawer();+ });+ $('vlt-sell-connect')?.addEventListener('click', connectAndList);+ refreshSessionBalance();+ loadListings();+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);+else init();++// Exposed for a "reset session" affordance if a future revision wants one+// (not wired into this HTML's session strip — kept out of the way here).+export { resetVaultSession };diff --git a/tests/bnb-vault-fsm.test.js b/tests/bnb-vault-fsm.test.jsnew file mode 100644index 000000000..82395870e--- /dev/null+++ b/tests/bnb-vault-fsm.test.js@@ -0,0 +1,108 @@+// Unit tests for src/vault-fsm.js — the pure state-machine/formatting helpers+// backing the /vault page (prompt 12). No DOM, no network: every branch of+// deriveListingState/nextFlowStep is exercised table-style so the UI's+// buy → settle → unlock progression is provably correct independent of+// mounting the page. See prompts/bnb-chain/12-vault-ui.md's "Tests" section.++import { describe, it, expect } from 'vitest';+import { deriveListingState, nextFlowStep, formatBnbAtomic, truncateAddress, pollDelayMs, SALE_STATUS, FLOW_STEPS } from '../src/vault-fsm.js';++describe('deriveListingState', () => {+ it('is unlisted when the contract is not deployed, regardless of other fields', () => {+ expect(deriveListingState({ contractDeployed: false, listingActive: true, saleId: '1', saleStatus: 'Granted' })).toBe('unlisted');+ });+ it('is unlisted when never listed (saleId 0, listing inactive)', () => {+ expect(deriveListingState({ contractDeployed: true, listingActive: false, saleId: 0n })).toBe('unlisted');+ });+ it('is available when listed and no purchase yet', () => {+ expect(deriveListingState({ contractDeployed: true, listingActive: true, saleId: '0' })).toBe('available');+ });+ it('is pending-grant when purchased but not yet Granted', () => {+ expect(deriveListingState({ contractDeployed: true, listingActive: true, saleId: '1', saleStatus: 'Pending' })).toBe('pending-grant');+ });+ it('is unlocked once the sale status is Granted', () => {+ expect(deriveListingState({ contractDeployed: true, listingActive: true, saleId: '1', saleStatus: 'Granted' })).toBe('unlocked');+ });+ it('accepts saleId as bigint, string, or number interchangeably', () => {+ const base = { contractDeployed: true, listingActive: true, saleStatus: 'Granted' };+ expect(deriveListingState({ ...base, saleId: 1n })).toBe('unlocked');+ expect(deriveListingState({ ...base, saleId: '1' })).toBe('unlocked');+ expect(deriveListingState({ ...base, saleId: 1 })).toBe('unlocked');+ });+});++describe('nextFlowStep', () => {+ it('routes to connect when the wallet/session is not ready', () => {+ expect(nextFlowStep({ walletConnected: false, listingState: 'available', hasDecrypted: false })).toBe('connect');+ });+ it('routes unlisted straight through', () => {+ expect(nextFlowStep({ walletConnected: true, listingState: 'unlisted', hasDecrypted: false })).toBe('unlisted');+ });+ it('routes available to buy', () => {+ expect(nextFlowStep({ walletConnected: true, listingState: 'available', hasDecrypted: false })).toBe('buy');+ });+ it('routes pending-grant through unchanged', () => {+ expect(nextFlowStep({ walletConnected: true, listingState: 'pending-grant', hasDecrypted: false })).toBe('pending-grant');+ });+ it('routes unlocked-but-not-yet-decrypted to unlocked (show the Unlock button)', () => {+ expect(nextFlowStep({ walletConnected: true, listingState: 'unlocked', hasDecrypted: false })).toBe('unlocked');+ });+ it('routes unlocked-and-decrypted to viewing (render the model)', () => {+ expect(nextFlowStep({ walletConnected: true, listingState: 'unlocked', hasDecrypted: true })).toBe('viewing');+ });+});++describe('formatBnbAtomic', () => {+ it('formats a whole-BNB atomic value with no fractional remainder', () => {+ expect(formatBnbAtomic('2000000000000000000')).toBe('2 BNB');+ });+ it('formats a fractional atomic value, trimming trailing zeros', () => {+ expect(formatBnbAtomic('1500000000000000000')).toBe('1.5 BNB');+ });+ it('formats zero', () => {+ expect(formatBnbAtomic('0')).toBe('0 BNB');+ });+ it('accepts a bigint directly', () => {+ expect(formatBnbAtomic(1_000_000_000_000_000_000n)).toBe('1 BNB');+ });+ it('never throws on garbage input — returns an em dash', () => {+ expect(formatBnbAtomic('not-a-number')).toBe('—');+ expect(formatBnbAtomic(undefined)).toBe('0 BNB');+ });+});++describe('truncateAddress', () => {+ it('truncates a real EVM address to 0x1234…abcd form', () => {+ expect(truncateAddress('0x1234567890abcdef1234567890abcdef12345678')).toBe('0x1234…5678');+ });+ it('passes through a non-address string unchanged', () => {+ expect(truncateAddress('not-an-address')).toBe('not-an-address');+ });+ it('never throws on null/undefined', () => {+ expect(truncateAddress(null)).toBe('');+ expect(truncateAddress(undefined)).toBe('');+ });+});++describe('pollDelayMs', () => {+ it('grows with attempt number and is capped at 8000ms', () => {+ const d0 = pollDelayMs(0);+ const d1 = pollDelayMs(1);+ const d10 = pollDelayMs(10);+ expect(d1).toBeGreaterThan(d0);+ expect(d10).toBeLessThanOrEqual(8000);+ });+ it('never returns a negative or zero delay for attempt 0', () => {+ expect(pollDelayMs(0)).toBeGreaterThan(0);+ });+});++describe('static tables', () => {+ it('SALE_STATUS mirrors the contract enum order', () => {+ expect(SALE_STATUS).toEqual(['Pending', 'Granted', 'Failed', 'Revoked']);+ });+ it('FLOW_STEPS is a well-formed ordered list', () => {+ expect(FLOW_STEPS).toContain('browse');+ expect(FLOW_STEPS).toContain('unlocked');+ });+});diff --git a/vercel.json b/vercel.jsonindex a879b6fad..a89a1e560 100644--- a/vercel.json+++ b/vercel.json@@ -4815,6 +4815,14 @@"src": "/vaults/","dest": "/vaults.html"},+ {+ "src": "/vault",+ "dest": "/vault.html"+ },+ {+ "src": "/vault/",+ "dest": "/vault.html"+ },{"src": "/play/ufo","dest": "/play/ufo.html"diff --git a/vite.config.js b/vite.config.jsindex d3ee0df4a..4049d731e 100644--- a/vite.config.js+++ b/vite.config.js@@ -479,6 +479,7 @@ const appConfig = {stablecoins: resolve(__dirname, 'pages/stablecoins.html'),bnb: resolve(__dirname, 'pages/bnb.html'),'bnb-latency': resolve(__dirname, 'pages/bnb-latency.html'),+ vault: resolve(__dirname, 'pages/vault.html'),trending: resolve(__dirname, 'pages/trending.html'),compose: resolve(__dirname, 'pages/compose.html'),'create-next': resolve(__dirname, 'pages/create-next.html'),@@ -1030,6 +1031,8 @@ support: resolve(__dirname, 'pages/support.html'),'/bnb/': resolve(root, 'pages/bnb.html'),'/bnb-latency': resolve(root, 'pages/bnb-latency.html'),'/bnb-latency/': resolve(root, 'pages/bnb-latency.html'),+ '/vault': resolve(root, 'pages/vault.html'),+ '/vault/': resolve(root, 'pages/vault.html'),'/compose': resolve(root, 'pages/compose.html'),'/compose/': resolve(root, 'pages/compose.html'),'/create/next': resolve(root, 'pages/create-next.html'),