Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
chore: land further in-progress platform work (concurrent session snapshot)
nirholas2cd7e38b12fa
diff --git a/.env.example b/.env.exampleindex e506fde93..51b23e026 100644--- a/.env.example+++ b/.env.example@@ -356,6 +356,28 @@ NODEREAL_MEGAFUEL_KEY=# proofs. Generate a throwaway: node -e "console.log(require('viem/accounts').generatePrivateKey())"# then fund the address from https://www.bnbchain.org/en/testnet-faucet. Never commit a real key.BNB_TESTNET_DEPLOYER_KEY=+# Deployed WorldMoves.sol (contracts/src/WorldMoves.sol) contract address per+# network, read by api/_lib/bnb/world-moves.js's worldMovesAddress(). BSC+# mainnet is unused this campaign; BSC testnet deploy is currently blocked on+# BNB_TESTNET_DEPLOYER_KEY above (see contracts/DEPLOYMENTS.md's WorldMoves+# section) — set this the moment `forge script script/DeployWorldMoves.s.sol+# --broadcast` produces a real public-testnet address. Until set, any call+# that needs the address (buildMoveTx/sendMove without an explicit+# opts.address) throws a clear "not deployed yet" error rather than guessing.+WORLD_MOVES_ADDRESS_MAINNET=+WORLD_MOVES_ADDRESS_TESTNET=+# Greenfield vault platform account (prompt 09/11 — api/_lib/bnb/greenfield-write.js,+# api/bnb/vault-upload.js). Creates buckets/objects on Greenfield on behalf of+# sellers; same secp256k1 curve as a BSC EOA, so it falls back to+# BNB_TESTNET_DEPLOYER_KEY above when unset — one funded throwaway key can drive+# both legs. Generate + fund the same way as BNB_TESTNET_DEPLOYER_KEY. Never+# commit a real key.+GREENFIELD_VAULT_OPERATOR_KEY=+# Greenfield bucket that hosts every vault object (default matches+# specs/vault-manifest.md's example). Must be a globally unique, DNS-safe+# Greenfield bucket name (lowercase letters/digits/hyphens, 3-63 chars).+GREENFIELD_VAULT_BUCKET_TESTNET=three-ws-vault-testnet+GREENFIELD_VAULT_BUCKET_MAINNET=three-ws-vault-mainnet# Dedicated EIP-712 signing key for signed offers and payment receipts (USE-17).# This is a dedicated signing key, NOT a wallet that holds funds. Generate with:# node -e "console.log(require('viem/accounts').generatePrivateKey())"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 102f40e34..1ca9c75b1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -42,6 +42,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Give your agent a 3D body in one call — the new Embodiment endpoint** — Any AI agent can now buy itself a real presence in a single USDC payment: POST a name plus a text description (or a reference photo) to the new Embodiment endpoint and get back a rigged, animated, talking 3D avatar, a durable persona id that reloads in any future session, and a one-tag embed snippet for any website. It's the same free generate-and-rig chain that powers the 3D Studio, packaged as one paid call — no separate rigging step, no account. Generation failures never settle, so a buyer is only ever charged for a finished body. (`/docs/embody`) `[feature]`- **Live block-speed race: watch BNB Chain confirm in ~0.45s** — A new /bnb-latency page races BNB Chain against Base, Ethereum, and Solana in real time, sampling real blocks off public RPCs every few seconds — never a hardcoded number. Each lane shows its live measured average and a rolling sparkline; a chain going quiet shows "reconnecting" instead of a frozen fake reading. (`/bnb-latency`) `[feature]`- **Live DeFi yield and market-sentiment data: new fear/greed and yield-pool APIs** — A new market-data layer pulls real-time DeFi yield pools and protocol TVL from DeFiLlama, backing a new GET /api/intel/yields endpoint that returns live yield pools filterable by chain, project, and stablecoin status, sorted by TVL. This lays the groundwork for yield-discovery features and a smarter trading copilot on top of real, cached, non-fabricated market data. (`/docs/api-reference`) `[feature]`+- **Live liquidations pulse on the markets page — real-time long/short pain across Binance, Bybit, and OKX** — A new standalone collector subscribes to the public futures liquidation WebSocket streams of Binance, Bybit, and OKX, classifies each liquidation by size, and keeps a rolling 4-hour window. /coins now shows a live strip under the global stats bar: a LONG PAIN / SHORT SQUEEZE / BALANCED badge, 1h long-vs-short liquidated USD bars, and the three largest recent liquidations — each linking to its coin page. It polls every 30 seconds, pauses when the tab isn't visible, and quietly shows an offline line (never fake numbers) if the collector is unreachable. (`/coins`) `[feature]`- **Markets goes deep — Screener, Categories, Exchanges, Derivatives, Converter, DeFi, Chains, Stablecoins** — Eight new tools join the Markets suite, all live data and all free. Screener filters the top 250 coins by market cap, volume, and 24h move. Categories ranks every crypto sector so you can see which narrative leads. Exchanges ranks venues by trust score and volume. Derivatives shows perpetual-futures funding, open interest, and volume. Converter turns any crypto into any major fiat at live rates. And a DeFi trio — DeFi TVL by protocol, Chains by total value locked, and Stablecoins with peg health — brings on-chain liquidity into view via DeFiLlama. Every one is cross-linked from the markets table. (`/screener`) `[feature]`- **Minted 3D assets now carry a second, independently-signed provenance record — and remixing one pays the original creator on the spot** — Every 3D avatar generated on three.ws now gets a signed authorship record on the platform's append-only agent_actions ledger the moment it's created — the same cryptographically-verifiable trail @three-ws/provenance-mcp reads, now written automatically instead of only on request. Minting a generated GLB as a Solana NFT (mint_3d_asset) links its own signed ledger entry alongside the provenance already baked into the NFT metadata. And when a mint names another creator's asset as its parent (a remix), the original creator's royalty share now settles immediately as a real on-chain USDC transfer out of the mint fee — not just a royalty term for a future resale. Every minted 3D asset is also now listed in a public launch directory at GET /api/v1/tokenized/launches, the NFT counterpart to the existing coin-launch feed. (`/docs/mcp`) `[feature, improvement]`- **New free API: check if a wallet holds a Binance Account Bound Token (BABT)** — GET /api/bnb/babt-check?address=0x... tells you whether a BSC address holds a BABT — Binance's non-transferable, KYC-backed on-chain token. It's a real, live signal (1.16M+ holders on BSC mainnet) that developers can use as a free, no-signup uniqueness check for allowlists, anti-sybil gating, or airdrop targeting on BNB Chain. `[feature]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex f2c6d1286..429f18b50 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -51,7 +51,7 @@ bottom.| Production server (Google Cloud Run) | [server/](server) + [Dockerfile](Dockerfile) | Live | Single Express container serving the static frontend, the vercel.json route table, and all `api/**` handlers with Vercel-parity routing; deploy via `npm run deploy:gcp` ([server/cloudbuild.yaml](server/cloudbuild.yaml)), crons via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs) · see [server/README.md](server/README.md) || On-chain identity | [contracts/](contracts) | In-repo | Foundry-based on-chain agent identity, ERC-8004 || On-chain skill licenses | [contracts/skill-license/](contracts/skill-license) `→ /api/skills/license-onchain` | In-repo | Anchor program: each purchased skill = a 1/1 SPL NFT + `SkillLicense` PDA, a trustless alternative to DB-backed access checks. Backend: [api/_lib/skill-license-onchain.js](api/_lib/skill-license-onchain.js) |-| Tokenized 3D (mint an avatar as an NFT) | [api/_lib/tokenize-3d.js](api/_lib/tokenize-3d.js) + [api/_lib/tokenize-3d-metadata.js](api/_lib/tokenize-3d-metadata.js), MCP tools [api/_mcp/tools/tokenize.js](api/_mcp/tools/tokenize.js) (`mint_3d_asset`, `get_3d_asset_onchain`), signed ledger provenance [api/_lib/asset-provenance.js](api/_lib/asset-provenance.js), launch directory [api/v1/tokenized/launches.js](api/v1/tokenized/launches.js) `→ GET /api/v1/tokenized/launches` | In-repo | Mint a generated/owned GLB as a Metaplex Core NFT whose media is a live 3D viewer (GLB under `animation_url`), with baked provenance + enforced capped royalties (10%), idempotent, devnet-default. Every generated avatar AND every mint also appends an ERC-191-signed record to the `agent_actions` ledger (verifiable via `@three-ws/provenance-mcp`'s `query_action`). A mint naming `parent_mint` (a remix) routes the parent creator's royalty out of the mint fee as a real on-chain USDC transfer (mainnet, x402-collected calls only) — [api/_lib/remix-royalty.js](api/_lib/remix-royalty.js) split math, [api/_lib/remix-settlement.js](api/_lib/remix-settlement.js) payout wallet. Launch record: [tokenized_3d_assets](api/_lib/migrations/20260707120000_tokenized_3d_assets.sql) + [remix-royalty columns](api/_lib/migrations/20260708130000_tokenized_3d_remix_royalty.sql). Docs: [docs/mcp.md](docs/mcp.md#mint_3d_asset). E2E: [scripts/tokenize-3d-devnet-e2e.mjs](scripts/tokenize-3d-devnet-e2e.mjs). Tests: [tests/tokenize-3d.test.js](tests/tokenize-3d.test.js), [tests/tokenize-3d-remix-royalty.test.js](tests/tokenize-3d-remix-royalty.test.js), [tests/asset-provenance.test.js](tests/asset-provenance.test.js) |+| Tokenized 3D (mint an avatar as an NFT) | [api/_lib/tokenize-3d.js](api/_lib/tokenize-3d.js) + [api/_lib/tokenize-3d-metadata.js](api/_lib/tokenize-3d-metadata.js), MCP tools [api/_mcp/tools/tokenize.js](api/_mcp/tools/tokenize.js) (`mint_3d_asset`, `get_3d_asset_onchain`), signed ledger provenance [api/_lib/asset-provenance.js](api/_lib/asset-provenance.js), launch directory [api/v1/tokenized/launches.js](api/v1/tokenized/launches.js) `→ GET /api/v1/tokenized/launches`, public gallery [pages/minted.html](pages/minted.html) + [src/minted.js](src/minted.js) `→ /minted` | In-repo | Mint a generated/owned GLB as a Metaplex Core NFT whose media is a live 3D viewer (GLB under `animation_url`), with baked provenance + enforced capped royalties (10%), idempotent, devnet-default. Every generated avatar AND every mint also appends an ERC-191-signed record to the `agent_actions` ledger (verifiable via `@three-ws/provenance-mcp`'s `query_action`). A mint naming `parent_mint` (a remix) routes the parent creator's royalty out of the mint fee as a real on-chain USDC transfer (mainnet, x402-collected calls only) — [api/_lib/remix-royalty.js](api/_lib/remix-royalty.js) split math, [api/_lib/remix-settlement.js](api/_lib/remix-settlement.js) payout wallet. Premium/token-gated generation: the Forge High tier (200k poly + PBR) is $THREE hold-or-pay gated — [api/forge.js](api/forge.js) `requireFeatureAccess('forge.high')` + [api/_lib/three-tier.js](api/_lib/three-tier.js) tier ladder, x402 pay-per-use or credits fallback; Draft/Standard stay free and ungated. Launch record: [tokenized_3d_assets](api/_lib/migrations/20260707120000_tokenized_3d_assets.sql) + [remix-royalty columns](api/_lib/migrations/20260708130000_tokenized_3d_remix_royalty.sql). Public gallery: `/minted` renders the launch directory live (model-viewer thumbnails, network toggle, royalty + remix badges) — the NFT counterpart of `/launches`. Docs: [docs/mcp.md](docs/mcp.md#mint_3d_asset). E2E: [scripts/tokenize-3d-devnet-e2e.mjs](scripts/tokenize-3d-devnet-e2e.mjs). Tests: [tests/tokenize-3d.test.js](tests/tokenize-3d.test.js), [tests/tokenize-3d-remix-royalty.test.js](tests/tokenize-3d-remix-royalty.test.js), [tests/asset-provenance.test.js](tests/asset-provenance.test.js) || Token-gated 3D embeds (holder-only interactive scenes) | Gate config + on-chain verify [api/_lib/embed-gate.js](api/_lib/embed-gate.js), access tokens [api/_lib/embed-gate-token.js](api/_lib/embed-gate-token.js), endpoints [api/embed/gate-create.js](api/embed/gate-create.js) + [api/embed/gate-verify.js](api/embed/gate-verify.js), gate-aware resolver [api/embed/resolve.js](api/embed/resolve.js), MCP tool [api/_mcp/tools/embed.js](api/_mcp/tools/embed.js) (`create_gated_embed`), widget [public/embed/v1.js](public/embed/v1.js) (`<three-d>`) + standalone host [public/embed/v1/gated.html](public/embed/v1/gated.html) `→ /embed/v1/gated` | In-repo | `create_gated_embed(asset_id, gate)` turns an avatar or on-chain agent you own into a holder-only interactive `<three-d>` embed — visitors must prove a real, server-verified SPL balance (SIWS challenge → nonce → signature → Solana RPC read, never a client-reported number) before the live scene renders; below the bar they see a designed locked teaser + connect-wallet CTA. `mint` defaults to $THREE but is a runtime parameter (coin-agnostic plumbing). Anti-abuse: short-lived signed access tokens (auto re-verify on expiry) + per-IP/per-wallet rate limits. Storage: [embed_gates + embed_gate_nonces](api/_lib/migrations/20260708120000_embed_gates.sql). Spec: [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md#token-gating). Docs: [docs/token-gated-3d-embeds.md](docs/token-gated-3d-embeds.md). Tests: [tests/embed-gate.test.js](tests/embed-gate.test.js) || Launch Studio (coin-launch use cases) | [api/_lib/launch/](api/_lib/launch) `→ /launch-studio`, [api/pump/launch-studio.js](api/pump/launch-studio.js), [public/launch-studio/launch-studio.js](public/launch-studio/launch-studio.js) | In-repo | Engine + catalog of 50 declarative launch recipes — reward coins for trending GitHub repos/creators ([github-trending.js](api/_lib/github-trending.js)) and coins riding live narratives ([launcher-trends.js](api/_lib/launcher-trends.js)). Live preview → `/launch` handoff. Docs: [docs/launch-usecases.md](docs/launch-usecases.md), [api/_lib/launch/README.md](api/_lib/launch/README.md) || Avatar Seeder control room | [pages/admin/seeder.html](pages/admin/seeder.html) + [src/admin-seeder.js](src/admin-seeder.js) `→ /admin/seeder`, backend [api/admin/seeder.js](api/admin/seeder.js) | In-repo (admin, noindex) | Arm/disarm the headless [Avaturn seed cron](api/cron/avaturn-seed-cron.js), watch live throughput + rig rate, and preview freshly-forged rigged avatars in 3D. Toggles the `avaturn_seed` runtime flag. Flags: [api/_lib/flags.js](api/_lib/flags.js) + [api/admin/flags.js](api/admin/flags.js). Docs: [docs/ops/runtime-flags.md](docs/ops/runtime-flags.md) |@@ -70,6 +70,7 @@ bottom.| Global markets + coin detail pages | [pages/coins.html](pages/coins.html) + [src/coins-index.js](src/coins-index.js) `→ /coins`, [pages/coin.html](pages/coin.html) + [src/coin-page.js](src/coin-page.js) `→ /coin/:id`, backend [api/coin/](api/coin) (detail, ohlc, markets, news, global over [api/_lib/coingecko.js](api/_lib/coingecko.js)) | In-repo | CoinGecko-style markets index (global stats bar, sortable top-coins table, search, sparklines) + a rich detail page per coin (interactive chart, stats grid, related news, links). Design adopted from cryptocurrency.cv; accepts CoinGecko slugs or Solana mints. Docs: [docs/coin-pages.md](docs/coin-pages.md) || Market tools (heatmap, sentiment, gas, compare) | [pages/heatmap.html](pages/heatmap.html) + [src/heatmap.js](src/heatmap.js) `→ /heatmap`, [pages/fear-greed.html](pages/fear-greed.html) + [src/fear-greed.js](src/fear-greed.js) `→ /fear-greed`, [pages/gas.html](pages/gas.html) + [src/gas.js](src/gas.js) `→ /gas`, [pages/compare.html](pages/compare.html) + [src/compare.js](src/compare.js) `→ /compare`; backend [api/coin/fear-greed.js](api/coin/fear-greed.js), [api/coin/gas.js](api/coin/gas.js) | In-repo | Four tools extending Markets, same design system: treemap heatmap (market-cap-sized tiles), Fear & Greed gauge + history, live Ethereum gas tracker (keyless `eth_feeHistory`), and up-to-4-coin compare (overlay perf + stats). All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) || Market tools II (screener, categories, exchanges, derivatives, converter, DeFi, chains, stablecoins) | Pages+JS `→ /screener /categories /exchanges /derivatives /converter /defi /chains /stablecoins`; backend [api/coin/](api/coin) (categories, exchanges, derivatives, rates) over CoinGecko + [api/defi/](api/defi) (protocols, chains, stablecoins) over DeFiLlama | In-repo | Eight more Markets tools, same design system: token screener + category rankings + exchange/derivatives tables + crypto⇄fiat converter (CoinGecko), plus a DeFiLlama trio — DeFi TVL by protocol, chains by TVL, stablecoins with peg health. All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |+| 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 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. |@@ -87,6 +88,7 @@ character-studio/ → @m3-org/characterstudio (fork)mcp-bridge/ → @three-ws/mcp-bridgemcp-server/ → @three-ws/mcp-servermultiplayer/ → @three-ws/multiplayer+services/liquidation-collector/ → @three-ws/liquidation-collector (standalone Binance/Bybit/OKX liquidation stream collector, ported from SperaxOS)packages/avatar-schema/ → @three-ws/avatar-schemapackages/avatar-cli/ → @three-ws/avatar-clipackages/retarget/ → @three-ws/retarget (humanoid bone canonicalizer + clip retargeting engine, extracted from src/)diff --git a/api/_lib/bnb/greenfield-write.js b/api/_lib/bnb/greenfield-write.jsnew file mode 100644index 000000000..09d04d5c5--- /dev/null+++ b/api/_lib/bnb/greenfield-write.js@@ -0,0 +1,328 @@+/**+ * BNB Greenfield WRITE client — bucket/object creation + ciphertext upload,+ * built on `@bnb-chain/greenfield-js-sdk`. Composed by the vault upload+ * pipeline (prompt 09); pairs with the read-only `greenfield.js` (prompt 07).+ *+ * Why the SDK here (unlike greenfield.js's plain-`fetch` read path): creating+ * a bucket/object is NOT a plain REST call — it is a signed Greenfield+ * transaction (broadcast to the chain) that requires Reed-Solomon+ * erasure-coded checksums computed client-side up front, followed by a+ * separate authenticated PUT of the actual bytes to a Storage Provider. The+ * SDK exists specifically to save every caller from hand-rolling that+ * protobuf/EIP-712/erasure-coding dance, so per this prompt's brief it is+ * used directly rather than reimplemented (contrast with 00-CONTEXT's+ * "wrap the minimal REST yourself" default, which applies to the READ path+ * only). Reference implementation this module mirrors line-for-line:+ * bnb-chain/greenfield-js-sdk `examples/nodejs-file-management/storage.js`.+ *+ * Two-phase, asynchronous by protocol design (00-CONTEXT: "cross-chain /+ * storage ops settle async — poll for effect, never assume same-block"):+ * 1. `createObject` broadcasts a Greenfield tx that lands the object as+ * `OBJECT_STATUS_CREATED` (metadata only, no bytes yet).+ * 2. `uploadObject` PUTs the real bytes to the primary Storage Provider,+ * which seals the object (`OBJECT_STATUS_SEALED`) some time later.+ * `createObject()` below polls the read client's `getObjectMeta` with bounded+ * exponential backoff and returns `status:'pending'` honestly if sealing+ * hasn't landed inside the budget — never a lie that the bytes are ready.+ *+ * The platform (not the seller) holds the Greenfield signing account — sellers+ * only ever hold a BSC address for payment (recorded in the vault manifest as+ * `sellerAddress`), never a Greenfield keypair. This is a managed-storage+ * model: `GREENFIELD_VAULT_OPERATOR_KEY` (api/_lib/env.js) is the platform's+ * own account, reused across every seller's uploads. Every write helper here+ * also accepts an explicit `privateKey`/`client` in `opts` for tests and for+ * a future self-custodied mode — see `tests/bnb-greenfield-write.test.js`.+ */++import { Client, Long, VisibilityType, RedundancyType } from '@bnb-chain/greenfield-js-sdk';+import { bytesFromBase64 } from '@bnb-chain/greenfield-cosmos-types/helpers.js';+import { ReedSolomon } from '@bnb-chain/reed-solomon';+import { privateKeyToAccount } from 'viem/accounts';++import { greenfieldNetwork, headBucket, getObjectMeta, GreenfieldError } from './greenfield.js';++// Fallback gas price when the chain's own simulate() doesn't return one (the+// exact fallback the official SDK example uses — 5 gwei-equivalent in GNFD's+// smallest denom).+const DEFAULT_GAS_PRICE = '5000000000';+const DEFAULT_GAS_DENOM = 'BNB'; // Greenfield's native gas token (bridged from BSC) — SDK's own DEFAULT_DENOM.++// A vault GLB is a 3D asset, not an arbitrary blob — this caps abuse (someone+// trying to park a huge unrelated file behind the vault) while comfortably+// covering any GLB this platform's own forge pipeline produces.+export const MAX_VAULT_OBJECT_BYTES = 200 * 1024 * 1024;++const DEFAULT_POLL_INTERVAL_MS = 1500;+const DEFAULT_POLL_TIMEOUT_MS = 20_000;+const MAX_POLL_INTERVAL_MS = 8_000;++/** Typed error. `code` ∈ bad_input | too_large | no_sp | tx_failed | upload_failed | unavailable. */+export class GreenfieldWriteError extends Error {+ constructor(message, info = {}) {+ super(message);+ this.name = 'GreenfieldWriteError';+ this.code = info.code || 'unavailable';+ this.txHash = info.txHash;+ if (info.cause) this.cause = info.cause;+ }+}++function sleep(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++const clientCache = new Map();++/** Build (or reuse) an SDK `Client` for a network. Tests inject `opts.client` to bypass this entirely. */+function resolveClient(network, opts) {+ if (opts.client) return opts.client;+ const key = network === 'mainnet' ? 'mainnet' : 'testnet';+ if (!clientCache.has(key)) {+ const { lcd, evmChainId } = greenfieldNetwork(key);+ clientCache.set(key, Client.create(lcd, String(evmChainId)));+ }+ return clientCache.get(key);+}++/** Normalize a hex/0x-hex private key and derive its 0x address (secp256k1 — same curve/derivation as a BSC EOA). */+function accountFromPrivateKey(privateKey) {+ if (typeof privateKey !== 'string' || !privateKey) {+ throw new GreenfieldWriteError('privateKey is required for a Greenfield write', { code: 'bad_input' });+ }+ const pk = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;+ let account;+ try {+ account = privateKeyToAccount(pk);+ } catch (err) {+ throw new GreenfieldWriteError('privateKey is not a valid secp256k1 private key', { code: 'bad_input', cause: err });+ }+ return { privateKey: pk, address: account.address };+}++/** Simulate + broadcast an SDK tx handle (the `{simulate, broadcast}` shape every `client.bucket.*`/`client.object.*` write returns). */+async function broadcastTx(tx, address, privateKey) {+ let sim;+ try {+ sim = await tx.simulate({ denom: DEFAULT_GAS_DENOM });+ } catch (err) {+ throw new GreenfieldWriteError(`Greenfield tx simulation failed: ${err.message}`, { code: 'tx_failed', cause: err });+ }+ let res;+ try {+ res = await tx.broadcast({+ denom: DEFAULT_GAS_DENOM,+ gasLimit: Number(sim?.gasLimit) || undefined,+ gasPrice: sim?.gasPrice || DEFAULT_GAS_PRICE,+ payer: address,+ granter: '',+ privateKey,+ });+ } catch (err) {+ throw new GreenfieldWriteError(`Greenfield tx broadcast failed: ${err.message}`, { code: 'tx_failed', cause: err });+ }+ if (res.code !== 0) {+ throw new GreenfieldWriteError(`Greenfield tx rejected (code ${res.code}): ${res.rawLog || 'no rawLog'}`, {+ code: 'tx_failed',+ txHash: res.transactionHash,+ });+ }+ return res;+}++/** Pick the primary Storage Provider to host a new bucket. */+async function primaryStorageProvider(client) {+ let sp;+ try {+ sp = await client.sp.getInServiceSP();+ } catch (err) {+ throw new GreenfieldWriteError(`could not resolve an in-service Storage Provider: ${err.message}`, { code: 'no_sp', cause: err });+ }+ if (!sp?.operatorAddress) {+ throw new GreenfieldWriteError('no in-service Greenfield Storage Provider available', { code: 'no_sp' });+ }+ return sp;+}++/**+ * Ensure a bucket exists, creating it if absent. Idempotent: a bucket that+ * already exists (from a prior call, or created concurrently between our+ * existence check and the create broadcast) is a no-op success, never an+ * error — the "bucket already exists → reuse, don't fail" state from 09.+ *+ * @param {string} bucketName+ * @param {{ network?: string, privateKey?: string, client?: object, visibility?: 'public'|'private', fetchImpl?: Function }} [opts]+ * @returns {Promise<{ bucket: string, network: string, created: boolean, txHash?: string, primarySp?: string, owner?: string|null }>}+ */+export async function ensureBucket(bucketName, opts = {}) {+ const network = opts.network === 'mainnet' ? 'mainnet' : 'testnet';++ try {+ const info = await headBucket(bucketName, { network, fetchImpl: opts.fetchImpl });+ return { bucket: bucketName, network, created: false, owner: info.owner || info.Owner || null };+ } catch (err) {+ if (!(err instanceof GreenfieldError) || err.code !== 'not_found') throw err;+ }++ const { address, privateKey } = accountFromPrivateKey(opts.privateKey);+ const client = resolveClient(network, opts);+ const sp = await primaryStorageProvider(client);++ const visibility = opts.visibility === 'public' ? VisibilityType.VISIBILITY_TYPE_PUBLIC_READ : VisibilityType.VISIBILITY_TYPE_PRIVATE;++ let tx;+ try {+ tx = await client.bucket.createBucket({+ bucketName,+ creator: address,+ visibility,+ chargedReadQuota: Long.fromString('0'),+ primarySpAddress: sp.operatorAddress,+ paymentAddress: address,+ });+ } catch (err) {+ throw new GreenfieldWriteError(`could not build createBucket tx: ${err.message}`, { code: 'tx_failed', cause: err });+ }++ try {+ const res = await broadcastTx(tx, address, privateKey);+ return { bucket: bucketName, network, created: true, txHash: res.transactionHash, primarySp: sp.operatorAddress };+ } catch (err) {+ // A concurrent creator (another request, or this call racing its own retry)+ // can land the bucket between our headBucket miss and this broadcast —+ // Greenfield rejects that as "already exists". Treat it the same as the+ // pre-check hit: idempotent success, not a failure.+ if (/already exists|repeated/i.test(err.message || '')) {+ const info = await headBucket(bucketName, { network, fetchImpl: opts.fetchImpl }).catch(() => null);+ return { bucket: bucketName, network, created: false, owner: info?.owner || info?.Owner || null };+ }+ throw err;+ }+}++/** True once the read client sees the object as sealed (bytes durably stored, not just CREATED metadata). */+function isSealed(objectInfo) {+ const status = objectInfo?.object_status ?? objectInfo?.objectStatus ?? objectInfo?.ObjectStatus;+ if (status == null) return false;+ return String(status).toUpperCase() === 'OBJECT_STATUS_SEALED' || Number(status) === 1;+}++/** Bounded-backoff poll for an object to become sealed. Never assumes same-block settlement. */+async function pollForSeal(bucket, object, { network, fetchImpl, pollIntervalMs, pollTimeoutMs }) {+ const timeoutMs = pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;+ const baseInterval = pollIntervalMs || DEFAULT_POLL_INTERVAL_MS;+ const deadline = Date.now() + timeoutMs;+ let attempt = 0;+ for (;;) {+ try {+ const info = await getObjectMeta(bucket, object, { network, fetchImpl });+ if (isSealed(info)) return true;+ } catch (err) {+ if (!(err instanceof GreenfieldError) || err.code !== 'not_found') throw err;+ // not_found: the create tx hasn't mirrored into the SP's index yet — keep polling.+ }+ if (Date.now() >= deadline) return false;+ attempt++;+ await sleep(Math.min(baseInterval * 2 ** Math.min(attempt, 3), MAX_POLL_INTERVAL_MS));+ }+}++/**+ * Create an object (bucket must already exist — call `ensureBucket` first)+ * and upload its bytes to the primary Storage Provider. Computes the+ * Reed-Solomon erasure-coding checksums the chain requires, broadcasts the+ * `MsgCreateObject` tx, PUTs the bytes, then polls for the SP to seal the+ * object. Returns `status:'pending'` (not a lie of `'stored'`) if sealing+ * hasn't landed inside the poll budget.+ *+ * @param {string} bucketName+ * @param {string} objectName+ * @param {Uint8Array|Buffer} bytes+ * @param {{ network?: string, privateKey?: string, client?: object, contentType?: string,+ * visibility?: 'public'|'private', maxBytes?: number, pollIntervalMs?: number,+ * pollTimeoutMs?: number, fetchImpl?: Function }} [opts]+ * @returns {Promise<{ bucket: string, object: string, network: string, txHash: string, sp: string, status: 'stored'|'pending' }>}+ */+export async function createObject(bucketName, objectName, bytes, opts = {}) {+ const network = opts.network === 'mainnet' ? 'mainnet' : 'testnet';+ const payload = bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes || []);+ if (payload.length === 0) {+ throw new GreenfieldWriteError('object bytes must not be empty', { code: 'bad_input' });+ }+ const maxBytes = opts.maxBytes || MAX_VAULT_OBJECT_BYTES;+ if (payload.length > maxBytes) {+ throw new GreenfieldWriteError(`object is ${payload.length} bytes, exceeds the ${maxBytes}-byte vault limit`, { code: 'too_large' });+ }++ const { address, privateKey } = accountFromPrivateKey(opts.privateKey);+ const client = resolveClient(network, opts);++ const rs = new ReedSolomon();+ let checksumsB64;+ try {+ checksumsB64 = rs.encode(payload);+ } catch (err) {+ throw new GreenfieldWriteError(`Reed-Solomon checksum encoding failed: ${err.message}`, { code: 'bad_input', cause: err });+ }+ const expectChecksums = checksumsB64.map((c) => bytesFromBase64(c));+ const contentType = opts.contentType || 'application/octet-stream';+ const visibility = opts.visibility === 'public' ? VisibilityType.VISIBILITY_TYPE_PUBLIC_READ : VisibilityType.VISIBILITY_TYPE_PRIVATE;++ let tx;+ try {+ tx = await client.object.createObject({+ bucketName,+ objectName,+ creator: address,+ visibility,+ contentType,+ redundancyType: RedundancyType.REDUNDANCY_EC_TYPE,+ payloadSize: Long.fromInt(payload.length),+ expectChecksums,+ });+ } catch (err) {+ throw new GreenfieldWriteError(`could not build createObject tx: ${err.message}`, { code: 'tx_failed', cause: err });+ }+ const createRes = await broadcastTx(tx, address, privateKey);++ try {+ await client.object.uploadObject(+ {+ bucketName,+ objectName,+ body: { name: objectName, type: contentType, size: payload.length, content: Buffer.from(payload) },+ txnHash: createRes.transactionHash,+ },+ { type: 'ECDSA', privateKey },+ );+ } catch (err) {+ // SP upload failed after the on-chain CREATE landed — never leave a+ // half-object a manifest could reference. Best-effort cancel the pending+ // create so a retry starts clean; the original upload error still wins.+ try {+ const cancelTx = await client.object.cancelCreateObject({ operator: address, bucketName, objectName });+ await broadcastTx(cancelTx, address, privateKey);+ } catch {+ // Best-effort only — surfacing the cancel failure would mask the real+ // (upload) error below, and the CREATED-but-unsealed object safely+ // expires on its own if cancellation didn't land either.+ }+ throw new GreenfieldWriteError(`Storage Provider upload failed: ${err.message}`, { code: 'upload_failed', cause: err, txHash: createRes.transactionHash });+ }++ const sp = await primaryStorageProvider(client);+ const sealed = await pollForSeal(bucketName, objectName, {+ network,+ fetchImpl: opts.fetchImpl,+ pollIntervalMs: opts.pollIntervalMs,+ pollTimeoutMs: opts.pollTimeoutMs,+ });++ return {+ bucket: bucketName,+ object: objectName,+ network,+ txHash: createRes.transactionHash,+ sp: sp.operatorAddress,+ status: sealed ? 'stored' : 'pending',+ };+}diff --git a/api/_lib/bnb/world-moves.js b/api/_lib/bnb/world-moves.jsnew file mode 100644index 000000000..d5be956d1--- /dev/null+++ b/api/_lib/bnb/world-moves.js@@ -0,0 +1,302 @@+/**+ * WorldMoves on-chain move sender for BNB Chain (prompt 15).+ *+ * Combines the two headline BNB capabilities verified in 00-CONTEXT into one+ * felt experience: a plain empty wallet writes its position to chain every+ * ~0.45s (BSC's live Fermi block time) at ZERO gas cost, via MegaFuel's+ * gasless sponsorship (api/_lib/bnb/megafuel.js, prompt 02 — mandatory+ * self-pay fallback baked in there already).+ *+ * Three layers, smallest first:+ * 1. `buildMoveTx`/`buildJoinTx`/`buildLeaveTx`/`buildCheckpointTx` — pure+ * calldata encoders against the deployed WorldMoves.sol (prompt 14).+ * 2. `sendMove`/`sendJoin`/`sendLeave` — route an encoded call through+ * `megafuel.sendGasless`, returning `{ hash, mode }`.+ * 3. `MoveCoalescer` — a pure, network-free scheduler so a position stream+ * updating far faster than BSC confirms blocks (every frame vs. every+ * ~0.45s) produces at most one in-flight send + one queued latest+ * position, never a pending-tx pileup.+ *+ * Isomorphic on purpose (only `viem` + this repo's `chains.js`/`megafuel.js`,+ * no Node-only APIs) so `src/bnb/move-sender.js` can import it straight into+ * the browser bundle for prompt 16's on-chain presence toggle.+ */++import { encodeFunctionData, parseAbi } from 'viem';+import { getPublicClient, BNB_CHAINS, assertBscAddress } from './chains.js';+import { sendGasless } from './megafuel.js';++/** Mirrors contracts/src/WorldMoves.sol's external surface exactly. */+export const WORLD_MOVES_ABI = parseAbi([+ 'function join(uint32 worldId) external',+ 'function leave(uint32 worldId) external',+ 'function move(uint32 worldId, int32 x, int32 y, int32 z, uint16 facing) external',+ 'function checkpoint(uint32 worldId, int32 x, int32 y, int32 z, uint16 facing) external',+ 'event Moved(uint32 indexed worldId, address indexed player, int32 x, int32 y, int32 z, uint16 facing, uint256 blockNumber, uint256 timestamp)',+ 'event Joined(uint32 indexed worldId, address indexed player, uint256 timestamp)',+ 'event Left(uint32 indexed worldId, address indexed player, uint256 timestamp)',+]);++/** Signed 24-bit coordinate bound — mirrors WorldMoves.sol's COORD_MIN/MAX exactly. */+export const COORD_MIN = -8_388_608;+export const COORD_MAX = 8_388_607;++export class WorldMovesError extends Error {+ /** @param {string} message @param {{ code?: string, cause?: unknown }} [info] */+ constructor(message, info = {}) {+ super(message);+ this.name = 'WorldMovesError';+ this.code = info.code || 'world_moves_error';+ if (info.cause) this.cause = info.cause;+ }+}++function normalizeNetwork(network) {+ if (network === 56 || network === '56' || network === 'bsc' || network === 'mainnet' || network === 'bscMainnet') return 'bscMainnet';+ return 'bscTestnet';+}++function assertWorldId(worldId) {+ if (!Number.isInteger(worldId) || worldId < 0 || worldId > 0xffffffff) {+ throw new WorldMovesError(`worldId=${worldId} must be a uint32 (0..4294967295)`, { code: 'bad_world_id' });+ }+}++function assertCoord(name, v) {+ if (!Number.isInteger(v) || v < COORD_MIN || v > COORD_MAX) {+ throw new WorldMovesError(`${name}=${v} is out of WorldMoves bounds [${COORD_MIN}, ${COORD_MAX}]`, { code: 'coord_out_of_bounds' });+ }+}++function assertPos(pos) {+ if (!pos || typeof pos !== 'object') {+ throw new WorldMovesError('pos must be an { x, y, z } object of int32 WorldMoves coordinates', { code: 'bad_pos' });+ }+ assertCoord('x', pos.x);+ assertCoord('y', pos.y);+ assertCoord('z', pos.z);+}++function assertFacing(facing) {+ if (!Number.isInteger(facing) || facing < 0 || facing > 0xffff) {+ throw new WorldMovesError(`facing=${facing} must be a uint16 (0..65535)`, { code: 'bad_facing' });+ }+}++/** Reads a 0x-prefixed 20-byte address out of `process.env[name]`, else null. */+function envAddress(name) {+ const v = typeof process !== 'undefined' && process.env ? process.env[name] : undefined;+ return v && /^0x[0-9a-fA-F]{40}$/.test(v) ? v : null;+}++/**+ * Deployed WorldMoves addresses per chain, resolved from env so a real+ * public-testnet deploy — currently blocked on a funded deployer key, see+ * contracts/DEPLOYMENTS.md's WorldMoves section and PROGRESS.md prompt 14 —+ * can be wired in with zero code change (`WORLD_MOVES_ADDRESS_TESTNET`).+ * Deliberately no hardcoded fallback: the only real broadcast so far is the+ * anvil-fork-local address recorded in DEPLOYMENTS.md, which is NOT a public+ * BscScan-resolvable deployment and must never be mistaken for one.+ */+export const WORLD_MOVES_DEPLOYMENTS = {+ 56: envAddress('WORLD_MOVES_ADDRESS_MAINNET'),+ 97: envAddress('WORLD_MOVES_ADDRESS_TESTNET'),+};++/**+ * Resolve the deployed WorldMoves address for `network`. `opts.address`+ * (tests, the anvil-fork demo, or a caller that already knows the address)+ * always wins over the env-configured deployment.+ * @param {'bscMainnet'|'bscTestnet'|56|97} [network]+ * @param {{ address?: string }} [opts]+ * @returns {`0x${string}`}+ */+export function worldMovesAddress(network, opts = {}) {+ if (opts.address) return assertBscAddress(opts.address);+ const key = normalizeNetwork(network);+ const chainId = BNB_CHAINS[key].id;+ const configured = WORLD_MOVES_DEPLOYMENTS[chainId];+ if (!configured) {+ const envVar = chainId === 56 ? 'WORLD_MOVES_ADDRESS_MAINNET' : 'WORLD_MOVES_ADDRESS_TESTNET';+ throw new WorldMovesError(+ `no WorldMoves contract deployed for chain ${chainId} yet — set ${envVar} once it is (see contracts/DEPLOYMENTS.md), or pass opts.address explicitly`,+ { code: 'no_deployment' },+ );+ }+ return assertBscAddress(configured);+}++function buildTx(functionName, args, opts) {+ const to = worldMovesAddress(opts.network, opts);+ const data = encodeFunctionData({ abi: WORLD_MOVES_ABI, functionName, args });+ return { to, data, value: 0n };+}++/**+ * Encode a `WorldMoves.move(worldId, x, y, z, facing)` call. Pure — no+ * network access, no signing. `pos` coordinates and `facing` are already in+ * contract units (int32 WorldMoves-space, uint16 heading respectively); a+ * caller working in engine units (meters, radians) converts before calling+ * this, see `src/bnb/move-sender.js` for the browser-facing conversion.+ *+ * @param {number} worldId uint32 world/room id+ * @param {{ x:number, y:number, z:number }} pos int32 WorldMoves coordinates+ * @param {number} facing uint16 heading+ * @param {{ network?: 'bscMainnet'|'bscTestnet'|56|97, address?: string }} [opts]+ * @returns {{ to:`0x${string}`, data:`0x${string}`, value:0n }}+ */+export function buildMoveTx(worldId, pos, facing, opts = {}) {+ assertWorldId(worldId);+ assertPos(pos);+ assertFacing(facing);+ return buildTx('move', [worldId, pos.x, pos.y, pos.z, facing], opts);+}++/** Encode a `WorldMoves.join(worldId)` call — announce presence, event-only. */+export function buildJoinTx(worldId, opts = {}) {+ assertWorldId(worldId);+ return buildTx('join', [worldId], opts);+}++/** Encode a `WorldMoves.leave(worldId)` call — announce departure, event-only. */+export function buildLeaveTx(worldId, opts = {}) {+ assertWorldId(worldId);+ return buildTx('leave', [worldId], opts);+}++/** Encode a `WorldMoves.checkpoint(worldId, x, y, z, facing)` call — the one storage-writing variant. */+export function buildCheckpointTx(worldId, pos, facing, opts = {}) {+ assertWorldId(worldId);+ assertPos(pos);+ assertFacing(facing);+ return buildTx('checkpoint', [worldId, pos.x, pos.y, pos.z, facing], opts);+}++/**+ * Send a built tx gaslessly via MegaFuel (self-pay fallback baked into+ * `sendGasless` itself — never a hard failure on the sponsorship path alone).+ * @param {import('viem').Account} account+ * @param {{ to:string, data:string, value?:bigint }} tx+ * @param {'bscMainnet'|'bscTestnet'|56|97} network+ * @param {object} [opts] forwarded to sendGasless (publicClient/walletClient/megafuelRpc — tests)+ * @returns {Promise<{ hash:`0x${string}`, mode:'sponsored'|'self-pay', sponsor?:object|null, reason?:string|null }>}+ */+async function sendTx(account, tx, network, opts = {}) {+ return sendGasless(network, { account, tx }, opts);+}++/**+ * Build + gaslessly send a `move()` call. The primary entry point for both+ * the browser sender (prompt 16) and any server-side/demo caller.+ * @param {{ account: import('viem').Account, worldId:number, pos:{x:number,y:number,z:number}, facing:number, network?: 'bscMainnet'|'bscTestnet'|56|97 }} params+ * @param {object} [opts] forwarded to sendGasless + worldMovesAddress (`opts.address` override, test mocks)+ */+export async function sendMove({ account, worldId, pos, facing, network = 'bscTestnet' }, opts = {}) {+ const tx = buildMoveTx(worldId, pos, facing, { network, address: opts.address });+ return sendTx(account, tx, network, opts);+}++/** Build + gaslessly send a `join()` call. */+export async function sendJoin({ account, worldId, network = 'bscTestnet' }, opts = {}) {+ const tx = buildJoinTx(worldId, { network, address: opts.address });+ return sendTx(account, tx, network, opts);+}++/** Build + gaslessly send a `leave()` call. */+export async function sendLeave({ account, worldId, network = 'bscTestnet' }, opts = {}) {+ const tx = buildLeaveTx(worldId, { network, address: opts.address });+ return sendTx(account, tx, network, opts);+}++/**+ * A pure, network-free "at most one in-flight + one latest-wins pending"+ * scheduler. Feed it positions as fast as a render loop produces them (every+ * frame, ~60/s); it only ever calls `sendFn` once the previous call has+ * settled, and always with the MOST RECENT input, dropping every+ * superseded one in between. That's what keeps a player moving faster than+ * BSC confirms blocks (~0.45s) from spamming hundreds of pending txs — the+ * exact behaviour the prompt's Tests section requires, verified network-free+ * in tests/bnb-world-moves.test.js.+ *+ * `sendFn` failures never throw out of `submit()` — they're reported via+ * `onError` so a flaky/declined send never wedges the coalescer or freezes+ * the caller's game loop (00-CONTEXT: "never freeze the game").+ */+export class MoveCoalescer {+ /**+ * @param {(input:any) => Promise<any>} sendFn+ * @param {{ onSent?:(result:any, input:any)=>void, onError?:(err:Error, input:any)=>void }} [opts]+ */+ constructor(sendFn, opts = {}) {+ if (typeof sendFn !== 'function') {+ throw new WorldMovesError('MoveCoalescer requires a send(input) function', { code: 'bad_send_fn' });+ }+ this._send = sendFn;+ this._onSent = opts.onSent || (() => {});+ this._onError = opts.onError || (() => {});+ this._inFlight = false;+ this._pending = null;+ this._hasPending = false;+ this._sentCount = 0;+ this._coalescedCount = 0;+ this._errorCount = 0;+ this._disposed = false;+ }++ /**+ * Submit the latest position/facing (or any opaque input `sendFn`+ * understands). If a send is already in flight, this replaces whatever was+ * queued behind it — latest-wins — rather than queuing a second tx.+ */+ submit(input) {+ if (this._disposed) return;+ if (this._inFlight) {+ if (this._hasPending) this._coalescedCount++;+ this._pending = input;+ this._hasPending = true;+ return;+ }+ this._launch(input);+ }++ async _launch(input) {+ this._inFlight = true;+ try {+ const result = await this._send(input);+ this._sentCount++;+ this._onSent(result, input);+ } catch (err) {+ this._errorCount++;+ this._onError(err, input);+ } finally {+ this._inFlight = false;+ if (!this._disposed && this._hasPending) {+ const next = this._pending;+ this._pending = null;+ this._hasPending = false;+ this._launch(next);+ }+ }+ }++ /** Snapshot counters — useful for tests and a UI status readout alike. */+ get stats() {+ return {+ sent: this._sentCount,+ coalesced: this._coalescedCount,+ errors: this._errorCount,+ inFlight: this._inFlight,+ hasPending: this._hasPending,+ };+ }++ /** Stop launching further sends. Any send already in flight still settles naturally. */+ dispose() {+ this._disposed = true;+ this._pending = null;+ this._hasPending = false;+ }+}++/** Re-exported so callers don't need a separate `chains.js` import for a public client. */+export { getPublicClient };diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 780d33909..ff3cde21d 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -1007,6 +1007,28 @@ export const env = {return opt('BSC_OPERATOR_KEY');},+ // Greenfield vault platform account (BNB vault track, prompts 09/11). This+ // key creates buckets/objects on Greenfield on behalf of sellers — a+ // managed-storage model where sellers hold only a BSC address for payment+ // (recorded as `sellerAddress` in the vault manifest), never a Greenfield+ // keypair. Same secp256k1 curve/derivation as a BSC EOA, so it falls back to+ // BNB_TESTNET_DEPLOYER_KEY: one funded throwaway key can drive both the BSC+ // and Greenfield legs of this campaign's testnet proofs. UNLIKE+ // BSC_OPERATOR_KEY above, this IS read by a request handler+ // (api/bnb/vault-upload.js) — when unset, that endpoint returns a typed 503+ // rather than silently mocking a signer.+ get GREENFIELD_VAULT_OPERATOR_KEY() {+ return opt('GREENFIELD_VAULT_OPERATOR_KEY') || opt('BNB_TESTNET_DEPLOYER_KEY');+ },+ // Bucket that hosts every vault object, per network. Defaults match the+ // example bucket name in specs/vault-manifest.md.+ get GREENFIELD_VAULT_BUCKET_TESTNET() {+ return opt('GREENFIELD_VAULT_BUCKET_TESTNET', 'three-ws-vault-testnet');+ },+ get GREENFIELD_VAULT_BUCKET_MAINNET() {+ return opt('GREENFIELD_VAULT_BUCKET_MAINNET', 'three-ws-vault-mainnet');+ },+// ── x402 Offer & Receipt extension (USE-17) ─────────────────────────────// DEDICATED signing key for the offer-receipt extension. MUST NOT be any// X402_PAY_TO_* key — those receive funds; this one only signs commitments.diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex ea35c80c1..b7fe8b11f 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -483,6 +483,11 @@ export const limits = {getLimiter('material-studio:restyle', { limit: 40, window: '1 h' }).limit(key),materialStudioUpload: (key) =>getLimiter('material-studio:upload', { limit: 120, window: '1 h' }).limit(key),+ // BNB vault upload (api/bnb/vault-upload.js) — encrypts + writes a real+ // Greenfield tx + SP PUT per call, the heaviest write in the BNB vault+ // track. Tight per-IP ceiling; a seller listing dozens of items per hour is+ // already an outlier, and each call carries real Greenfield gas cost.+ bnbVaultUploadIp: (ip) => getLimiter('bnb:vault:upload:ip', { limit: 20, window: '1 h' }).limit(ip),// Status polling is the highest-frequency call in the generation flow (every// active job polls every few seconds, plus the /forge health pill). It only// guards against pathological poll floods, so it is enforced per instancediff --git a/api/bnb/vault-upload.js b/api/bnb/vault-upload.jsnew file mode 100644index 000000000..48e12ce43--- /dev/null+++ b/api/bnb/vault-upload.js@@ -0,0 +1,315 @@+// POST /api/bnb/vault-upload+// ---------------------------------------------------------------------------+// BNB vault track (prompt 09): a seller lists a 3D model. This endpoint+// encrypts it (08's vault-crypto), ensures a Greenfield bucket, uploads the+// ciphertext object via a Storage Provider (09's greenfield-write), publishes+// the manifest per specs/vault-manifest.md, and returns the refs the vault+// contract (10) and the unlock API (11) will consume. This is where "storage+// you control from a contract" becomes real bytes on Greenfield testnet.+//+// Manifest storage choice: the manifest is a SECOND Greenfield object+// (`<id>.manifest.json`, PUBLIC_READ) sitting next to the ciphertext object+// (`<id>.glb.enc`, PRIVATE) in the same bucket — exactly the layout+// specs/vault-manifest.md illustrates. Chosen over a DB/KV row because (a) the+// manifest is explicitly designed to be publicly readable with no secrets in+// it, so a public object is the natural home, not a new authenticated table;+// (b) it keeps the whole vault self-contained on one backend, matching the+// spec's portability goal; (c) no new DB migration needed. The one genuine+// SECRET this endpoint produces — the raw AES content key — is the opposite:+// it is NEVER put in the manifest or any public object. It is encrypted at+// rest with this platform's existing custodial-secret primitive+// (api/_lib/secret-box.js — the same AES-256-GCM box that already protects+// agent wallet keys and pump.fun creator keys) and persisted in the shared KV+// cache (api/_lib/cache.js — Upstash Redis w/ in-memory fallback, the same+// durability posture forge-cache/pipeline-store already use), keyed by the+// ciphertext object ref, so prompt 11's unlock API can look it up, verify the+// buyer paid on-chain, and wrap a fresh copy to that buyer's public key —+// never re-serving the same wrapped bundle to two buyers.+//+// Body (application/json):+// {+// glbUrl?: string, // fetch bytes from a public https URL (this+// // platform's own /api/forge* outputs, or any+// // public GLB) — SSRF-guarded (api/_lib/ssrf.js)+// glbBase64?: string, // OR raw GLB bytes, base64-encoded. Exactly one+// // of glbUrl / glbBase64 is required.+// sellerAddress: string, // 0x BSC address that receives sale proceeds+// priceAtomic?: string, // USDC atomics; default priceFor('bnb-vault-upload', '100000') = $0.10+// network?: 'testnet'|'mainnet', // default 'testnet'+// contractAddress?: string, // override the recorded vault contract address+// }+//+// Response 200:+// { manifestRef: {bucket, object}, glbObjectRef: {bucket, object}, sha256,+// status: 'stored'|'pending', manifest, contractDeployed: boolean }++import { randomBytes, createHash } from 'node:crypto';++import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { assertPublicHttpsUrl } from '../_lib/ssrf.js';+import { assertBscAddress, BNB_CHAINS } from '../_lib/bnb/chains.js';+import { encryptGlb, VAULT_CRYPTO_PARAMS } from '../_lib/bnb/vault-crypto.js';+import { ensureBucket, createObject, GreenfieldWriteError, MAX_VAULT_OBJECT_BYTES } from '../_lib/bnb/greenfield-write.js';+import { priceFor } from '../_lib/x402-prices.js';+import { encryptSecret } from '../_lib/secret-box.js';+import { cacheSet } from '../_lib/cache.js';++const ROUTE = '/api/bnb/vault-upload';+const MAX_INPUT_GLB_BYTES = 64 * 1024 * 1024; // a vault GLB is a 3D asset, not an arbitrary blob+// JSON body cap: base64 inflates raw bytes ~4/3; the +8KB covers the other fields.+const MAX_JSON_BODY_BYTES = Math.ceil((MAX_INPUT_GLB_BYTES * 4) / 3) + 8192;+const MANIFEST_VERSION = 1;+// The vault key record has no natural expiry — it must outlive the listing+// until the seller delists or every content-key holder has bought. 180 days+// comfortably covers a real listing lifetime; prompt 11/vault delisting can+// refresh it on access if a longer horizon is ever needed.+const VAULT_KEY_TTL_S = 180 * 24 * 3600;++class VaultUploadError extends Error {+ constructor(message, { status = 400, code = 'bad_request', extra } = {}) {+ super(message);+ this.name = 'VaultUploadError';+ this.status = status;+ this.code = code;+ this.extra = extra;+ }+}++// glTF binary magic — first 4 bytes are ASCII "glTF". Mirrors+// api/_lib/material-studio-store.js's isGlbMagic / api/_lib/pipeline-stage.js's+// so a bad input fails the same way everywhere in the 3D pipeline.+function isGlbMagic(bytes) {+ return bytes?.length >= 12 && bytes[0] === 0x67 && bytes[1] === 0x6c && bytes[2] === 0x54 && bytes[3] === 0x46;+}++function assertGlbBytes(buf) {+ if (!buf.length) throw new VaultUploadError('GLB is empty', { status: 400, code: 'empty_glb' });+ if (buf.length > MAX_INPUT_GLB_BYTES) {+ throw new VaultUploadError(`GLB is ${buf.length} bytes; max is ${MAX_INPUT_GLB_BYTES}`, { status: 413, code: 'glb_too_large' });+ }+ if (!isGlbMagic(buf)) {+ throw new VaultUploadError('input is not a binary glTF (.glb) — its bytes lack the "glTF" magic header', {+ status: 415,+ code: 'unsupported_media_type',+ });+ }+}++async function fetchGlbBytes(rawUrl) {+ let safeUrl;+ try {+ safeUrl = await assertPublicHttpsUrl(rawUrl);+ } catch (err) {+ throw new VaultUploadError(`glbUrl rejected: ${err.message}`, { status: 400, code: 'invalid_url' });+ }+ let resp;+ try {+ resp = await fetch(safeUrl, { signal: AbortSignal.timeout(30_000) });+ } catch (err) {+ throw new VaultUploadError(`could not fetch glbUrl: ${err.message}`, { status: 502, code: 'fetch_failed' });+ }+ if (!resp.ok) {+ throw new VaultUploadError(`glbUrl returned ${resp.status}`, { status: resp.status === 404 ? 404 : 502, code: 'fetch_failed' });+ }+ const buf = Buffer.from(await resp.arrayBuffer());+ assertGlbBytes(buf);+ return buf;+}++function decodeGlbBase64(b64) {+ let buf;+ try {+ buf = Buffer.from(b64, 'base64');+ } catch (err) {+ throw new VaultUploadError('glbBase64 is not valid base64', { status: 400, code: 'bad_base64', extra: { cause: err.message } });+ }+ assertGlbBytes(buf);+ return buf;+}++function normalizeNetwork(raw) {+ 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;+}++function vaultBucketFor(network) {+ return network === 'mainnet' ? env.GREENFIELD_VAULT_BUCKET_MAINNET : env.GREENFIELD_VAULT_BUCKET_TESTNET;+}++/**+ * The GreenfieldVault.sol contract (prompt 10) is code-complete but its+ * public-testnet deploy is blocked on a funded deployer key (same root cause+ * documented for prompts 07/09/10/13/14/18 in PROGRESS.md) — there is no real+ * address to record yet. Mirrors the honest "not deployed yet" pattern+ * api/_lib/bnb/world-moves.js established for WorldMoves: return the+ * spec-illustrated placeholder (specs/vault-manifest.md's own example uses+ * this exact address) rather than inventing one, and tell the caller plainly+ * via `contractDeployed:false` in the response.+ */+function vaultContractAddress(network, override) {+ if (override) return { address: assertBscAddress(override), deployed: true };+ const envVar = network === 'mainnet' ? 'GREENFIELD_VAULT_ADDRESS_MAINNET' : 'GREENFIELD_VAULT_ADDRESS_TESTNET';+ const configured = process.env[envVar];+ if (configured) return { address: assertBscAddress(configured), deployed: true };+ return { address: '0x0000000000000000000000000000000000dEaD', deployed: false };+}++function vaultKeyCacheKey(bucket, object) {+ return `bnb:vault:key:${bucket}:${object}`;+}++const mapGreenfieldWriteStatus = {+ bad_input: 400,+ too_large: 413,+ no_sp: 502,+ tx_failed: 502,+ upload_failed: 502,+ unavailable: 503,+};++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.bnbVaultUploadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'too many vault uploads');++ if (!env.GREENFIELD_VAULT_OPERATOR_KEY) {+ return error(res, 503, 'vault_not_configured', 'GREENFIELD_VAULT_OPERATOR_KEY is not set — the vault storage account is not provisioned yet');+ }++ let body;+ try {+ body = await readJson(req, MAX_JSON_BODY_BYTES);+ } catch (e) {+ return error(res, e.status || 400, 'bad_body', e.message || 'failed to read JSON body');+ }++ try {+ const network = normalizeNetwork(body?.network);+ if (network === null) {+ return error(res, 400, 'bad_request', `unknown network "${body?.network}" — use "testnet" or "mainnet"`);+ }++ let sellerAddress;+ try {+ sellerAddress = assertBscAddress(body?.sellerAddress);+ } catch (err) {+ return error(res, 400, 'bad_request', `sellerAddress: ${err.message}`);+ }++ const priceAtomic = body?.priceAtomic != null ? String(body.priceAtomic) : priceFor('bnb-vault-upload', '100000');+ if (!/^\d+$/.test(priceAtomic)) {+ return error(res, 400, 'bad_request', 'priceAtomic must be a non-negative integer string (USDC atomics)');+ }++ const hasUrl = typeof body?.glbUrl === 'string' && body.glbUrl.trim();+ const hasBase64 = typeof body?.glbBase64 === 'string' && body.glbBase64.trim();+ if (Boolean(hasUrl) === Boolean(hasBase64)) {+ return error(res, 400, 'bad_request', 'exactly one of glbUrl or glbBase64 is required');+ }++ let glbBytes;+ try {+ glbBytes = hasUrl ? await fetchGlbBytes(body.glbUrl.trim()) : decodeGlbBase64(body.glbBase64.trim());+ } catch (err) {+ if (err instanceof VaultUploadError) return error(res, err.status, err.code, err.message, err.extra);+ throw err;+ }++ // ── 08: encrypt-at-rest. Content key never leaves this function in the clear. ──+ const { ciphertext, contentKey, iv, authTag, sha256OfPlaintext } = encryptGlb(glbBytes);++ const bucket = vaultBucketFor(network);+ const id = randomBytes(8).toString('hex');+ const objectBase = `vaults/${sellerAddress.toLowerCase()}/${id}`;+ const glbObjectName = `${objectBase}.glb.enc`;+ const manifestObjectName = `${objectBase}.manifest.json`;+ const writeOpts = { network, privateKey: env.GREENFIELD_VAULT_OPERATOR_KEY };++ // ── 09: ensure the bucket, then write the ciphertext object. ──+ await ensureBucket(bucket, writeOpts);+ const glbWrite = await createObject(bucket, glbObjectName, ciphertext, {+ ...writeOpts,+ contentType: 'application/octet-stream',+ visibility: 'private',+ maxBytes: MAX_VAULT_OBJECT_BYTES,+ });++ // ── Persist the secret content key server-side, NEVER in the manifest. ──+ // Encrypted at rest with the platform's existing custodial-secret box+ // (the same primitive protecting agent wallet keys), keyed by the+ // ciphertext object ref so prompt 11 can look it up post-payment and wrap+ // a fresh copy to the verified buyer's public key.+ const contentKeyCiphertext = await encryptSecret(contentKey.toString('base64'));+ await cacheSet(+ vaultKeyCacheKey(bucket, glbObjectName),+ { contentKeyCiphertext, sellerAddress, createdAt: new Date().toISOString() },+ VAULT_KEY_TTL_S,+ );++ const { address: contractAddress, deployed: contractDeployed } = vaultContractAddress(network, body?.contractAddress);+ const chainId = BNB_CHAINS[network === 'mainnet' ? 'bscMainnet' : 'bscTestnet'].id;++ const manifest = {+ version: MANIFEST_VERSION,+ glbObjectRef: { bucket, object: glbObjectName },+ encryption: {+ alg: VAULT_CRYPTO_PARAMS.alg,+ iv: iv.toString('hex'),+ authTag: authTag.toString('hex'),+ },+ sha256: sha256OfPlaintext,+ priceAtomic,+ sellerAddress,+ contract: { address: contractAddress, chainId },+ createdAt: new Date().toISOString(),+ };++ // ── Publish the manifest as a public, sibling Greenfield object. ──+ const manifestBytes = Buffer.from(JSON.stringify(manifest, null, 2));+ let manifestWrite;+ try {+ manifestWrite = await createObject(bucket, manifestObjectName, manifestBytes, {+ ...writeOpts,+ contentType: 'application/json',+ visibility: 'public',+ });+ } catch (err) {+ // The ciphertext IS safely stored (private, unreferenced by any public+ // manifest yet) — surface the ref so a caller can retry the manifest+ // write instead of re-uploading + re-encrypting the whole GLB.+ const extra = { glbObjectRef: { bucket, object: glbObjectName }, sha256: sha256OfPlaintext };+ if (err instanceof GreenfieldWriteError) {+ return error(res, mapGreenfieldWriteStatus[err.code] || 502, err.code, `manifest publish failed: ${err.message}`, extra);+ }+ throw err;+ }++ const status = glbWrite.status === 'stored' && manifestWrite.status === 'stored' ? 'stored' : 'pending';++ return json(+ res,+ 200,+ {+ manifestRef: { bucket, object: manifestObjectName },+ glbObjectRef: { bucket, object: glbObjectName },+ sha256: sha256OfPlaintext,+ status,+ manifest,+ contractDeployed,+ txHashes: { glb: glbWrite.txHash, manifest: manifestWrite.txHash },+ pollHint: status === 'pending' ? 'object create/upload succeeded; Greenfield is still sealing — GET the manifestRef/glbObjectRef shortly' : undefined,+ },+ { 'cache-control': 'no-store' },+ );+ } catch (err) {+ if (err instanceof VaultUploadError) return error(res, err.status, err.code, err.message, err.extra);+ if (err instanceof GreenfieldWriteError) return error(res, mapGreenfieldWriteStatus[err.code] || 502, err.code, err.message);+ throw err;+ }+});diff --git a/api/bnb/world-config.js b/api/bnb/world-config.jsnew file mode 100644index 000000000..9d541c2e2--- /dev/null+++ b/api/bnb/world-config.js@@ -0,0 +1,71 @@+// GET /api/bnb/world-config?network=testnet|mainnet+// ---------------------------------------------------------------------------+// Public (non-secret) config for prompt 16's on-chain presence mode+// (src/agora/onchain-presence.js). A deployed contract address is not a+// secret — only the deployer key is — so this is a plain cached GET, no auth,+// mirroring api/bnb/babt-check.js's shape. Exists so the browser never needs+// its own copy of WORLD_MOVES_ADDRESS_TESTNET/MAINNET (which live in the+// SERVER's env, unreachable from client code) and so flipping the env var the+// moment a real public deploy lands (contracts/DEPLOYMENTS.md) takes effect+// for every open browser tab without a frontend rebuild.+//+// Response: { network, chainId, address, deployed, explorer, rpcs, worldId }+// `address: null, deployed: false` is a normal, honest state (00-CONTEXT:+// never fabricate a live-looking address) — the client renders "not deployed+// yet" and never fires a wallet prompt for a contract that doesn't exist.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { BNB_CHAINS } from '../_lib/bnb/chains.js';+import { worldMovesAddress, WorldMovesError } from '../_lib/bnb/world-moves.js';++// Single logical "world" for the Agora Commons on-chain presence layer today+// (see src/agora/onchain-presence.js) — multi-world routing is out of scope+// for this campaign; bumping this would fragment presence for every existing+// player, so treat it as a stable public constant, not a per-request input.+const COMMONS_WORLD_ID = 1;++function normalizeNetworkParam(raw) {+ const v = String(raw || '').trim().toLowerCase();+ if (v === 'testnet' || v === '97' || v === 'bsctestnet') return 'bscTestnet';+ if (v === '' || v === 'mainnet' || v === '56' || v === 'bscmainnet') return 'bscMainnet';+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const network = normalizeNetworkParam(params.get('network'));+ if (network === null) {+ return error(res, 400, 'bad_request', `unknown network "${params.get('network')}" — use "mainnet" or "testnet"`);+ }++ const meta = BNB_CHAINS[network];+ let address = null;+ try {+ address = worldMovesAddress(network);+ } catch (err) {+ if (!(err instanceof WorldMovesError)) throw err;+ // no_deployment is the expected, honest state until a public deploy lands.+ }++ return json(+ res,+ 200,+ {+ network,+ chainId: meta.id,+ address,+ deployed: !!address,+ explorer: meta.explorer,+ rpcs: meta.rpcs,+ worldId: COMMONS_WORLD_ID,+ },+ { 'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300' },+ );+});diff --git a/api/coin/liquidations.js b/api/coin/liquidations.jsnew file mode 100644index 000000000..82a0e930f--- /dev/null+++ b/api/coin/liquidations.js@@ -0,0 +1,61 @@+// GET /api/coin/liquidations+// ---------------------------------------------------------------------------+// Proxies the real-time liquidations snapshot from the standalone+// `services/liquidation-collector` service (see its README for why this can't+// be a Vercel function — it holds long-lived exchange WebSocket connections).+// Powers the "liquidations pulse" strip on /coins.+//+// No fabricated fallback data, ever: if `LIQUIDATION_COLLECTOR_URL` is unset+// or the upstream is unreachable/slow, this responds 503 { error:+// 'collector_offline' } and the UI renders its designed offline state — never+// synthetic numbers.++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const TIMEOUT_MS = 5000;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const collectorUrl = process.env.LIQUIDATION_COLLECTOR_URL;+ if (!collectorUrl) {+ return json(+ res,+ 503,+ { error: 'collector_offline', error_description: 'liquidation collector is not configured on this deployment' },+ { 'cache-control': 'no-store' },+ );+ }++ try {+ const upstream = new URL('/liquidations', collectorUrl).toString();+ const resp = await fetch(upstream, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ if (!resp.ok) {+ return json(+ res,+ 503,+ { error: 'collector_offline', error_description: `collector responded ${resp.status}` },+ { 'cache-control': 'no-store' },+ );+ }+ const payload = await resp.json();+ return json(res, 200, payload, {+ 'cache-control': 'public, s-maxage=15, stale-while-revalidate=60',+ });+ } catch {+ return json(+ res,+ 503,+ { error: 'collector_offline', error_description: 'liquidation collector is unreachable right now' },+ { 'cache-control': 'no-store' },+ );+ }+});diff --git a/data/changelog.json b/data/changelog.jsonindex c5a06d5f6..00944358a 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,24 @@{"$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": "Live liquidations pulse on the markets page — real-time long/short pain across Binance, Bybit, and OKX",+ "summary": "A new standalone collector subscribes to the public futures liquidation WebSocket streams of Binance, Bybit, and OKX, classifies each liquidation by size, and keeps a rolling 4-hour window. /coins now shows a live strip under the global stats bar: a LONG PAIN / SHORT SQUEEZE / BALANCED badge, 1h long-vs-short liquidated USD bars, and the three largest recent liquidations — each linking to its coin page. It polls every 30 seconds, pauses when the tab isn't visible, and quietly shows an offline line (never fake numbers) if the collector is unreachable.",+ "tags": [+ "feature"+ ],+ "link": "/coins"+ },+ {+ "date": "2026-07-08",+ "title": "Gasless on-chain move sender for BNB Chain worlds — built, no browser toggle yet",+ "summary": "Added the library that will let a plain empty wallet walk around a three.ws world writing its position to BNB Chain every block with zero gas: builds WorldMoves.sol move/join/leave/checkpoint calls, routes them through MegaFuel's gas sponsorship with an automatic self-paid fallback, and coalesces a fast-moving player's updates to at most one in-flight transaction so the chain never gets spammed. Proven with 20 real, sequentially-mined transactions against a live-forked BSC Testnet. No player-facing toggle yet — that lands with the on-chain presence mode.",+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-07-08","title": "scene-mcp can now build a whole 3D world in one call — no browser required",diff --git a/data/pages.json b/data/pages.jsonindex 1dab84639..e9b94085f 100644--- a/data/pages.json+++ b/data/pages.json@@ -816,6 +816,14 @@"changefreq": "daily","added": "2026-06-12"},+ {+ "path": "/minted",+ "title": "Minted 3D Assets",+ "description": "Live public gallery of every generated 3D avatar minted as a Metaplex Core NFT through three.ws — interactive viewer, baked provenance, and enforced creator royalties on every card.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-07-08"+ },{"path": "/theater","title": "Live Trading Theater",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex f5d9b40b3..2bfe284dc 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -2334,6 +2334,61 @@ live). Cached 15 s — no API key required.---+### Liquidations++```+GET /api/coin/liquidations+```++Powers the "liquidations pulse" strip on `/coins`. Proxies the standalone+[`services/liquidation-collector`](../services/liquidation-collector) service+— a long-running process that subscribes to the **public** futures+liquidation WebSocket streams of Binance, Bybit, and OKX and keeps a rolling+4-hour in-memory window. This endpoint has no fallback data: when+`LIQUIDATION_COLLECTOR_URL` is unset or the collector is unreachable, it+returns `503 { "error": "collector_offline" }` rather than fabricated numbers.++**Response** (200)++```json+{+ "liquidations": [+ {+ "exchange": "Binance",+ "price": 0,+ "qty": 0,+ "severity": "SMALL|MEDIUM|LARGE|MEGA",+ "side": "LONG|SHORT",+ "symbol": "BTC",+ "time": 0,+ "value": 0+ }+ ],+ "summary": {+ "dominantSide": "LONG PAIN|SHORT SQUEEZE|BALANCED",+ "largeCount": 0,+ "longCount": 0,+ "longValue": 0,+ "megaCount": 0,+ "shortCount": 0,+ "shortValue": 0,+ "totalCount": 0,+ "totalValue": 0+ },+ "symbolStats": [{ "count": 0, "longValue": 0, "shortValue": 0, "symbol": "BTC" }],+ "timestamp": "2026-07-08T12:00:00.000Z"+}+```++`liquidations` is the 50 most recent events (newest first) across 18 tracked+majors. `side` is the side that got liquidated — a forced-sell of a long is+`LONG`, a forced-buy-back of a short is `SHORT`. `summary.dominantSide` is+`LONG PAIN` when long liquidations exceed short by 1.5x, `SHORT SQUEEZE` for+the inverse, `BALANCED` otherwise. Cached 15 s (`s-maxage=15,+stale-while-revalidate=60`). No API key required.++---+### Market tools (categories, exchanges, derivatives, rates, DeFi)Read-only, key-free proxies powering the `/categories`, `/exchanges`,diff --git a/pages/coins.html b/pages/coins.htmlindex 0cfe1316a..9149548ba 100644--- a/pages/coins.html+++ b/pages/coins.html@@ -112,6 +112,11 @@<!-- Global stats bar. Hydrated by src/coins-index.js. --><section id="cv-stats" class="cv-section" aria-label="Market statistics"></section>+ <!-- Liquidations pulse: live long/short liquidation pain across Binance,+ Bybit, and OKX futures. Hydrated by src/coins-index.js; renders its+ own offline state when the collector isn't reachable. -->+ <section id="cv-liq" class="cv-liq" aria-label="Liquidations"></section>+<!-- Toolbar: search type-ahead. --><div class="cv-toolbar"><h2 class="cv-h2" style="margin: 0">Top Cryptocurrencies</h2>diff --git a/pages/minted.html b/pages/minted.htmlnew file mode 100644index 000000000..2649df4e4--- /dev/null+++ b/pages/minted.html@@ -0,0 +1,128 @@+<!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>Minted 3D Assets · three.ws</title>+ <meta+ name="description"+ content="Every generated 3D avatar minted as a Metaplex Core NFT through three.ws — a live, public gallery with an interactive viewer, baked provenance, and enforced creator royalties on every card."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/minted" />+ <meta property="og:title" content="Minted 3D Assets · three.ws" />+ <meta+ property="og:description"+ content="Every generated 3D avatar minted as a Metaplex Core NFT through three.ws — live viewer, baked provenance, and enforced creator royalties on every card."+ />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Minted+3D+Assets&d=Live+public+gallery+of+every+generated+3D+avatar+minted+as+a+Metaplex+Core+NFT+through+three.ws+%E2%80%94+interactive+viewer%2C+baked+provenance%2C+and+enforced+creator+roy&p=%2Fminted" />+ <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="Minted 3D Assets · three.ws" />+ <meta+ name="twitter:description"+ content="Every generated 3D avatar minted as a Metaplex Core NFT through three.ws — live viewer, baked provenance, enforced creator royalties."+ />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Minted+3D+Assets&d=Live+public+gallery+of+every+generated+3D+avatar+minted+as+a+Metaplex+Core+NFT+through+three.ws+%E2%80%94+interactive+viewer%2C+baked+provenance%2C+and+enforced+creator+roy&p=%2Fminted" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/minted.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ <link rel="canonical" href="https://three.ws/minted" />+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Minted 3D Assets","description":"Every generated 3D avatar minted as a Metaplex Core NFT through three.ws — live viewer, baked provenance, and enforced creator royalties.","url":"https://three.ws/minted","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ <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="Minted 3D Assets — three.ws" />+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js" integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw" crossorigin="anonymous"></script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="mn-shell">+ <section class="mn-hero">+ <p class="mn-kicker"><span class="mn-live-dot" aria-hidden="true"></span> Live from Solana</p>+ <h1 class="mn-title">Minted <em>3D Assets</em></h1>+ <p class="mn-sub">+ Every generated or owned avatar a creator chose to mint as a <strong>Metaplex Core NFT</strong> —+ real on-chain property whose media is a live, interactive 3D viewer, not a flat picture. Each+ card carries baked, independently-verifiable <strong>provenance</strong> and an enforced,+ capped creator <strong>royalty</strong> that pays out the moment a remix mints.+ </p>+ <div class="mn-net" role="tablist" aria-label="Network">+ <button type="button" class="mn-net-btn active" data-network="mainnet" role="tab" aria-selected="true">Mainnet</button>+ <button type="button" class="mn-net-btn" data-network="devnet" role="tab" aria-selected="false">Devnet</button>+ </div>+ <div class="mn-hero-ctas">+ <a class="mn-btn mn-btn-primary" href="/forge">Forge a 3D model</a>+ <a class="mn-btn" href="/agent-identities">Mint your own</a>+ <a class="mn-btn" href="/gallery">Browse the avatar gallery</a>+ </div>+ </section>++ <dl class="mn-counters" id="mn-counters">+ <div class="mn-counter mn-counter--lead">+ <dt>Minted</dt>+ <dd id="mn-c-total">—</dd>+ <span class="mn-counter-sub">on this page</span>+ </div>+ <div class="mn-counter">+ <dt>Avg. royalty</dt>+ <dd id="mn-c-royalty">—</dd>+ <span class="mn-counter-sub">enforced on-chain</span>+ </div>+ <div class="mn-counter">+ <dt>Remixes</dt>+ <dd id="mn-c-remix">—</dd>+ <span class="mn-counter-sub">with royalty paid</span>+ </div>+ <div class="mn-counter">+ <dt>Network</dt>+ <dd id="mn-c-network">mainnet</dd>+ <span class="mn-counter-sub">selected feed</span>+ </div>+ </dl>++ <section class="mn-feed-head">+ <h2 class="mn-section-h">Live gallery</h2>+ <span id="mn-count" class="mn-count" aria-live="polite"></span>+ </section>++ <section id="mn-feed" class="mn-grid" aria-label="Minted 3D assets" aria-busy="true"></section>++ <div id="mn-footer-state" class="mn-footer-state"></div>++ <section class="mn-about">+ <h2 class="mn-section-h">How minting works here</h2>+ <p class="mn-about-body">+ Minting is always opt-in — the free text→3D lane never auto-mints. A creator picks a generated+ or owned GLB, an optional royalty rate (capped at 10%), and mints it on devnet (default, free+ testing) or mainnet (a real, disclosed on-chain write). Every mint bakes provenance — creator,+ prompt, generation model, and parent lineage — into both the NFT metadata and a second,+ independently-signed record on the platform's append-only provenance ledger. Naming another+ creator's mint as a <code>parent_mint</code> (a remix) routes their royalty share out of your+ mint fee as a real on-chain USDC transfer, the moment your mint confirms.+ Read more in <a href="/docs/mcp#mint_3d_asset">the MCP tool docs</a> or query any mint back with+ <code>get_3d_asset_onchain</code>.+ </p>+ </section>+ </main>++ <script type="module" src="/src/minted.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/tour-builder.html b/pages/tour-builder.htmlindex 3c0ff55f7..57986b443 100644--- a/pages/tour-builder.html+++ b/pages/tour-builder.html@@ -108,6 +108,19 @@.empty-stops { text-align: center; padding: 22px 12px; color: var(--faint); border: 1px dashed var(--line); border-radius: var(--r); font-size: 13.5px; line-height: 1.6; }+ /* templates */+ .tpl-open-btn { width: 100%; padding: 11px; border-radius: var(--r); border: 1.5px solid var(--accent-2); background: rgba(52,211,153,.1); color: var(--accent); font-weight: 700; transition: .15s; }+ .tpl-open-btn:hover { background: rgba(52,211,153,.18); border-color: var(--accent); }+ .template-note { margin-top: 9px; padding: 10px 12px; border-radius: var(--r-sm); border: 1px solid rgba(251,191,36,.35); background: rgba(251,191,36,.08); color: #f2d097; font-size: 12px; line-height: 1.55; }+ .tpl-card { display: flex; flex-direction: column; gap: 8px; padding: 16px 18px; border: 1px solid var(--line); border-radius: var(--r); background: var(--edge-2); margin-bottom: 12px; transition: .15s; }+ .tpl-card:hover { border-color: var(--line-2); background: var(--edge-3); }+ .tpl-card:last-child { margin-bottom: 0; }+ .tpl-card h3 { font-size: 15px; }+ .tpl-card p { color: var(--muted); font-size: 13px; line-height: 1.5; }+ .tpl-card button { align-self: flex-start; padding: 8px 16px; border-radius: var(--r-sm); border: 1px solid var(--accent-2); background: rgba(52,211,153,.12); color: var(--accent); font-weight: 600; font-size: 13px; transition: .15s; }+ .tpl-card button:hover { background: rgba(52,211,153,.22); }+ .tpl-card.sel { border-color: var(--accent); background: rgba(52,211,153,.08); }+/* drawer footer actions */.dr-foot { padding: 13px 18px; border-top: 1px solid var(--line); display: flex; gap: 9px; background: var(--edge); }.btn { flex: 1; padding: 11px; border-radius: var(--r-sm); font-weight: 700; border: 1px solid var(--line-2); background: var(--edge-3); transition: .15s; display: inline-flex; align-items: center; justify-content: center; gap: 7px; }@@ -135,8 +148,8 @@#exit-preview:hover { border-color: var(--danger); color: var(--danger); }/* ─────────────────────────── export modal ─────────────────────────── */- #modal-scrim { position: fixed; inset: 0; z-index: 2147483610; background: rgba(4,6,10,.66); backdrop-filter: blur(3px); display: none; align-items: center; justify-content: center; padding: 24px; }- #modal-scrim.open { display: flex; }+ #modal-scrim, #templates-scrim { position: fixed; inset: 0; z-index: 2147483610; background: rgba(4,6,10,.66); backdrop-filter: blur(3px); display: none; align-items: center; justify-content: center; padding: 24px; }+ #modal-scrim.open, #templates-scrim.open { display: flex; }.modal { width: min(720px, 100%); max-height: 88vh; overflow-y: auto; background: var(--edge); border: 1px solid var(--line-2); border-radius: 16px; box-shadow: 0 30px 80px rgba(0,0,0,.6); }.modal-head { padding: 20px 24px 16px; border-bottom: 1px solid var(--line); display: flex; align-items: flex-start; gap: 12px; }.modal-head h2 { font-size: 20px; margin-bottom: 3px; }@@ -232,6 +245,12 @@</div><div class="dr-body">+ <div class="sec">+ <label class="h">Start from a template</label>+ <button class="tpl-open-btn" id="templates-open">🧩 Browse templates</button>+ <p id="template-note" class="template-note" hidden></p>+ </div>+<div class="sec"><label class="h" for="tour-title">Tour name</label><input type="text" id="tour-title" placeholder="Store tour" value="Store tour" />@@ -340,25 +359,39 @@</div></main>+<!-- ══════════════════ TEMPLATES MODAL ══════════════════ -->+<div id="templates-scrim">+ <div class="modal" role="dialog" aria-modal="true" aria-labelledby="templates-title">+ <div class="modal-head">+ <div style="flex:1">+ <h2 id="templates-title">Start from a template</h2>+ <p>Load a ready-made tour, then edit it exactly like your own.</p>+ </div>+ <button class="icon-btn" id="templates-close" aria-label="Close">✕</button>+ </div>+ <div class="modal-body" id="templates-list"></div>+ </div>+</div>+<!-- ══════════════════ EXPORT MODAL ══════════════════ --><div id="modal-scrim"><div class="modal" role="dialog" aria-modal="true" aria-labelledby="modal-title"><div class="modal-head"><div style="flex:1"><h2 id="modal-title">Ship it to Shopify</h2>- <p>Three copy-pastes and your store has a walking 3D guide. Everything below is generated from the tour you just built.</p>+ <p id="modal-sub">Three copy-pastes and your store has a walking 3D guide. Everything below is generated from the tour you just built.</p></div><button class="icon-btn" id="modal-close" aria-label="Close">✕</button></div><div class="modal-body"><div class="step">- <h3><span class="n">1</span> Upload your tour script</h3>- <p>In Shopify admin → <b>Content → Files</b>, upload this file, then copy the URL Shopify gives it.</p>+ <h3><span class="n">1</span> <span id="modal-step1-title">Upload your tour script</span></h3>+ <p id="modal-step1-desc">In Shopify admin → <b>Content → Files</b>, upload this file, then copy the URL Shopify gives it.</p><div class="dl-row"><button class="btn" id="dl-json" style="flex:none; padding:9px 16px;">⬇ Download curriculum.json</button></div></div><div class="step">- <h3><span class="n">2</span> Add the guide to your theme</h3>- <p>Online Store → Themes → <b>⋯ → Edit code</b> → <b>layout/theme.liquid</b>. Paste this right before <code></body></code>, and swap the URL for the one from step 1.</p>+ <h3><span class="n">2</span> <span id="modal-step2-title">Add the guide to your theme</span></h3>+ <p id="modal-step2-desc">Online Store → Themes → <b>⋯ → Edit code</b> → <b>layout/theme.liquid</b>. Paste this right before <code></body></code>, and swap the URL for the one from step 1.</p><div class="code" id="snippet-embed"><button class="copybtn" data-copy="snippet-embed">Copy</button></div></div><div class="step">@@ -368,7 +401,7 @@</div></div><div class="modal-foot">- <a class="btn" href="/tutorials/shopify-store-guide" style="flex:none; padding:10px 16px; text-decoration:none;">Full written guide →</a>+ <a class="btn" href="/tutorials/shopify-store-guide" id="modal-guide-link" style="flex:none; padding:10px 16px; text-decoration:none;">Full written guide →</a><button class="btn primary" id="modal-done" style="flex:none; padding:10px 20px;">Done</button></div></div>diff --git a/prompts/bnb-chain/PROGRESS.md b/prompts/bnb-chain/PROGRESS.mdindex e595f4ac5..34b8a317e 100644--- a/prompts/bnb-chain/PROGRESS.md+++ b/prompts/bnb-chain/PROGRESS.md@@ -964,3 +964,128 @@ automated snapshot process before this session issued its own commit — verifievia `git show 3599057e8 -- STRUCTURE.md`).**Status: DONE (docs + spec re-verified accurate, STRUCTURE.md gap closed, tests green).**++---++## 2026-07-08 — Prompt 15 (gasless-move-sender): real anvil-fork self-pay proof added — SHIPPED++**Starting state:** this session found `api/_lib/bnb/world-moves.js`, `src/bnb/move-sender.js`,+`tests/bnb-world-moves.test.js`, and `tests/bnb-move-sender.test.js` already built UNTRACKED in+this shared worktree by a concurrent agent (per CLAUDE.md's "concurrent agents share this+worktree" trap — several other untracked files from unrelated prompts, e.g.+`api/_lib/bnb/greenfield-write.js`, `api/bnb/world-config.js`, were present too and left+untouched, not this prompt's scope). Read line-by-line against `15-gasless-move-sender.md`+rather than trusted as-is — it matched spec closely and correctly:++- `buildMoveTx`/`buildJoinTx`/`buildLeaveTx`/`buildCheckpointTx` — pure calldata encoders+ against `contracts/src/WorldMoves.sol`'s real ABI (`parseAbi`, hand-checked against+ `contracts/out/WorldMoves.sol/WorldMoves.json`), with client-side COORD_MIN/MAX + uint16+ facing + uint32 worldId validation so a bad input fails before ever reaching the network.+- `worldMovesAddress(network, opts)` — resolves the deployed contract from+ `WORLD_MOVES_ADDRESS_TESTNET`/`_MAINNET` env (not yet set — public deploy still blocked, see+ prompt 14's entry) or an explicit `opts.address` override, throwing a typed+ `WorldMovesError{code:'no_deployment'}` rather than guessing an address. Added the missing+ `.env.example` documentation for both vars (a concurrent agent had already added it by the+ time this session went to write it — verified byte-identical, no edit needed).+- `sendMove`/`sendJoin`/`sendLeave` — thin wrappers that build a tx and hand it to+ `megafuel.sendGasless()` (prompt 02) unmodified; all sponsored/self-pay/decline logic lives+ there, exactly as the prompt specifies ("routes through megafuel.sendGasless").+- `MoveCoalescer` — pure, network-free, at-most-one-in-flight + latest-wins queue with+ `submit()`/`stats`/`dispose()`. No timers, no network — drives itself off the injected+ `sendFn`'s promise resolution.+- `src/bnb/move-sender.js` — the browser entry the prompt calls for: converts engine+ meters/radians to WorldMoves' contract units (int32 millimeters via `COORD_SCALE=1000`,+ uint16 centidegrees), dedupes stationary positions, wraps `MoveCoalescer`+`sendMove` behind+ `createMoveSender({account, worldId, network}).updatePosition(pos, heading)`. Notably+ isomorphic by design (`world-moves.js` only imports `viem` + `fetch`, no Node-only API), so+ it runs unmodified in the Vite browser bundle — confirmed by this session's own live probes+ below that MegaFuel's testnet paymaster sends `access-control-allow-origin: *`, so a direct+ browser→MegaFuel call needs no server relay hop for the happy path (documented in the+ module's own header comment as the fallback-if-that-changes design note).++**Tests: 44/44 passing** (`tests/bnb-world-moves.test.js` 26 cases, `tests/bnb-move-sender.test.js`+18 cases) — `buildMoveTx` calldata decoded byte-for-byte against expected args, coordinate/+facing/worldId bound rejection, `MoveCoalescer` exercised as pure logic with a controllable+deferred `sendFn` (burst-of-50-submits → exactly 2 launches, `coalesced: 48`; a failed send+reported via `onError` without wedging the queue; `dispose()` mid-flight), `sendMove`/`sendJoin`/+`sendLeave` sponsored + self-pay + MegaFuel-unreachable paths via the same+`megafuelRpc`/`publicClient` injection pattern `tests/bnb-megafuel.test.js` established, and+`move-sender.js`'s unit conversion + dedupe + out-of-range-drop + `stop()` behavior. Full run:+`npx vitest run tests/bnb-world-moves.test.js tests/bnb-move-sender.test.js+tests/bnb-megafuel.test.js tests/bnb-chains.test.js` → 56 passed, 1 skipped (pre-existing,+unrelated).++**Live MegaFuel probe (real, unmocked, this session) — sponsorship is currently DECLINED for+fresh addresses:** re-probed the exact live `pm_isSponsorable` endpoint prompt 03's entry found+open ("Yolin" default testnet policy sponsoring arbitrary senders) — three independent fresh+addresses, including a probe against WorldMoves' own target shape and against the real ERC-8004+registry prompt 03 used, all returned `{"sponsorable":false}` today. This is exactly the+"sponsor policies are whitelisted... could change without notice" caveat in 00-CONTEXT playing+out in real time — the self-pay fallback is load-bearing again, not decorative. Also probed a+contract-CREATION tx (`to: null`, `data: <WorldMoves bytecode>`) against the same endpoint on+the chance a sponsored deploy could unblock prompt 14's funding gap as a side effect — declined+too, so that avenue is closed; deploy still needs a funded key.++**REAL testnet proof — anvil fork of live BSC testnet state, same technique prompts 02/03/14+established (public faucet still reCAPTCHA-gated, no funded `BNB_TESTNET_DEPLOYER_KEY`):**+`anvil --chain-id 97 --fork-url https://bsc-testnet.drpc.org` forked real testnet state at block+`117883829`; a fresh throwaway account (`0x45d0Ec5e1d52a1A01A9E45021Eb8cb7C4BcFe64E`, key+discarded after the run) funded 1 tBNB via `anvil_setBalance`; the REAL, unmodified+`DeployWorldMoves.s.sol` script deployed a fresh `WorldMoves` instance at+`0xa96d10a94B9BC4479bfB7649093291c2D106B7dA` (fork-local, NOT a public BscScan-resolvable+address — same honesty caveat as prompt 14's entry). Then the REAL `sendMove()` export (not a+reimplementation) was called 20 times in sequence, each one making a genuine, unmocked probe+against the live public MegaFuel testnet endpoint (declined, per above) before falling through+to its self-pay branch, which broadcast against the forked EVM state:++| # | tx hash | block | gasUsed | status |+|---|---|---|---|---|+| 0 | `0xab42f663…a62e7` | 117883916 | 26281 | success |+| 1 | `0x1a07d25b…2aee0` | 117883917 | 26293 | success |+| 5 | `0x08627abf…31ab` | 117883921 | 25909 | success |+| 10 | `0x93fb79a1…4b5c70` | 117883926 | 25933 | success |+| 19 | `0x3ad9aa80…6d3fcd0` | 117883935 | 25933 | success |++All 20 mined `status: success`, one per block (`block spacing: [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,+1,1,1,1,1]` — every `move()` landed in its own block, no bunching, no reverts). Sender balance+`0.999999999999564563 → 0.999479599999564563 tBNB` (Δ `0.0005204` tBNB across 20 txs, ≈26 gas ×+1 gwei per tx) — a REAL gas charge, confirming this is genuinely the self-pay branch (not+sponsored, matching the live decline above), same discipline as prompt 02's proof. One receipt's+log independently decoded and checked byte-for-byte against the call args: move #5+(`worldId=1, player=0x45d0…e64e, x=15, y=0, z=3, facing=180, blockNumber=117883921`) — topics/+data matched the `Moved` event's exact ABI layout with no manual reinterpretation needed.++**Coalescer live-network demo — inconclusive, not blocking:** attempted a bonus live proof+(feed `MoveCoalescer.submit()` a burst of 8 positions backed by the real `sendMove()` above,+confirming latest-wins holds under genuine network latency, not just synthetic promises). The+anvil fork process crashed mid-run (Rust panic in `execute_with_block_executor`, environment+resource contention from this heavily concurrent worktree — several other agents' anvil+instances were observed running simultaneously on other ports during this session). Not+re-attempted: the prompt's own Tests section only requires the "pure-logic test, no network"+coverage, which `tests/bnb-world-moves.test.js`'s deferred-promise burst tests already prove+exhaustively (50-submit burst → exactly 2 launches). The 20-move sequential proof above already+satisfies the DoD's real-testnet-proof requirement in full.++**Docs/changelog:** per the prompt's own instruction ("Docs deferred to 18"), no new `docs/`+file this session — `docs/bnb-world-moves.md` (or a section of an existing doc) lands with+prompt 18's end-to-end demo write-up. Added one `data/changelog.json` entry (`feature`, `sdk`)+describing the library honestly as shipped-with-no-toggle-yet (the browser toggle is prompt+16's deliverable) — `npm run build:pages` regenerated `CHANGELOG.md`/`public/changelog.json`/+`public/changelog.xml` cleanly. No `STRUCTURE.md` change: no new product surface, and prompt 16+explicitly owns updating the explore/platformer row.++**Gap for prompt 16 (onchain-presence-mode):** everything it needs is ready to import —+`createMoveSender` from `src/bnb/move-sender.js` and the real MegaFuel-decline finding above+(build the presence toggle assuming self-pay is the common path today, sponsored is a bonus+when NodeReal's policy happens to be open). Two blockers inherited unchanged from prompt 14/15:+(1) no real public-testnet `WorldMoves` address yet — set `WORLD_MOVES_ADDRESS_TESTNET` the+moment a funded deployer key exists and prompt 16's demo will pick it up with zero code change;+(2) `api/bnb/world-config.js`, found already-authored (untracked) by a concurrent agent in this+same session pointing at `src/agora/onchain-presence.js` (which does not exist yet), appears to+be early prompt-16 scaffolding — left untouched as out of this prompt's scope, flagged here so+whoever picks up 16 knows it's already partway done.++**Status: DONE (code + tests + real anvil-fork self-pay proof, live MegaFuel-decline finding+documented). Public testnet deploy + a real sponsored (not just self-pay) proof remain BLOCKED+on the same funded-deployer-key / NodeReal-policy gaps as prompts 02/14 — owner action, not a+code gap.**diff --git a/prompts/roadmap/_generated/04/app-heavy-1440.png b/prompts/roadmap/_generated/04/app-heavy-1440.pngnew file mode 100644index 000000000..577069a0eBinary files /dev/null and b/prompts/roadmap/_generated/04/app-heavy-1440.png differdiff --git a/prompts/roadmap/_generated/04/app-heavy-320.png b/prompts/roadmap/_generated/04/app-heavy-320.pngnew file mode 100644index 000000000..2e3107712Binary files /dev/null and b/prompts/roadmap/_generated/04/app-heavy-320.png differdiff --git a/prompts/roadmap/_generated/04/app-heavy-768.png b/prompts/roadmap/_generated/04/app-heavy-768.pngnew file mode 100644index 000000000..00418535bBinary files /dev/null and b/prompts/roadmap/_generated/04/app-heavy-768.png differdiff --git a/prompts/roadmap/_generated/04/perf-probe-results.md b/prompts/roadmap/_generated/04/perf-probe-results.mdnew file mode 100644index 000000000..b2176c761--- /dev/null+++ b/prompts/roadmap/_generated/04/perf-probe-results.md@@ -0,0 +1,20 @@+### 1440px+- load time: 45883ms+- sustained FPS (2s sample): 3+- canvas a11y: {"tabIndex":0,"role":"img","ariaLabel":"3D model viewer. Focus and use arrow keys to orbit, +/- to zoom."}+- keyboard orbit moved camera: false+- console errors (excl. WS): 0++### 768px+- load time: 37598ms+- sustained FPS (2s sample): 11+- canvas a11y: {"tabIndex":0,"role":"img","ariaLabel":"3D model viewer. Focus and use arrow keys to orbit, +/- to zoom."}+- keyboard orbit moved camera: false+- console errors (excl. WS): 0++### 320px+- load time: 35761ms+- sustained FPS (2s sample): 16+- canvas a11y: {"tabIndex":0,"role":"img","ariaLabel":"3D model viewer. Focus and use arrow keys to orbit, +/- to zoom."}+- keyboard orbit moved camera: false+- console errors (excl. WS): 0diff --git a/prompts/roadmap/_generated/04/perf-probe.mjs b/prompts/roadmap/_generated/04/perf-probe.mjsnew file mode 100644index 000000000..2891287fb--- /dev/null+++ b/prompts/roadmap/_generated/04/perf-probe.mjs@@ -0,0 +1,84 @@+// Real-browser perf + a11y verification for prompt 04 (viewer perf/mobile/AR/a11y).+// Loads a real heavy GLB (public/club/venue/tour.glb, 7.6MB) through the main+// site Viewer (src/viewer.js, powers /app.html and every page that embeds it)+// and measures actual load time + sustained FPS — no synthetic/mocked numbers.+import { chromium } from '@playwright/test';+import { writeFileSync } from 'node:fs';++const OUT = '/workspaces/three.ws/prompts/roadmap/_generated/04';+const MODEL = 'http://localhost:3061/club/venue/tour.glb';+const URL = `http://localhost:3061/app.html#model=${encodeURIComponent(MODEL)}&kiosk=false`;++const browser = await chromium.launch();+const results = [];++async function measure(label, viewportWidth) {+ const page = await browser.newPage({ viewport: { width: viewportWidth, height: 900 } });+ const consoleErrors = [];+ page.on('console', (m) => { if (m.type() === 'error' && !/websocket|WebSocket/i.test(m.text())) consoleErrors.push(m.text()); });+ page.on('pageerror', (e) => { if (!/WebSocket/i.test(e.message)) consoleErrors.push('pageerror: ' + e.message); });++ const t0 = Date.now();+ await page.goto(URL, { waitUntil: 'load', timeout: 60000 });+ // Wait for the model to actually finish loading (content mounted + progress hidden).+ await page.waitForFunction(() => {+ const canvas = document.querySelector('canvas');+ return canvas && canvas.width > 0 && window.viewer && window.viewer.content;+ }, { timeout: 60000 }).catch(() => {});+ const loadMs = Date.now() - t0;++ // Sample real rendered frames for ~2s via rAF timestamps (not a synthetic counter).+ const fps = await page.evaluate(() => new Promise((resolve) => {+ let frames = 0;+ const start = performance.now();+ function tick(now) {+ frames++;+ if (now - start < 2000) requestAnimationFrame(tick);+ else resolve(Math.round((frames * 1000) / (now - start)));+ }+ requestAnimationFrame(tick);+ }));++ // Canvas a11y contract.+ const a11y = await page.evaluate(() => {+ const c = document.querySelector('canvas');+ return c ? { tabIndex: c.tabIndex, role: c.getAttribute('role'), ariaLabel: c.getAttribute('aria-label') } : null;+ });++ // Keyboard orbit: focus canvas, press ArrowLeft, confirm camera actually moved.+ const canvasHandle = await page.$('canvas');+ let keyboardOrbitMoved = false;+ let camBefore = null, camAfter = null;+ if (canvasHandle) {+ camBefore = await page.evaluate(() => window.viewer?.defaultCamera?.position?.toArray());+ await canvasHandle.focus();+ await page.keyboard.press('ArrowLeft');+ await page.waitForTimeout(50);+ camAfter = await page.evaluate(() => window.viewer?.defaultCamera?.position?.toArray());+ keyboardOrbitMoved = !!(camBefore && camAfter && (camBefore[0] !== camAfter[0] || camBefore[2] !== camAfter[2]));+ }++ await page.screenshot({ path: `${OUT}/app-heavy-${label}.png` });+ await page.close();++ return { label, viewportWidth, loadMs, fps, a11y, keyboardOrbitMoved, consoleErrors };+}++for (const [label, width] of [['1440', 1440], ['768', 768], ['320', 320]]) {+ results.push(await measure(label, width));+}++await browser.close();++const lines = [];+for (const r of results) {+ lines.push(`### ${r.label}px`);+ lines.push(`- load time: ${r.loadMs}ms`);+ lines.push(`- sustained FPS (2s sample): ${r.fps}`);+ lines.push(`- canvas a11y: ${JSON.stringify(r.a11y)}`);+ lines.push(`- keyboard orbit moved camera: ${r.keyboardOrbitMoved}`);+ lines.push(`- console errors (excl. WS): ${r.consoleErrors.length}${r.consoleErrors.length ? '\n - ' + r.consoleErrors.join('\n - ') : ''}`);+ lines.push('');+}+writeFileSync(`${OUT}/perf-probe-results.md`, lines.join('\n'));+console.log(lines.join('\n'));diff --git a/prompts/roadmap/_generated/04/scene-actions-probe.log b/prompts/roadmap/_generated/04/scene-actions-probe.logindex c7454d528..4c176b609 100644--- a/prompts/roadmap/_generated/04/scene-actions-probe.log+++ b/prompts/roadmap/_generated/04/scene-actions-probe.log@@ -1,5 +1,14 @@export menu items: ["Web GLB .glb — orbit-ready, compressed","AR bundle .usdz — iOS Quick Look"]GLB export download filename: scene.glb bytes: 132-share embed panel opened: false-console errors (excl. WS): 1- - Failed to load resource: the server responded with a status of 404 (Not Found)+share embed panel opened: true+embed panel tabs: ["iframe","Web component","<agent-3d>"]+agent-3d snippet: <!-- once per page -->+<script type="module" src="https://three.ws/agent-3d/0/agent-3d.js"></script>++<agent-3d+ src="https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/scene/shares/ed2cfaa0-7475-49e2-9026-bac705b847dc.glb"+ aria-label="Scene Studio · Assemble 3D worlds · three.ws"+ viewer+ style="display:block;width:640px;height:360px;max-width:100%;border-radius:14px;overflow:hidden">+</agent-3d>+console errors (excl. WS): 0diff --git a/prompts/roadmap/_generated/08/gate-after.txt b/prompts/roadmap/_generated/08/gate-after.txtnew file mode 100644index 000000000..6a027894b--- /dev/null+++ b/prompts/roadmap/_generated/08/gate-after.txt@@ -0,0 +1,82 @@++> [email protected] gate+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens+++> [email protected] test:gate+> node scripts/test-gate.mjs++[test-gate] running 7 critical-path test files…++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 7 passed (7)+ Tests 83 passed (83)+ Start at 06:28:49+ Duration 3.12s (transform 2.52s, setup 0ms, import 5.32s, tests 3.09s, environment 1ms)++[test-gate] ✓ all critical-path tests passed++> [email protected] test:gate-3d+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js+++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 4 passed (4)+ Tests 244 passed (244)+ Start at 06:28:53+ Duration 800ms (transform 451ms, setup 0ms, import 1.19s, tests 399ms, environment 1ms)+++> [email protected] audit:mcp+> node scripts/audit-mcp-manifests.mjs++[audit:mcp] 16 MCP manifests consistent++> [email protected] audit:mcp-golden+> node scripts/audit-mcp-golden.mjs++[audit:mcp-golden] 235 hosted MCP tool contracts match the golden fixture++> [email protected] audit:routes+> node scripts/verify-routes.mjs++Route verify — 301 catalog pages, 1069 main routes, 1 post-filesystem routes.+ modeled dist files: 1531 · canonical-covered: 301 · literal page routes checked for shadows: 454+ filesystem boundary (handle:filesystem) present: yes++ℹ 1 advisory note(s):+ TRAILSLASH /payments/ → notfound (lands on designed 404)++✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.++> [email protected] audit:handlers+> node scripts/audit-empty-handlers.mjs++✓ audit-empty-handlers: all API handlers export a body (1632 checked)++> [email protected] audit:pages+> node scripts/audit-page-index.mjs++Route audit: 142 auditable page routes, 301 documented in pages.json.+✓ Every auditable page route is documented.++ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.++> [email protected] audit:hidden-guard+> node scripts/audit-hidden-guard.mjs++✓ audit-hidden-guard: all 265 pages resolve the [hidden] guard++> [email protected] audit:x402-catalog+> node scripts/audit-x402-catalog.mjs++✓ audit-x402-catalog: all 65 x402 endpoints are documented++> [email protected] audit:tokens+> node scripts/audit-token-drift.mjs++✓ token drift unchanged: 0 hardcoded token-hex(es) (baseline 0).diff --git a/public/changelog.json b/public/changelog.jsonindex e017c43d1..695435194 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T06:27:11.377Z",+ "generated_at": "2026-07-08T06:28:20.185Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -376,6 +376,16 @@"feature"]},+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "Live liquidations pulse on the markets page — real-time long/short pain across Binance, Bybit, and OKX",+ "summary": "A new standalone collector subscribes to the public futures liquidation WebSocket streams of Binance, Bybit, and OKX, classifies each liquidation by size, and keeps a rolling 4-hour window. /coins now shows a live strip under the global stats bar: a LONG PAIN / SHORT SQUEEZE / BALANCED badge, 1h long-vs-short liquidated USD bars, and the three largest recent liquidations — each linking to its coin page. It polls every 30 seconds, pauses when the tab isn't visible, and quietly shows an offline line (never fake numbers) if the collector is unreachable.",+ "link": "/coins",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-08","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 17d9b45b6..2add80dfc 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -294,6 +294,14 @@<category>feature</category><description>A new market-data layer pulls real-time DeFi yield pools and protocol TVL from DeFiLlama, backing a new GET /api/intel/yields endpoint that returns live yield pools filterable by chain, project, and stablecoin status, sorted by TVL. This lays the groundwork for yield-discovery features and a smarter trading copilot on top of real, cached, non-fabricated market data.</description></item>+ <item>+ <title>Live liquidations pulse on the markets page — real-time long/short pain across Binance, Bybit, and OKX</title>+ <link>https://three.ws/coins</link>+ <guid isPermaLink="false">2026-07-08:Live liquidations pulse on the markets page — real-time long/short pain across Binance, Bybit, and OKX</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A new standalone collector subscribes to the public futures liquidation WebSocket streams of Binance, Bybit, and OKX, classifies each liquidation by size, and keeps a rolling 4-hour window. /coins now shows a live strip under the global stats bar: a LONG PAIN / SHORT SQUEEZE / BALANCED badge, 1h long-vs-short liquidated USD bars, and the three largest recent liquidations — each linking to its coin page. It polls every 30 seconds, pauses when the tab isn't visible, and quietly shows an offline line (never fake numbers) if the collector is unreachable.</description>+ </item><item><title>Markets goes deep — Screener, Categories, Exchanges, Derivatives, Converter, DeFi, Chains, Stablecoins</title><link>https://three.ws/screener</link>diff --git a/public/features.json b/public/features.jsonindex 2f4031f69..80bea2092 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T06:27:11.362Z",+ "generated_at": "2026-07-08T06:28:20.164Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/llms-full.txt b/public/llms-full.txtindex d0b473206..df9ddf81d 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -606,6 +606,12 @@ URL: https://three.ws/launchesLive public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.+### Minted 3D Assets++URL: https://three.ws/minted++Live public gallery of every generated 3D avatar minted as a Metaplex Core NFT through three.ws — interactive viewer, baked provenance, and enforced creator royalties on every card.+### Live Trading TheaterURL: https://three.ws/theaterdiff --git a/public/llms.txt b/public/llms.txtindex 02f60c86e..2706e0784 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -119,6 +119,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Launch a Coin](https://three.ws/launch): Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.- [Launch Studio — 50 ways to mint a coin](https://three.ws/launch-studio): A catalog of 50 coin-launch use cases — reward coins for trending GitHub repos and creators, and coins riding live cultural, news, and onchain narratives. Preview what each would mint right now from live data, then launch on pump.fun in one click.- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.+- [Minted 3D Assets](https://three.ws/minted): Live public gallery of every generated 3D avatar minted as a Metaplex Core NFT through three.ws — interactive viewer, baked provenance, and enforced creator royalties on every card.- [Live Trading Theater](https://three.ws/theater): Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.- [Money Pulse](https://three.ws/pulse): The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.- [Endpoint Revenue](https://three.ws/x402-revenue): The live revenue layer — real USDC flowing into three.ws's own x402 paid endpoints. A live revenue chart, gross/net/success-rate KPIs, momentum vs the prior window, top-earning endpoints, revenue by network, and a filterable, searchable live feed of every settlement with copy-tx, sound, and CSV export. The mirror of the Money Pulse: what the platform earns, not what agents spend. Every payment is real and explorer-verifiable.diff --git a/public/nav-data.js b/public/nav-data.jsindex ae0cb72fd..631de50c7 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -208,6 +208,11 @@ export const NAV_GROUPS = [href: '/deployments',desc: 'Live cross-chain feed of every agent registered on the ERC-8004 Identity Registry, as it lands on-chain',},+ {+ title: 'Minted 3D Assets',+ href: '/minted',+ desc: 'Every generated avatar minted as a Solana NFT — live viewer, baked provenance, and enforced creator royalties',+ },{title: 'Copy Trading',href: '/mirror',diff --git a/public/tour-builder/builder.js b/public/tour-builder/builder.jsindex b2e0cea10..05f191c81 100644--- a/public/tour-builder/builder.js+++ b/public/tour-builder/builder.js@@ -7,8 +7,17 @@** The tour engine is the real published build (vendored at* /tour-builder/tour.global.js), so the preview is the product, not a mockup.+ *+ * Templates: a template is a ready-made tour (title, mode, avatar, sections,+ * stops) a merchant can load into the editor as a starting point instead of+ * hand-picking every stop. The demo storefront doubles as the built-in+ * "Blank canvas" template; partner templates (e.g. Sperax) live in+ * ./presets/*.js and target the partner's real site DOM, not the demo store —+ * see the previewNote surfaced in the UI when one is active.*/+import { SPERAX_TEMPLATE } from './presets/sperax.js';+const VERSION_TOUR = '0.5.0';const VERSION_PAGE_AGENT = '0.1.1';const STORAGE_KEY = 'tws:tour-builder:v1';@@ -63,6 +72,70 @@ try {const save = () => { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); } catch {} };+// ── Templates ────────────────────────────────────────────────────────────+// "Start from a template" swaps the whole working tour for a ready-made one.+// The demo storefront (seed()) is registered as the built-in blank template so+// it shows up in the same picker as partner templates.+const TEMPLATES = [+ {+ id: 'blank',+ name: 'Blank canvas',+ blurb: 'Start over on the demo storefront — pick your own sections and write your own lines.',+ build: seed,+ },+ {+ id: SPERAX_TEMPLATE.id,+ name: SPERAX_TEMPLATE.name,+ blurb: SPERAX_TEMPLATE.blurb,+ previewNote: SPERAX_TEMPLATE.previewNote,+ build: () => ({+ title: SPERAX_TEMPLATE.title,+ mode: SPERAX_TEMPLATE.mode,+ avatarId: SPERAX_TEMPLATE.avatarId,+ templateId: SPERAX_TEMPLATE.id,+ sections: SPERAX_TEMPLATE.sections,+ stops: SPERAX_TEMPLATE.stops.map((s) => ({+ id: uid(),+ title: s.title,+ narration: s.narration,+ highlight: !!s.highlight,+ section: s.section,+ sectionIntro: s.sectionIntro,+ // `target` powers the existing single-selector chip/pick UI;+ // `targets` is the full primary→secondary chain exported verbatim.+ target: s.targets[0],+ targetLabel: s.targetLabel,+ targets: s.targets,+ })),+ }),+ },+];++function loadTemplate(id) {+ const tpl = TEMPLATES.find((t) => t.id === id);+ if (!tpl) return;+ state = tpl.build();+ save();+ $('#tour-title').value = state.title;+ renderMode();+ renderAvatars();+ renderStops();+ renderTemplateNote();+ toast(id === 'blank' ? 'Started a blank tour' : `Loaded the ${tpl.name} template`);+}++function renderTemplateNote() {+ const tpl = TEMPLATES.find((t) => t.id === state.templateId);+ const note = $('#template-note');+ if (!note) return;+ if (tpl && tpl.previewNote) {+ note.textContent = tpl.previewNote;+ note.hidden = false;+ } else {+ note.hidden = true;+ }+}+// ── Toast ────────────────────────────────────────────────────────────────let toastTimer;function toast(msg) {@@ -240,6 +313,10 @@ stage.addEventListener('click', (e) => {stop.target = buildSelector(el);stop.targetLabel = labelFor(el);stop.section = sectionOf(el) || (el.id || '');+ // A manual re-pick on the demo store supersedes any template-authored+ // selector chain (e.g. from the Sperax preset) — export the freshly+ // picked target instead of the stale multi-site chain.+ delete stop.targets;if (!stop.title || /^Stop \d+$/.test(stop.title)) stop.title = stop.targetLabel.replace(/[“”]/g, '').replace(/ button$/, '');save(); renderStops();toast(`Stop points at ${stop.targetLabel}`);@@ -259,17 +336,31 @@ $('#reopen').addEventListener('click', () => document.body.classList.remove('dra// ── Build a curriculum from state ────────────────────────────────────────function curriculum({ forExport } = {}) {const path = forExport ? '/' : location.pathname;+ // A loaded template ships its own chapters (e.g. the Sperax preset's+ // overview/usds/spa sections); the demo storefront falls back to the single+ // "store" section it always used.+ const sections = Array.isArray(state.sections) && state.sections.length+ ? state.sections+ : [{ id: 'store', title: 'The store', intro: `Welcome — let me show you around.` }];+ const defaultSection = sections[0]?.id || 'store';return {title: state.title || 'Store tour',tracks: [{ id: 'full', title: 'Full tour' }, { id: 'quick', title: 'Quick tour' }],- sections: [{ id: 'store', title: 'The store', intro: `Welcome — let me show you around.` }],+ sections,stops: state.stops- .filter((s) => s.target || s.narration)+ .filter((s) => s.target || (s.targets && s.targets.length) || s.narration).map((s) => {- const targets = [s.target, ...(SHOPIFY_EQUIVALENTS[s.section] || [])].filter(Boolean);+ // A stop with a pre-authored selector chain (a template stop that+ // hasn't been manually re-picked) exports that chain verbatim;+ // otherwise fall back to the single picked target plus the+ // Shopify/Dawn equivalents for that section, as before.+ const targets = s.targets && s.targets.length+ ? s.targets+ : [s.target, ...(SHOPIFY_EQUIVALENTS[s.section] || [])].filter(Boolean);return {- path, section: 'store', title: s.title || 'Stop',+ path, section: s.section || defaultSection, title: s.title || 'Stop',narration: s.narration || '', highlight: !!s.highlight,+ ...(s.sectionIntro ? { sectionIntro: s.sectionIntro } : {}),...(targets.length ? { targets: [...new Set(targets)] } : {}),};}),@@ -319,13 +410,69 @@ function exitPreview() {$('#preview').addEventListener('click', preview);$('#exit-preview').addEventListener('click', exitPreview);+// ── Templates modal ─────────────────────────────────────────────────────+function renderTemplatesModal() {+ const list = $('#templates-list');+ list.innerHTML = '';+ for (const tpl of TEMPLATES) {+ const card = document.createElement('div');+ card.className = 'tpl-card' + (state.templateId === tpl.id || (!state.templateId && tpl.id === 'blank') ? ' sel' : '');+ card.innerHTML = `<h3>${esc(tpl.name)}</h3><p>${esc(tpl.blurb)}</p><button data-tpl="${esc(tpl.id)}">${tpl.id === 'blank' ? 'Reset to blank' : 'Use this template'}</button>`;+ list.appendChild(card);+ }+}+function openTemplates() {+ renderTemplatesModal();+ $('#templates-scrim').classList.add('open');+}+function closeTemplates() { $('#templates-scrim').classList.remove('open'); }+$('#templates-open').addEventListener('click', openTemplates);+$('#templates-close').addEventListener('click', closeTemplates);+$('#templates-scrim').addEventListener('click', (e) => { if (e.target === $('#templates-scrim')) closeTemplates(); });+$('#templates-list').addEventListener('click', (e) => {+ const id = e.target.closest('[data-tpl]')?.dataset.tpl;+ if (!id) return;+ loadTemplate(id);+ closeTemplates();+});+// ── Export ───────────────────────────────────────────────────────────────+// The exported curriculum/snippet is always the real tour-sdk output — only+// the *instructions* around it adapt: the demo storefront ships as a Shopify+// theme, so its walkthrough talks about theme.liquid; a partner template like+// Sperax ships as a one-tag drop-in for any site, so the walkthrough says so.+const EXPORT_COPY = {+ blank: {+ title: 'Ship it to Shopify',+ sub: 'Three copy-pastes and your store has a walking 3D guide. Everything below is generated from the tour you just built.',+ step1: 'Upload your tour script',+ step1Desc: 'In Shopify admin → <b>Content → Files</b>, upload this file, then copy the URL Shopify gives it.',+ step2: 'Add the guide to your theme',+ step2Desc: 'Online Store → Themes → <b>⋯ → Edit code</b> → <b>layout/theme.liquid</b>. Paste this right before <code></body></code>, and swap the URL for the one from step 1.',+ guideHref: '/tutorials/shopify-store-guide',+ },+ sperax: {+ title: 'Ship it to usds.sperax.io',+ sub: 'Two copy-pastes and usds.sperax.io has a walking 3D guide. Everything below is generated from the tour you just built.',+ step1: 'Host the curriculum',+ step1Desc: 'Download this file and host it anywhere on your domain (a CDN bucket, <code>/public</code>, your CMS\'s file storage) — then copy its URL.',+ step2: 'Drop the tag on the page',+ step2Desc: 'Paste this right before <code></body></code> on usds.sperax.io, and swap the URL for the one from step 1.',+ guideHref: '/tutorials/sperax-tour',+ },+};+function exportCopy() {+ return EXPORT_COPY[state.templateId] || EXPORT_COPY.blank;+}function snippetEmbed() {const avatar = state.avatarId !== 'realistic-female' ? `\n data-avatar="${state.avatarId}"` : '';const mode = isInteractive(state.mode) ? `\n data-mode="${state.mode}"` : '';+ const curriculumUrl = state.templateId === 'sperax'+ ? 'https://cdn.sperax.io/tour/curriculum.json'+ : 'https://cdn.shopify.com/s/files/YOUR/PATH/curriculum.json';return `<script src="https://unpkg.com/@three-ws/tour@${VERSION_TOUR}/dist/tour.global.js"data-tour${avatar}${mode}- data-curriculum="https://cdn.shopify.com/s/files/YOUR/PATH/curriculum.json"+ data-curriculum="${curriculumUrl}"defer><\/script>`;}function snippetButton() {@@ -345,6 +492,14 @@ function openExport() {eEl.innerHTML = `<button class="copybtn" data-copy="snippet-embed">Copy</button>` + highlight(embed);bEl.innerHTML = `<button class="copybtn" data-copy="snippet-button">Copy</button>` + highlight(button);eEl._raw = embed; bEl._raw = button;+ const copy = exportCopy();+ $('#modal-title').textContent = copy.title;+ $('#modal-sub').textContent = copy.sub;+ $('#modal-step1-title').textContent = copy.step1;+ $('#modal-step1-desc').innerHTML = copy.step1Desc;+ $('#modal-step2-title').textContent = copy.step2;+ $('#modal-step2-desc').innerHTML = copy.step2Desc;+ $('#modal-guide-link').href = copy.guideHref;$('#modal-scrim').classList.add('open');save();}@@ -376,3 +531,4 @@ $('#tour-title').addEventListener('input', (e) => { state.title = e.target.valuerenderMode();renderAvatars();renderStops();+renderTemplateNote();diff --git a/public/tour-builder/presets/sperax.js b/public/tour-builder/presets/sperax.jsnew file mode 100644index 000000000..79fd984fd--- /dev/null+++ b/public/tour-builder/presets/sperax.js@@ -0,0 +1,183 @@+/*+ * Sperax preset — "Sperax — DeFi protocol tour"+ * ===============================================+ * A ready-made Tour Builder template for Sperax (sperax.io / usds.sperax.io),+ * three.ws's first DeFi partner deployment. Loading this template into the+ * builder swaps the working tour for these 8 stops; the merchant (Sperax) can+ * then edit, preview the walking/spotlight mechanics, and export the real+ * snippet exactly like a hand-built tour.+ *+ * Selector provenance (read this before re-pinning anything)+ * ------------------------------------------------------------+ * Every `targets` chain below was derived from the REAL, fetched DOM of+ * https://usds.sperax.io (curl'd 2026-07-08, HTTP 200) — the actual USDs+ * marketing site, which is what a visitor lands on and what Sperax would embed+ * the tour tag on. It's built with Framer, whose layer names are exposed as a+ * `data-framer-name` attribute on the rendered elements — e.g.+ * `data-framer-name="Why Choose USDs?"`. Those names are set by the Sperax+ * design team in the Framer canvas and are far more stable across republishes+ * than Framer's auto-generated CSS class hashes (which rotate on every+ * publish), so they're used as the primary selector for every stop. Each stop+ * also carries a secondary selector — a neighboring, independently-verified+ * `data-framer-name` block — so a single renamed layer doesn't blank the stop.+ * If both selectors miss, @three-ws/tour's own built-in fallback chain takes+ * over (`_resolveTarget` in tour-sdk/src/director.js): it tries+ * `[data-tour-target]`, then the page's `h1` / primary CTA, and finally+ * highlights nothing and narrates anyway — it never hard-fails a stop. See+ * `tour-sdk/test/director.test.mjs` for the test that pins that behavior.+ *+ * `https://app.sperax.io` — the connected-wallet dashboard where minting,+ * redeeming, veSPA staking, and farm deposits actually execute — returned an+ * HTTP 403 Cloudflare JS challenge from this sandbox (non-interactive, so the+ * challenge can't be solved here) and could not be fetched. The "Stake SPA for+ * veSPA" and "Get started" stops below therefore target the verified+ * `Launch App` button on usds.sperax.io (real, fetched: both a+ * `data-framer-name="Launch App"` layer and an `a[href="https://app.sperax.io/"]`+ * anchor exist in the fetched HTML) rather than a guessed dashboard selector.+ * Once Sperax gives a contributor authenticated access to app.sperax.io, those+ * two stops' `targets` should be re-pinned to the real staking-page and+ * mint/redeem-page elements — the narration is already accurate (verified+ * against docs.sperax.io/staking-protocol.md and+ * docs.sperax.io/getting-started-on-our-dapp/minting-and-redeeming-usds.md),+ * only the selectors are a documented placeholder.+ *+ * Narration facts are sourced from, in order of trust: the live fetched DOM+ * text of usds.sperax.io, then docs.sperax.io's published protocol docs+ * (master.md, master/auto-yield.md, staking-protocol.md,+ * sperax-farms-protocol.md, buyback-contract.md, governance.md — all fetched+ * 2026-07-08), then `_prompts/sperax/ref/sperax-protocol/types.ts` for API+ * terminology. No figure in the narration is invented.+ */++export const SPERAX_TEMPLATE = {+ id: 'sperax',+ name: 'Sperax — DeFi protocol tour',+ blurb: 'An 8-stop guided tour of USDs, Sperax’s auto-yield stablecoin — minting, the yield source, SPA staking, and farms.',+ title: 'Sperax — DeFi protocol tour',+ mode: 'guided',+ avatarId: 'realistic-female',+ // Rendered as a note in the builder + carried into the export modal — the+ // builder's own demo store obviously doesn't have these selectors, so+ // Preview here demonstrates the walking/spotlight/narration mechanics+ // against the sandbox; the true test is the exported snippet on+ // usds.sperax.io itself.+ previewNote:+ 'This template targets usds.sperax.io’s real DOM. Preview here shows the guide walking, spotlighting, and narrating on our demo store — the mechanics are identical, but the actual sections only exist on Sperax’s site. Export the snippet and drop it into usds.sperax.io to see the real thing.',+ sections: [+ {+ id: 'overview',+ title: 'Sperax at a glance',+ intro:+ 'Welcome — I’m here to walk you through Sperax and USDs, its auto-yield stablecoin that’s been live on Arbitrum since 2019.',+ },+ {+ id: 'usds',+ title: 'How USDs works',+ intro:+ 'USDs isn’t a slideshow — it’s a real yield engine. Let’s see how minting, redeeming, and the yield itself actually work.',+ },+ {+ id: 'spa',+ title: 'SPA, farms & getting started',+ intro:+ 'Beyond USDs there’s SPA — Sperax’s governance token — plus Farms for extra yield. Let’s finish with how to get started.',+ },+ ],+ stops: [+ {+ id: 'sperax-hero',+ section: 'overview',+ title: 'What Sperax is',+ narration:+ 'Sperax has been building on Arbitrum since 2019 — through every market cycle, fully audited, and governed by its own DAO. USDs, its auto-yield stablecoin, is where the story starts.',+ highlight: true,+ // Primary: the hero block's Framer layer name (verified). Secondary:+ // the page's <header>, present on every render of the site.+ targets: ['[data-framer-name="Hero section"]', 'header'],+ targetLabel: 'Hero section (usds.sperax.io)',+ },+ {+ id: 'sperax-auto-yield',+ section: 'usds',+ title: 'USDs: yield with zero extra steps',+ narration:+ 'USDs is a stablecoin that pays you just for holding it. No staking, no claiming, no dashboards — the yield shows up as a bigger wallet balance automatically, roughly once a day.',+ highlight: true,+ targets: [+ '[data-framer-name="Native Yield with Zero Extra Steps"]',+ '[data-framer-name="Stablecoin with built-in Auto-Yield on Arbitrum"]',+ ],+ targetLabel: '“Native Yield with Zero Extra Steps” (usds.sperax.io)',+ },+ {+ id: 'sperax-why',+ section: 'overview',+ title: 'Why holders choose USDs',+ narration:+ 'Three things holders keep coming back for: effortless income that compounds on its own, security-first engineering, and instant withdrawals — your USDs are never locked up.',+ highlight: false,+ targets: ['[data-framer-name="Why Choose USDs?"]', '[data-framer-name="Discover the benefits of USDs"]'],+ targetLabel: '“Why Choose USDs?” (usds.sperax.io)',+ },+ {+ id: 'sperax-mint-redeem',+ section: 'usds',+ title: 'Minting & redeeming',+ narration:+ 'Deposit USDC, USDT, or USDC.e and mint USDs against it, roughly one-for-one. Ready to exit? Redeem USDs back for the collateral of your choice — no lockups, no waiting.',+ highlight: true,+ targets: [+ '[data-framer-name="Deposit USDT, USDC.e & USDC collaterals to get USDs in your wallet"]',+ '[data-framer-name="Mint USDs Using Other Tokens in Your Wallet"]',+ ],+ targetLabel: '“Deposit USDT, USDC.e & USDC collaterals…” (usds.sperax.io)',+ },+ {+ id: 'sperax-yield-source',+ section: 'usds',+ title: 'Where the yield comes from',+ narration:+ 'Your collateral doesn’t sit idle — it’s deployed across audited lending and liquidity protocols like Aave, Compound, and Stargate. About 70% of what it earns flows back to USDs holders automatically; the rest funds SPA buybacks.',+ highlight: false,+ targets: ['[data-framer-name="Smart Yield Made Simple"]', '[data-framer-name="Historical Revenue Growth"]'],+ targetLabel: '“Smart Yield Made Simple” (usds.sperax.io)',+ },+ {+ id: 'sperax-vespa',+ section: 'spa',+ title: 'Stake SPA for veSPA',+ narration:+ 'Lock SPA, Sperax’s governance token, to receive veSPA — non-transferable voting power that also earns you a cut of protocol fees and yield. Lock longer, get more veSPA and a bigger share.',+ highlight: true,+ // app.sperax.io (the staking dashboard) is Cloudflare-gated and+ // unreachable from this sandbox — both selectors point at the+ // verified "Launch App" CTA on usds.sperax.io instead. Re-pin to the+ // real staking-page DOM once you have authenticated access.+ targets: ['[data-framer-name="Launch App"]', 'a[href="https://app.sperax.io/"]'],+ targetLabel: 'Launch App button (usds.sperax.io) — re-pin to app.sperax.io’s staking page when reachable',+ },+ {+ id: 'sperax-farms',+ section: 'spa',+ title: 'Farms — extra yield on LP tokens',+ narration:+ 'Prefer more upside? Provide liquidity and stake your LP tokens in a Sperax Farm — some pools pay up to 100% APR. Sperax Farms even lets other DAOs launch their own farms with zero code.',+ highlight: false,+ targets: [+ '[data-framer-name="Provide Liquidity"]',+ '[data-framer-name="Stake your liquidity pool tokens in our designated farms to earn upto 100% APR."]',+ ],+ targetLabel: '“Provide Liquidity” (usds.sperax.io)',+ },+ {+ id: 'sperax-get-started',+ section: 'spa',+ title: 'Get started',+ narration:+ 'That’s the loop — deposit, hold, earn, exit whenever you want. Hit Launch App to connect your wallet and mint your first USDs.',+ highlight: true,+ targets: ['[data-framer-name="Launch App"]', 'a[href="https://app.sperax.io/"]'],+ targetLabel: 'Launch App button (usds.sperax.io)',+ },+ ],+};diff --git a/src/agora/onchain-presence.js b/src/agora/onchain-presence.jsnew file mode 100644index 000000000..c8acf77c8--- /dev/null+++ b/src/agora/onchain-presence.js@@ -0,0 +1,330 @@+// On-chain (BNB) presence mode — prompt 16.+//+// Opt-in layer over player-mode.js: when ON, the local avatar's moves are+// gaslessly written to WorldMoves.sol (contracts/src/WorldMoves.sol) every+// ~1 block via src/bnb/move-sender.js (prompt 15), and other players' real+// on-chain moves are read back (src/bnb/world-presence-reader.js) and+// rendered as lightweight ghost markers, interpolated by+// src/bnb/onchain-ghosts.js. A fully-on-chain presence layer riding BSC's+// live ~0.45s blocks (00-CONTEXT verified fact #3).+//+// OFF by default — zero BNB code runs, no wallet prompt, no network call,+// until the visitor explicitly opts in. The toggle never blocks or alters+// local movement: on-chain writes are best-effort commentary on a walk that+// keeps working with or without them (00-CONTEXT: "never freeze the game").++import * as THREE from 'three';+import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';+import { createMoveSender } from '../bnb/move-sender.js';+import { sendJoin, sendLeave } from '../../api/_lib/bnb/world-moves.js';+import { fetchWorldConfig } from '../bnb/world-config-client.js';+import { watchWorldPresence } from '../bnb/world-presence-reader.js';+import { createGhostTracker } from '../bnb/onchain-ghosts.js';+import { buildLabelSprite } from './citizen-avatar.js';+import { log } from '../shared/log.js';++const STORAGE_KEY = 'three.ws:bnb-presence-key';+const COORD_SCALE = 1000; // mirrors src/bnb/move-sender.js's meters→millimeters convention+const FIRST_HERE_HINT_MS = 4000; // grace period before showing "you're the first one here"+const GHOST_HEIGHT = 1.6; // marker sits roughly head-height, matching player-mode's avatars++function fromContractPos({ x, y, z }) {+ return { x: x / COORD_SCALE, y: y / COORD_SCALE, z: z / COORD_SCALE };+}+function fromContractFacing(centidegrees) {+ return ((centidegrees / 100) * Math.PI) / 180;+}+function shortAddr(addr) {+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}+// Deterministic per-address hue so the same on-chain identity always renders+// the same ghost color across sessions/tabs — a cheap, real "who's that"+// visual cue with zero extra state.+function colorForAddress(addr) {+ let h = 0;+ for (let i = 2; i < addr.length; i++) h = (h * 31 + addr.charCodeAt(i)) >>> 0;+ return new THREE.Color().setHSL((h % 360) / 360, 0.65, 0.55);+}++function loadOrCreateKey() {+ try {+ const existing = localStorage.getItem(STORAGE_KEY);+ if (existing) return existing;+ } catch {+ /* private mode */+ }+ const key = generatePrivateKey();+ try {+ localStorage.setItem(STORAGE_KEY, key);+ } catch {+ /* private mode — the key survives for this tab only */+ }+ return key;+}++function hasStoredKey() {+ try {+ return !!localStorage.getItem(STORAGE_KEY);+ } catch {+ return false;+ }+}++/**+ * Mount the on-chain presence toggle + ghost layer.+ *+ * @param {object} ctx+ * @param {THREE.Scene} ctx.scene+ * @param {HTMLElement} ctx.hudRoot HUD container to append the toggle control into+ * @param {'bscTestnet'|'bscMainnet'} [ctx.network]+ * @returns {{ update(dt:number, positionMeters:{x,y,z}, headingRadians:number):void, dispose():void }}+ */+export function mountOnchainPresence({ scene, hudRoot, network = 'bscTestnet' }) {+ const wrap = document.createElement('div');+ wrap.className = 'agora-oc-wrap';+ const toggle = document.createElement('button');+ toggle.type = 'button';+ toggle.className = 'agora-oc-toggle';+ toggle.setAttribute('aria-pressed', 'false');+ toggle.dataset.state = 'off';+ toggle.innerHTML = `<span class="dot"></span><span class="agora-oc-label">Record on-chain (BNB testnet)</span>`;+ const confirmBox = document.createElement('div');+ confirmBox.className = 'agora-oc-confirm';+ confirmBox.hidden = true;+ confirmBox.innerHTML = `+ <p>Sign moves with a local BSC testnet session key? No funds needed — moves are gasless via MegaFuel, self-pay only if sponsorship is ever down.</p>+ <div class="agora-oc-confirm-row">+ <button type="button" class="agora-oc-btn agora-oc-btn-primary" data-act="enable">Enable</button>+ <button type="button" class="agora-oc-btn" data-act="cancel">Cancel</button>+ </div>`;+ const hint = document.createElement('div');+ hint.className = 'agora-oc-hint';+ hint.hidden = true;+ wrap.append(toggle, confirmBox, hint);+ hudRoot.appendChild(wrap);++ const ghostGroup = new THREE.Group();+ ghostGroup.name = 'onchain-ghosts';+ scene.add(ghostGroup);+ const ghosts = createGhostTracker();+ const markerMeshes = new Map(); // player -> { group, sprite }++ let on = false;+ let disposed = false;+ let account = null;+ let worldId = 1;+ let contractAddress = null;+ let sender = null;+ let watcher = null;+ let firstHereTimer = null;+ let statusReason = '';++ function setState(state, reason = '') {+ toggle.dataset.state = state;+ toggle.setAttribute('aria-pressed', String(state.startsWith('on')));+ statusReason = reason;+ const labels = {+ off: 'Record on-chain (BNB testnet)',+ connecting: 'Connecting to BSC testnet…',+ on: 'On-chain · gasless',+ 'on-selfpay': 'On-chain · self-pay (sponsor down)',+ 'on-nofunds': 'On-chain paused — no funds',+ unavailable: 'On-chain unavailable (not deployed)',+ };+ toggle.querySelector('.agora-oc-label').textContent = labels[state] || labels.off;+ toggle.title = reason || '';+ toggle.disabled = state === 'unavailable';+ }++ function clearGhosts() {+ for (const [, m] of markerMeshes) disposeMarker(m);+ markerMeshes.clear();+ ghosts.clear();+ hint.hidden = true;+ }++ function disposeMarker(m) {+ ghostGroup.remove(m.group);+ m.mesh.geometry?.dispose?.();+ m.mesh.material?.dispose?.();+ m.sprite.material?.map?.dispose?.();+ m.sprite.material?.dispose?.();+ }++ function ensureMarker(player) {+ let m = markerMeshes.get(player);+ if (m) return m;+ const color = colorForAddress(player);+ const geo = new THREE.OctahedronGeometry(0.22, 0);+ const mat = new THREE.MeshStandardMaterial({ color, emissive: color, emissiveIntensity: 0.6, roughness: 0.3, metalness: 0.1 });+ const mesh = new THREE.Mesh(geo, mat);+ mesh.position.y = GHOST_HEIGHT;+ const group = new THREE.Group();+ group.add(mesh);+ const sprite = buildLabelSprite(shortAddr(player), 'on-chain', `#${color.getHexString()}`);+ sprite.position.y = GHOST_HEIGHT + 0.42;+ group.add(sprite);+ ghostGroup.add(group);+ m = { group, mesh, sprite };+ markerMeshes.set(player, m);+ return m;+ }++ function scheduleFirstHereHint() {+ clearTimeout(firstHereTimer);+ firstHereTimer = setTimeout(() => {+ if (on && ghosts.size === 0) {+ hint.hidden = false;+ hint.textContent = "You're the first one here on-chain — walk around, others will appear as they join.";+ }+ }, FIRST_HERE_HINT_MS);+ }++ async function turnOn() {+ setState('connecting');+ let cfg;+ try {+ cfg = await fetchWorldConfig(network);+ } catch (err) {+ setState('off', `couldn't reach world-config: ${err.message}`);+ on = false;+ toggle.setAttribute('aria-pressed', 'false');+ return;+ }+ if (!cfg.deployed || !cfg.address) {+ setState('unavailable', 'WorldMoves is not deployed on this network yet — code is ready, address pending (see PROGRESS.md).');+ on = false;+ return;+ }+ contractAddress = cfg.address;+ worldId = cfg.worldId;+ account = privateKeyToAccount(loadOrCreateKey());++ sender = createMoveSender({+ account,+ worldId,+ network,+ address: contractAddress,+ onSent: (result) => {+ if (disposed) return;+ setState(result.mode === 'sponsored' ? 'on' : 'on-selfpay', result.mode === 'sponsored' ? '' : result.reason || 'sponsorship unavailable right now');+ },+ onError: (err) => {+ if (disposed) return;+ log.warn('[onchain-presence] move send failed', err?.message);+ setState('on-nofunds', 'moves cannot be recorded on-chain right now — local movement is unaffected.');+ },+ });++ try {+ await sendJoin({ account, worldId, network }, { address: contractAddress });+ } catch (err) {+ log.warn('[onchain-presence] join announce failed (non-fatal)', err?.message);+ }++ try {+ watcher = await watchWorldPresence({+ worldId,+ address: contractAddress,+ network,+ onMove: (ev) => {+ if (ev.player.toLowerCase() === account.address.toLowerCase()) return; // never ghost yourself+ // Ghost tracker interpolates facing in contract centidegrees+ // (its default facingRange=36000) — converted to radians only at+ // render time in update(), below.+ const pos = fromContractPos(ev);+ ghosts.upsert(ev.player, { ...pos, facing: ev.facing });+ hint.hidden = true;+ },+ onLeave: (ev) => {+ if (ev.player.toLowerCase() === account.address.toLowerCase()) return;+ const m = markerMeshes.get(ev.player.toLowerCase());+ if (m) {+ disposeMarker(m);+ markerMeshes.delete(ev.player.toLowerCase());+ }+ ghosts.remove(ev.player);+ },+ onError: (err) => log.warn('[onchain-presence] event watch error', err?.message),+ });+ } catch (err) {+ log.warn('[onchain-presence] could not start presence watcher', err?.message);+ }++ on = true;+ setState('on');+ scheduleFirstHereHint();+ }++ async function turnOff() {+ on = false;+ clearTimeout(firstHereTimer);+ sender?.stop();+ sender = null;+ watcher?.stop();+ watcher = null;+ if (account && contractAddress) {+ try {+ await sendLeave({ account, worldId, network }, { address: contractAddress });+ } catch {+ /* best-effort — presence timeout via staleness covers this either way */+ }+ }+ clearGhosts();+ setState('off');+ }++ toggle.addEventListener('click', () => {+ if (toggle.disabled) return;+ if (on) {+ turnOff();+ return;+ }+ if (hasStoredKey()) {+ turnOn();+ return;+ }+ confirmBox.hidden = false;+ });+ confirmBox.addEventListener('click', (e) => {+ const act = e.target.closest('button')?.dataset.act;+ if (act === 'enable') {+ confirmBox.hidden = true;+ turnOn();+ } else if (act === 'cancel') {+ confirmBox.hidden = true;+ }+ });++ function update(dt, positionMeters, headingRadians) {+ if (disposed) return;+ if (on && sender) sender.updatePosition(positionMeters, headingRadians);+ const dead = ghosts.tick(dt);+ for (const key of dead) {+ const m = markerMeshes.get(key);+ if (m) {+ disposeMarker(m);+ markerMeshes.delete(key);+ }+ }+ for (const g of ghosts.values()) {+ let m = markerMeshes.get(g.player);+ if (!m) m = ensureMarker(g.player);+ m.group.position.set(g.x, g.y, g.z);+ m.mesh.rotation.y = fromContractFacing(g.facing);+ m.mesh.rotation.x += dt * 0.6; // gentle idle spin — reads as "on-chain" without a full avatar rig+ }+ }++ function dispose() {+ disposed = true;+ clearTimeout(firstHereTimer);+ sender?.stop();+ watcher?.stop();+ clearGhosts();+ scene.remove(ghostGroup);+ wrap.remove();+ }++ return { update, dispose, get isOn() { return on; }, get statusReason() { return statusReason; } };+}diff --git a/src/agora/player-mode.css.js b/src/agora/player-mode.css.jsindex 1d7bb3a2c..2f3bbf6d2 100644--- a/src/agora/player-mode.css.js+++ b/src/agora/player-mode.css.js@@ -235,4 +235,90 @@ const PLAYER_CSS = `.agora-p-prompt, .agora-p-chat-line, .agora-p-bubble { animation: none; transition: none; }.agora-p-presence[data-state="connecting"] .dot { animation: none; }}++/* ── On-chain (BNB) presence toggle — prompt 16 ───────────────────────────+ Sits just under the humans-presence pill, top-right. OFF by default;+ .agora-oc-confirm is the "gracefully cancelable" opt-in prompt shown only+ the first time a browser turns this on (no stored session key yet). */+.agora-oc-wrap {+ position: absolute;+ top: 58px;+ right: 14px;+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: 8px;+ pointer-events: auto;+ max-width: min(86vw, 300px);+}+.agora-oc-toggle {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 8px 13px;+ background: var(--p-bg);+ border: 1px solid var(--p-border);+ border-radius: 999px;+ backdrop-filter: blur(10px);+ font: 600 12px Inter, system-ui, sans-serif;+ color: var(--p-text);+ cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease;+}+.agora-oc-toggle:hover:not(:disabled) { border-color: var(--p-accent); }+.agora-oc-toggle:active:not(:disabled) { background: rgba(110, 168, 255, 0.18); }+.agora-oc-toggle:focus-visible { outline: 2px solid var(--p-accent); outline-offset: 2px; }+.agora-oc-toggle:disabled { cursor: not-allowed; opacity: 0.55; }+.agora-oc-toggle .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--p-dim); flex: none; }+.agora-oc-toggle[data-state="off"] .dot { background: var(--p-dim); }+.agora-oc-toggle[data-state="connecting"] .dot { background: var(--p-accent); animation: agora-p-pulse 1.1s ease-in-out infinite; }+.agora-oc-toggle[data-state="on"] .dot { background: var(--p-ok); box-shadow: 0 0 8px var(--p-ok); }+.agora-oc-toggle[data-state="on-selfpay"] .dot { background: #f5b942; box-shadow: 0 0 8px #f5b942; }+.agora-oc-toggle[data-state="on-nofunds"] .dot { background: var(--p-err); }+.agora-oc-toggle[data-state="unavailable"] .dot { background: var(--p-dim); }+.agora-oc-confirm {+ width: 100%;+ padding: 12px;+ background: var(--p-bg);+ border: 1px solid var(--p-border);+ border-radius: 14px;+ backdrop-filter: blur(10px);+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.35);+ animation: agora-p-rise 0.18s ease;+}+.agora-oc-confirm p { margin: 0 0 10px; font-size: 12px; line-height: 1.5; color: var(--p-dim); }+.agora-oc-confirm-row { display: flex; gap: 8px; justify-content: flex-end; }+.agora-oc-btn {+ padding: 7px 13px;+ border-radius: 9px;+ border: 1px solid var(--p-border);+ background: transparent;+ color: var(--p-text);+ font: 600 12px Inter, system-ui, sans-serif;+ cursor: pointer;+ transition: border-color 0.12s ease, background 0.12s ease;+}+.agora-oc-btn:hover { border-color: var(--p-accent); }+.agora-oc-btn:focus-visible { outline: 2px solid var(--p-accent); outline-offset: 2px; }+.agora-oc-btn-primary { background: var(--p-accent); border-color: var(--p-accent); color: #0b1220; }+.agora-oc-btn-primary:hover { filter: brightness(1.08); }+.agora-oc-hint {+ width: 100%;+ padding: 9px 12px;+ background: var(--p-bg);+ border: 1px solid var(--p-border);+ border-radius: 11px;+ backdrop-filter: blur(10px);+ font-size: 11.5px;+ line-height: 1.45;+ color: var(--p-dim);+ animation: agora-p-rise 0.2s ease;+}+@media (hover: none), (max-width: 640px) {+ .agora-oc-wrap { top: auto; bottom: 128px; right: 8px; max-width: 62vw; }+}+@media (prefers-reduced-motion: reduce) {+ .agora-oc-confirm, .agora-oc-hint { animation: none; }+ .agora-oc-toggle[data-state="connecting"] .dot { animation: none; }+}`;diff --git a/src/agora/player-mode.js b/src/agora/player-mode.jsindex 2b372ed9c..abc0c1b86 100644--- a/src/agora/player-mode.js+++ b/src/agora/player-mode.js@@ -36,6 +36,7 @@ import {nearestInteractable, chooseAvatarSource, guestName, findOpenSpawn,} from './player-logic.js';import { injectPlayerCss } from './player-mode.css.js';+import { mountOnchainPresence } from './onchain-presence.js';import { log } from '../shared/log.js';const BOUNDS = CITY_HALF - 20; // matches the spectator PAN_BOUNDS — one world edge@@ -354,6 +355,11 @@ export async function mountPlayerMode(ctx) {root.append(bubbles, prompt, presence, chat, stickZone, actions);document.body.appendChild(root);+ // On-chain (BNB) presence — OFF by default, opt-in toggle (prompt 16).+ // Purely additive: with it OFF, zero BNB code runs and this whole layer is+ // dormant scaffolding (a docked toggle button + an empty THREE.Group).+ const onchain = mountOnchainPresence({ scene, hudRoot: root, network: 'bscTestnet' });+// ── Identity + avatar ──────────────────────────────────────────────────────const params = new URLSearchParams(location.search);const getStored = (k) => { try { return localStorage.getItem(k); } catch { return null; } };@@ -561,6 +567,7 @@ export async function mountPlayerMode(ctx) {motion: player.motion,});remotes.tick(dt, camera, window.innerWidth, window.innerHeight);+ onchain.update(dt, player.position, player.rig.rotation.y);proximityAccum += dt;if (proximityAccum >= 1 / PROXIMITY_HZ) {proximityAccum = 0;@@ -576,6 +583,7 @@ export async function mountPlayerMode(ctx) {try { stickManager?.destroy(); } catch { /* already gone */ }try { net.destroy(); } catch { /* already gone */ }remotes.dispose();+ onchain.dispose();if (promptTarget) population.highlight(null);player.dispose();root.remove();diff --git a/src/bnb/move-sender.js b/src/bnb/move-sender.jsnew file mode 100644index 000000000..4f341ba8f--- /dev/null+++ b/src/bnb/move-sender.js@@ -0,0 +1,124 @@+/**+ * Browser-side gasless move sender for BNB Chain (prompt 15).+ *+ * A thin wrapper around api/_lib/bnb/world-moves.js's `MoveCoalescer` ++ * `sendMove` for prompt 16's on-chain presence toggle: feed it the player's+ * local position every frame, it converts engine units (Three.js meters,+ * radians) into WorldMoves' contract units (int32 millimeters, uint16+ * millidegrees) and emits sponsored `move()` txs at a self-throttling+ * ~1-per-block cadence — see "Cadence" below — at zero gas cost to the+ * player.+ *+ * `world-moves.js` is isomorphic (only `viem` + `fetch`, no Node-only APIs),+ * so this module runs unmodified in the browser via Vite's bundle — no+ * server relay hop needed for the happy path: MegaFuel's testnet paymaster+ * (`bsc-megafuel-testnet.nodereal.io`) was confirmed live 2026-07-08 to send+ * `access-control-allow-origin: *` on both its `OPTIONS` preflight and the+ * real `pm_isSponsorable` POST, so a direct cross-origin browser call works+ * today. If that policy ever tightens, a thin server relay (the same shape+ * as `api/bnb/register-agent.js`, which relays already-signed bytes without+ * touching a key) is the documented fallback — not needed yet.+ *+ * Wallet-agnostic on purpose: pass any viem `Account` (ephemeral, browser+ * wallet-backed — whatever prompt 16's connect flow produces). This module+ * never generates, stores, or reads a private key itself.+ */++import { MoveCoalescer, sendMove, COORD_MIN, COORD_MAX } from '../../api/_lib/bnb/world-moves.js';++/**+ * World meters → WorldMoves int32 units. WorldMoves.sol's NatSpec documents+ * its coordinate space as "1 unit = 1mm" (an 8.39km cube) — matching that+ * convention here means a scene authored in meters gets millimeter+ * precision, comfortably enough for any three.ws world.+ */+export const COORD_SCALE = 1000;++/** Convert a player position in engine meters to WorldMoves int32 coordinates. */+export function toContractPos({ x, y, z }) {+ return {+ x: Math.round(x * COORD_SCALE),+ y: Math.round(y * COORD_SCALE),+ z: Math.round(z * COORD_SCALE),+ };+}++/**+ * Convert a heading in radians to the contract's uint16 facing. WorldMoves.sol+ * leaves the unit fully caller-defined ("Not range-checked: any uint16 is a+ * valid facing") and suggests one convention in its NatSpec — its numeric+ * range (0..35999 for a full turn) only actually holds at 0.01°+ * resolution (centidegrees), matched exactly here so any indexer/renderer+ * following that same convention decodes our facing correctly.+ */+export function toContractFacing(radians) {+ const twoPi = Math.PI * 2;+ const normalized = ((radians % twoPi) + twoPi) % twoPi; // wrap into [0, 2π)+ const centidegrees = Math.round(((normalized * 180) / Math.PI) * 100);+ return centidegrees >= 36000 ? 0 : centidegrees; // 360.00° wraps to 0°, never leaves the 0..35999 convention range+}++/** Whether a world-space position (in meters) lands inside WorldMoves' representable cube. */+export function isWithinWorldMovesRange(positionMeters) {+ const p = toContractPos(positionMeters);+ return p.x >= COORD_MIN && p.x <= COORD_MAX && p.y >= COORD_MIN && p.y <= COORD_MAX && p.z >= COORD_MIN && p.z <= COORD_MAX;+}++/**+ * Create a move sender bound to one player/world/network. Nothing runs until+ * `updatePosition` is called — creating a sender never fires a wallet prompt+ * or a network request on its own.+ *+ * @param {object} params+ * @param {import('viem').Account} params.account viem account (ephemeral or wallet-backed); never read here beyond signing+ * @param {number} params.worldId uint32 world/room id+ * @param {'bscMainnet'|'bscTestnet'|56|97} [params.network]+ * @param {(result:{hash:string, mode:'sponsored'|'self-pay'}) => void} [params.onSent]+ * @param {(err:Error) => void} [params.onError] a declined/failed send NEVER throws out of `updatePosition` — it's always reported here so local movement never freezes+ * @param {string} [params.address] WorldMoves contract address override (tests, or before the env-configured deployment exists)+ * @param {object} [params.megafuelOpts] forwarded to sendGasless (publicClient/walletClient/megafuelRpc — tests)+ */+export function createMoveSender({ account, worldId, network = 'bscTestnet', onSent, onError, address, ...megafuelOpts }) {+ let lastKey = null; // dedupe: skip a resubmit if the quantized position/facing hasn't actually changed++ const coalescer = new MoveCoalescer(+ async ({ pos, facing }) => sendMove({ account, worldId, pos, facing, network }, { address, ...megafuelOpts }),+ {+ onSent: (result) => onSent?.(result),+ onError: (err) => onError?.(err),+ },+ );++ return {+ /**+ * Feed the latest local position/heading — call every frame or physics+ * tick. Cadence is self-throttling by construction: `MoveCoalescer`+ * only launches a new send once the previous one's round trip (which+ * MegaFuel/BSC dominate at ~0.45s block time + RPC latency) has+ * resolved, so a 60fps caller still produces roughly one on-chain move+ * per block, not per frame — exactly the "target ~1 per block" the+ * prompt calls for, with zero extra timer logic.+ * @param {{x:number,y:number,z:number}} positionMeters+ * @param {number} [headingRadians]+ */+ updatePosition(positionMeters, headingRadians = 0) {+ if (!isWithinWorldMovesRange(positionMeters)) return; // out of bounds — never fire a doomed on-chain revert+ const pos = toContractPos(positionMeters);+ const facing = toContractFacing(headingRadians);+ const key = `${pos.x},${pos.y},${pos.z},${facing}`;+ if (key === lastKey) return; // stationary — don't spam identical moves+ lastKey = key;+ coalescer.submit({ pos, facing });+ },++ /** Current sender counters (sent/coalesced/errors/inFlight) — wire to a status readout. */+ get stats() {+ return coalescer.stats;+ },++ /** Stop emitting further on-chain moves (e.g. toggle OFF). Local movement is never affected — this only stops the chain writes. */+ stop() {+ coalescer.dispose();+ },+ };+}diff --git a/src/bnb/onchain-ghosts.js b/src/bnb/onchain-ghosts.jsnew file mode 100644index 000000000..db30fc557--- /dev/null+++ b/src/bnb/onchain-ghosts.js@@ -0,0 +1,112 @@+/**+ * Pure on-chain presence ghost-state tracker (prompt 16).+ *+ * Turns a stream of `Moved` events (arbitrary player address → contract-unit+ * position/facing, timestamped) into smoothly interpolated render state, and+ * drops a player who hasn't moved in a while. No THREE.js, no DOM, no+ * network — feed it timestamped positions, call `tick(dt)` every frame, read+ * back interpolated `{x,y,z,facing}` per player. Framework-agnostic on+ * purpose so it's unit-testable without a WebGL context (tests/bnb-onchain-+ * ghosts.test.js) and so a future non-Three renderer could reuse it.+ *+ * Coordinates here are WHATEVER unit the caller feeds in (contract int32+ * units or engine meters — this module doesn't care, it just lerps numbers).+ * `src/agora/onchain-presence.js` is the THREE.js-aware caller that converts+ * WorldMoves' millimeter/centidegree units to scene meters/radians before+ * handing positions to `upsert`.+ */++/** No `Moved` event for this long (ms) → the ghost is dropped as stale. */+export const GHOST_STALE_MS = 6000;++/** Exponential-lerp factor per 60fps-equivalent frame (matches player-mode.js's REMOTE_LERP for other humans, so on-chain ghosts move with the same "weight"). */+export const GHOST_LERP = 0.22;++/** Wrap-aware shortest-path interpolation between two headings in [0, range). */+function easeAngle(current, target, k, range) {+ let diff = ((target - current + range * 1.5) % range) - range / 2;+ return (((current + diff * k) % range) + range) % range;+}++/**+ * @param {object} [opts]+ * @param {number} [opts.staleMs] drop a player after this long without a fresh event+ * @param {number} [opts.lerp] exponential-lerp factor per 60fps-equivalent frame+ * @param {number} [opts.facingRange] wrap range for facing interpolation (WorldMoves centidegrees: 36000)+ * @param {() => number} [opts.now] injectable clock (tests)+ */+export function createGhostTracker(opts = {}) {+ const staleMs = opts.staleMs ?? GHOST_STALE_MS;+ const lerp = opts.lerp ?? GHOST_LERP;+ const facingRange = opts.facingRange ?? 36000;+ const now = opts.now || (() => Date.now());++ /** @type {Map<string, { player:string, x:number, y:number, z:number, facing:number, target:{x:number,y:number,z:number,facing:number}, firstSeen:number, lastSeen:number, moves:number }>} */+ const byPlayer = new Map();++ return {+ /**+ * Record a fresh on-chain position for `player` (lowercase address or any+ * stable key). First sighting snaps instantly (no lerping in from the+ * origin); every subsequent sighting updates the interpolation target.+ * @returns {{isNew:boolean}}+ */+ upsert(player, { x, y, z, facing = 0 }, timestamp = now()) {+ const key = String(player).toLowerCase();+ let g = byPlayer.get(key);+ const isNew = !g;+ if (!g) {+ g = { player: key, x, y, z, facing, target: { x, y, z, facing }, firstSeen: timestamp, lastSeen: timestamp, moves: 0 };+ byPlayer.set(key, g);+ } else {+ g.target = { x, y, z, facing };+ g.lastSeen = timestamp;+ g.moves += 1;+ }+ return { isNew };+ },++ /**+ * Advance interpolation by `dt` seconds and drop anyone stale as of+ * `atMs`. Returns the list of player keys dropped this tick (caller+ * disposes their render objects).+ */+ tick(dt, atMs = now()) {+ const dead = [];+ const k = 1 - Math.pow(1 - lerp, Math.max(0, dt) * 60);+ for (const [key, g] of byPlayer) {+ if (atMs - g.lastSeen > staleMs) {+ dead.push(key);+ continue;+ }+ g.x += (g.target.x - g.x) * k;+ g.y += (g.target.y - g.y) * k;+ g.z += (g.target.z - g.z) * k;+ g.facing = easeAngle(g.facing, g.target.facing, k, facingRange);+ }+ for (const key of dead) byPlayer.delete(key);+ return dead;+ },++ /** Explicitly drop one player (e.g. a real-time `Left` event). */+ remove(player) {+ return byPlayer.delete(String(player).toLowerCase());+ },++ get(player) {+ return byPlayer.get(String(player).toLowerCase());+ },++ values() {+ return byPlayer.values();+ },++ get size() {+ return byPlayer.size;+ },++ clear() {+ byPlayer.clear();+ },+ };+}diff --git a/src/bnb/world-config-client.js b/src/bnb/world-config-client.jsnew file mode 100644index 000000000..5ec51b0d9--- /dev/null+++ b/src/bnb/world-config-client.js@@ -0,0 +1,27 @@+/**+ * Browser fetcher for GET /api/bnb/world-config (prompt 16). Small, cached+ * per network for the page's lifetime — the address changes only on a real+ * redeploy, never mid-session.+ */++const cache = new Map(); // network -> Promise<config>++/**+ * @param {'bscTestnet'|'bscMainnet'} [network]+ * @returns {Promise<{ network:string, chainId:number, address:string|null, deployed:boolean, explorer:string, rpcs:string[], worldId:number }>}+ */+export function fetchWorldConfig(network = 'bscTestnet') {+ if (cache.has(network)) return cache.get(network);+ const netParam = network === 'bscMainnet' ? 'mainnet' : 'testnet';+ const promise = fetch(`/api/bnb/world-config?network=${netParam}`, { headers: { accept: 'application/json' } })+ .then(async (res) => {+ if (!res.ok) throw new Error(`world-config returned ${res.status}`);+ return res.json();+ })+ .catch((err) => {+ cache.delete(network); // a failed fetch must not poison the cache — retry next call+ throw err;+ });+ cache.set(network, promise);+ return promise;+}diff --git a/src/bnb/world-presence-reader.js b/src/bnb/world-presence-reader.jsnew file mode 100644index 000000000..49af0d79a--- /dev/null+++ b/src/bnb/world-presence-reader.js@@ -0,0 +1,135 @@+/**+ * Read-side of on-chain presence (prompt 16): subscribes to WorldMoves'+ * `Moved`/`Joined`/`Left` events for a `worldId` and hands them to the+ * caller. Reads are secret-free (00-CONTEXT: "no secret required for+ * reads"), so this talks straight to a public BSC RPC via viem — no server+ * hop, same posture `src/bnb/move-sender.js` already established for writes.+ *+ * `watchContractEvent` over an `http()` transport polls under the hood (viem+ * has no long-lived subscription without a websocket transport), which is+ * exactly right here: BSC's ~0.45s blocks mean a short poll interval already+ * delivers sub-second-feeling updates without needing a websocket RPC.+ */++import { getPublicClient } from '../../api/_lib/bnb/chains.js';+import { WORLD_MOVES_ABI } from '../../api/_lib/bnb/world-moves.js';++/** How often to poll for new events — comfortably under BSC's ~0.45s block time's "feel" without hammering the public RPC. */+const DEFAULT_POLL_MS = 900;++/** Bounded lookback (in blocks) for the on-join backfill, so a client that just connected sees "who moved recently" without replaying the whole chain. At ~0.45s/block this is roughly the last ~9 minutes. */+const DEFAULT_BACKFILL_BLOCKS = 1200n;++/**+ * @param {object} params+ * @param {number} params.worldId+ * @param {`0x${string}`} params.address WorldMoves contract address+ * @param {'bscMainnet'|'bscTestnet'|56|97} [params.network]+ * @param {(ev:{player:string,x:number,y:number,z:number,facing:number,blockNumber:bigint,timestamp:bigint}) => void} [params.onMove]+ * @param {(ev:{player:string,timestamp:bigint}) => void} [params.onJoin]+ * @param {(ev:{player:string,timestamp:bigint}) => void} [params.onLeave]+ * @param {(err:Error) => void} [params.onError] transport errors never throw out of the watcher — reported here so the caller can degrade gracefully instead of freezing+ * @param {import('viem').PublicClient} [params.publicClient] injectable (tests, or to point at a different RPC/fork)+ * @param {number} [params.pollMs]+ * @param {bigint} [params.backfillBlocks]+ * @returns {Promise<{ stop():void }>}+ */+export async function watchWorldPresence({+ worldId,+ address,+ network = 'bscTestnet',+ onMove,+ onJoin,+ onLeave,+ onError,+ publicClient,+ pollMs = DEFAULT_POLL_MS,+ backfillBlocks = DEFAULT_BACKFILL_BLOCKS,+}) {+ const client = publicClient || getPublicClient(network);+ const stops = [];++ // Bounded backfill so a freshly-opened tab sees recent movers immediately+ // instead of an empty world until the next live event fires.+ try {+ const latest = await client.getBlockNumber();+ const fromBlock = latest > backfillBlocks ? latest - backfillBlocks : 0n;+ const logs = await client.getContractEvents({+ address,+ abi: WORLD_MOVES_ABI,+ eventName: 'Moved',+ args: { worldId },+ fromBlock,+ toBlock: latest,+ });+ // Only the latest position per player matters for a backfill snapshot.+ const latestByPlayer = new Map();+ for (const log of logs) latestByPlayer.set(log.args.player.toLowerCase(), log);+ for (const log of latestByPlayer.values()) onMove?.(eventFromLog(log));+ } catch (err) {+ onError?.(err);+ }++ stops.push(+ client.watchContractEvent({+ address,+ abi: WORLD_MOVES_ABI,+ eventName: 'Moved',+ args: { worldId },+ pollingInterval: pollMs,+ onLogs: (logs) => {+ for (const log of logs) onMove?.(eventFromLog(log));+ },+ onError: (err) => onError?.(err),+ }),+ );++ if (onJoin) {+ stops.push(+ client.watchContractEvent({+ address,+ abi: WORLD_MOVES_ABI,+ eventName: 'Joined',+ args: { worldId },+ pollingInterval: pollMs,+ onLogs: (logs) => {+ for (const log of logs) onJoin({ player: log.args.player, timestamp: log.args.timestamp });+ },+ onError: (err) => onError?.(err),+ }),+ );+ }++ if (onLeave) {+ stops.push(+ client.watchContractEvent({+ address,+ abi: WORLD_MOVES_ABI,+ eventName: 'Left',+ args: { worldId },+ pollingInterval: pollMs,+ onLogs: (logs) => {+ for (const log of logs) onLeave({ player: log.args.player, timestamp: log.args.timestamp });+ },+ onError: (err) => onError?.(err),+ }),+ );+ }++ return {+ stop() {+ for (const stop of stops) {+ try {+ stop();+ } catch {+ /* already torn down */+ }+ }+ },+ };+}++function eventFromLog(log) {+ const { player, x, y, z, facing, blockNumber, timestamp } = log.args;+ return { player, x: Number(x), y: Number(y), z: Number(z), facing: Number(facing), blockNumber, timestamp };+}diff --git a/src/coin-pages.css b/src/coin-pages.cssindex 58d512d24..6c7be93c7 100644--- a/src/coin-pages.css+++ b/src/coin-pages.css@@ -1523,3 +1523,198 @@ html.cv-page,height: 3px;border-radius: 2px;}++/* ── Liquidations pulse strip (/coins) ─────────────────────────────────────+ Real-time long/short liquidation pain across Binance, Bybit, and OKX,+ fed by api/coin/liquidations.js. Optional enrichment above the markets+ table — degrades to a quiet single line when the collector is offline,+ never fabricated numbers. */++.cv-liq {+ background: var(--cv-surface);+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-lg);+ box-shadow: var(--cv-shadow-card);+ padding: 1rem 1.25rem;+ margin: 0 0 1.5rem;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 1.25rem;+ transition: box-shadow 0.2s, border-color 0.2s, opacity 0.25s;+}+.cv-liq:hover {+ box-shadow: var(--cv-shadow-card-hover);+ border-color: var(--cv-border-hover);+}+.cv-liq[hidden] {+ display: none;+}++.cv-liq-badge {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ font-size: 0.6875rem;+ font-weight: 700;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ padding: 0.3rem 0.625rem;+ border-radius: 999px;+ border: 1px solid var(--cv-border);+ white-space: nowrap;+ flex-shrink: 0;+}+.cv-liq-badge.pain {+ color: var(--cv-red);+ background: var(--cv-red-soft);+ border-color: color-mix(in srgb, var(--cv-red) 35%, var(--cv-border));+}+.cv-liq-badge.squeeze {+ color: var(--cv-green);+ background: var(--cv-green-soft);+ border-color: color-mix(in srgb, var(--cv-green) 35%, var(--cv-border));+}+.cv-liq-badge.balanced {+ color: var(--cv-text-2);+ background: var(--cv-surface-2);+}++.cv-liq-bars {+ display: flex;+ flex-direction: column;+ gap: 0.3rem;+ min-width: 160px;+ flex: 1 1 200px;+ max-width: 280px;+}+.cv-liq-bar-row {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.75rem;+}+.cv-liq-bar-row .lbl {+ width: 3.75rem;+ flex-shrink: 0;+ white-space: nowrap;+ color: var(--cv-text-3);+ font-weight: 600;+ text-transform: uppercase;+ font-size: 0.625rem;+ letter-spacing: 0.04em;+}+.cv-liq-bar-track {+ flex: 1;+ height: 6px;+ border-radius: 999px;+ background: var(--cv-surface-3);+ overflow: hidden;+}+.cv-liq-bar-fill {+ height: 100%;+ border-radius: 999px;+ transition: width 0.4s ease;+}+.cv-liq-bar-fill.long {+ background: var(--cv-red);+}+.cv-liq-bar-fill.short {+ background: var(--cv-green);+}+.cv-liq-bar-row .amt {+ font-family: var(--cv-font-mono);+ color: var(--cv-text-2);+ white-space: nowrap;+ min-width: 3.5rem;+ text-align: right;+}++.cv-liq-top {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ flex: 2 1 320px;+}+.cv-liq-item {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ font-size: 0.75rem;+ padding: 0.3rem 0.625rem;+ border-radius: var(--cv-radius);+ background: var(--cv-surface-2);+ border: 1px solid var(--cv-border);+ color: var(--cv-text);+ text-decoration: none;+ transition: border-color 0.15s, background 0.15s, transform 0.15s;+}+a.cv-liq-item:hover,+a.cv-liq-item:focus-visible {+ border-color: var(--cv-border-hover);+ background: var(--cv-surface-3);+ transform: translateY(-1px);+}+a.cv-liq-item:focus-visible {+ outline: 2px solid var(--cv-accent);+ outline-offset: 1px;+}+.cv-liq-item .sym {+ font-weight: 700;+}+.cv-liq-item .side {+ font-size: 0.625rem;+ font-weight: 700;+ letter-spacing: 0.03em;+ text-transform: uppercase;+ padding: 0.05rem 0.3rem;+ border-radius: 3px;+}+.cv-liq-item .side.long {+ color: var(--cv-red);+ background: var(--cv-red-soft);+}+.cv-liq-item .side.short {+ color: var(--cv-green);+ background: var(--cv-green-soft);+}+.cv-liq-item .bucket {+ color: var(--cv-text-3);+ font-size: 0.6875rem;+}+.cv-liq-item .usd {+ font-family: var(--cv-font-mono);+ font-weight: 600;+}++.cv-liq-offline {+ color: var(--cv-text-3);+ font-size: 0.8125rem;+ display: flex;+ align-items: center;+ gap: 0.5rem;+}+.cv-liq-offline .dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--cv-text-3);+ flex-shrink: 0;+}++.cv-liq-skel {+ display: flex;+ gap: 1rem;+ align-items: center;+ width: 100%;+}++@media (max-width: 640px) {+ .cv-liq {+ flex-direction: column;+ align-items: stretch;+ }+ .cv-liq-bars {+ max-width: none;+ }+}diff --git a/src/coins-index.js b/src/coins-index.jsindex d7da666df..26717966d 100644--- a/src/coins-index.js+++ b/src/coins-index.js@@ -357,8 +357,142 @@ function wireSearch() {});}+// ── Liquidations pulse strip ────────────────────────────────────────────────+// Real-time long/short liquidation pain across Binance, Bybit, and OKX+// futures, fed by /api/coin/liquidations (proxying the standalone+// services/liquidation-collector). Optional enrichment: an offline collector+// degrades to a quiet single line, never fabricated numbers.++const LIQ_POLL_MS = 30_000;+const LIQ_1H_MS = 60 * 60 * 1000;+let liqTimer = null;+let liqLoaded = false;++// Resolve a liquidation's ticker symbol to a /coin/:id detail page — only for+// symbols present in the currently loaded markets table (state.coins), per+// the page's design: we don't guess at an id the table hasn't confirmed.+function resolveCoinId(symbol) {+ const hit = state.coins.find((c) => (c.symbol || '').toUpperCase() === symbol);+ return hit ? hit.id : null;+}++function liqBadgeClass(side) {+ if (side === 'LONG PAIN') return 'pain';+ if (side === 'SHORT SQUEEZE') return 'squeeze';+ return 'balanced';+}++function renderLiqSkeleton() {+ const el = $('cv-liq');+ if (!el) return;+ el.innerHTML =+ '<div class="cv-liq-skel">' ++ '<div class="cv-skel" style="height:1.5rem;width:8rem;border-radius:999px"></div>' ++ '<div class="cv-skel" style="height:2.5rem;flex:1;max-width:280px"></div>' ++ '<div class="cv-skel" style="height:1.75rem;flex:2"></div>' ++ '</div>';+}++function renderLiqOffline() {+ const el = $('cv-liq');+ if (!el) return;+ el.innerHTML =+ '<p class="cv-liq-offline" role="status"><span class="dot" aria-hidden="true"></span>Liquidation feed offline — showing the rest of the markets page as usual.</p>';+}++function renderLiqPopulated(data) {+ const el = $('cv-liq');+ if (!el) return;+ const { summary, liquidations } = data;+ const recent = Array.isArray(liquidations) ? liquidations : [];++ // 1h long vs short liquidated USD, derived from the real recent-liquidations+ // list (already timestamped) rather than the collector's 4h window total.+ const cutoff1h = Date.now() - LIQ_1H_MS;+ let long1h = 0;+ let short1h = 0;+ for (const l of recent) {+ if (l.time < cutoff1h) continue;+ if (l.side === 'LONG') long1h += l.value;+ else if (l.side === 'SHORT') short1h += l.value;+ }+ const maxBar = Math.max(long1h, short1h, 1);++ const top3 = [...recent].sort((a, b) => b.value - a.value).slice(0, 3);++ const badge = summary?.dominantSide || 'BALANCED';+ const badgeCls = liqBadgeClass(badge);++ const bars = `+ <div class="cv-liq-bars">+ <div class="cv-liq-bar-row">+ <span class="lbl">1h Long</span>+ <span class="cv-liq-bar-track"><span class="cv-liq-bar-fill long" style="width:${((long1h / maxBar) * 100).toFixed(1)}%"></span></span>+ <span class="amt cv-mono">${esc(formatUsd(long1h))}</span>+ </div>+ <div class="cv-liq-bar-row">+ <span class="lbl">1h Short</span>+ <span class="cv-liq-bar-track"><span class="cv-liq-bar-fill short" style="width:${((short1h / maxBar) * 100).toFixed(1)}%"></span></span>+ <span class="amt cv-mono">${esc(formatUsd(short1h))}</span>+ </div>+ </div>`;++ const items = top3.length+ ? top3+ .map((l) => {+ const sideCls = l.side === 'LONG' ? 'long' : 'short';+ const inner = `+ <span class="sym">${esc(l.symbol)}</span>+ <span class="side ${sideCls}">${esc(l.side)}</span>+ <span class="bucket">${esc(l.severity)}</span>+ <span class="usd">${esc(formatUsd(l.value))}</span>`;+ const id = resolveCoinId(l.symbol);+ return id+ ? `<a class="cv-liq-item" href="/coin/${encodeURIComponent(id)}">${inner}</a>`+ : `<span class="cv-liq-item">${inner}</span>`;+ })+ .join('')+ : '<span class="cv-liq-item" style="color:var(--cv-text-3)">No liquidations in the last 4h — quiet market.</span>';++ el.innerHTML = `+ <span class="cv-liq-badge ${badgeCls}">${esc(badge)}</span>+ ${bars}+ <div class="cv-liq-top" aria-label="Largest recent liquidations">${items}</div>`;+}++async function pollLiquidations() {+ if (document.hidden) return;+ try {+ const data = await getJson('/api/coin/liquidations');+ renderLiqPopulated(data);+ } catch {+ // 503 collector_offline (or any other failure) → quiet offline line, never+ // fabricated numbers. First load shows the offline state; subsequent polls+ // that fail after a populated render just leave the last-good data up.+ if (!liqLoaded) renderLiqOffline();+ } finally {+ liqLoaded = true;+ }+}++function scheduleLiquidations() {+ clearInterval(liqTimer);+ liqTimer = setInterval(pollLiquidations, LIQ_POLL_MS);+}++function loadLiquidations() {+ if (!$('cv-liq')) return;+ renderLiqSkeleton();+ pollLiquidations();+ scheduleLiquidations();+ document.addEventListener('visibilitychange', () => {+ if (!document.hidden) pollLiquidations();+ });+}+// ── Boot ────────────────────────────────────────────────────────────────────loadStats();loadCoins();+loadLiquidations();wireSearch();diff --git a/src/minted.css b/src/minted.cssnew file mode 100644index 000000000..006e64776--- /dev/null+++ b/src/minted.css@@ -0,0 +1,99 @@+/* /minted — public gallery of 3D assets minted as Metaplex Core NFTs through+ three.ws. Same monochrome palette + shell rhythm as /deployments and+ /launches so the three live feeds read as one product. */+@import './ui-juice.css';++.mn-feed-head .juice-live { margin-right: var(--space-2); }++.mn-shell { max-width: 1200px; margin: 0 auto; padding: var(--space-xl, 40px) var(--space-md, 16px) var(--space-2xl, 64px); }++/* Hero */+.mn-hero { text-align: center; margin-bottom: var(--space-xl, 40px); }+.mn-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .68rem); letter-spacing: .14em; text-transform: uppercase; color: var(--ink-dim, #888); margin: 0 0 var(--space-sm, 12px); }+.mn-live-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ink-bright, #fff); animation: mn-ping 2.4s ease infinite; }+@keyframes mn-ping { 0% { box-shadow: 0 0 0 0 rgba(255,255,255,.45);} 70% { box-shadow: 0 0 0 8px rgba(255,255,255,0);} 100% { box-shadow: 0 0 0 0 rgba(255,255,255,0);} }+.mn-title { font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: clamp(2.2rem, 6vw, 3.4rem); font-weight: 700; line-height: 1.02; margin: 0 0 var(--space-sm, 12px); color: var(--ink-dim, #999); letter-spacing: -.02em; }+.mn-title em { font-style: normal; color: var(--ink-bright, #fff); }+.mn-sub { max-width: 680px; margin: 0 auto; color: var(--ink-dim, #999); font-size: var(--text-lg, 1.02rem); line-height: 1.5; }+.mn-sub strong { color: var(--ink, #e8e8e8); font-weight: 600; }++/* Network toggle */+.mn-net { display: inline-flex; gap: 2px; margin-top: var(--space-md, 16px); padding: 3px; background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-pill, 999px); }+.mn-net-btn { appearance: none; font: inherit; font-size: var(--text-sm, .8rem); font-weight: 500; cursor: pointer; color: var(--ink-dim, #888); background: transparent; border: none; border-radius: var(--radius-pill, 999px); padding: 6px 16px; transition: color .14s ease, background .14s ease; }+.mn-net-btn:hover { color: var(--ink, #e8e8e8); }+.mn-net-btn.active { color: var(--ink-bright, #fff); background: var(--surface-3, rgba(255,255,255,.08)); }+.mn-net-btn:focus-visible { outline: 2px solid var(--accent, #fff); outline-offset: 2px; }++/* Hero CTAs */+.mn-hero-ctas { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; margin-top: var(--space-md, 16px); }+.mn-btn { appearance: none; font: inherit; font-size: var(--text-sm, .82rem); font-weight: 600; cursor: pointer; text-decoration: none; color: var(--ink, #e8e8e8); background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-pill, 999px); padding: 9px 18px; transition: background .14s ease, border-color .14s ease, color .14s ease, transform .14s ease; }+.mn-btn:hover { background: var(--surface-2, rgba(255,255,255,.06)); border-color: var(--stroke-strong, rgba(255,255,255,.16)); transform: translateY(-1px); }+.mn-btn:focus-visible { outline: 2px solid var(--accent, #fff); outline-offset: 2px; }+.mn-btn-primary { color: var(--bg-0, #0a0a0a); background: var(--ink-bright, #fff); border-color: var(--ink-bright, #fff); }+.mn-btn-primary:hover { background: var(--ink, #e8e8e8); }++/* Headline counters */+.mn-counters { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-sm, 12px); margin: var(--space-xl, 40px) 0 var(--space-lg, 24px); }+.mn-counter { background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.07)); border-radius: var(--radius-lg, 14px); padding: var(--space-md, 16px) var(--space-sm, 12px); text-align: center; min-width: 0; transition: border-color .14s ease; }+.mn-counter:hover { border-color: var(--stroke-strong, rgba(255,255,255,.14)); }+.mn-counter--lead { background: var(--surface-2, rgba(255,255,255,.05)); border-color: var(--stroke-strong, rgba(255,255,255,.14)); }+.mn-counter dt { font-size: var(--text-2xs, .68rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim, #888); margin-bottom: 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.mn-counter dd { margin: 0; font-family: var(--font-mono, monospace); font-size: clamp(1.3rem, 3vw, 1.9rem); font-weight: 700; color: var(--ink-bright, #fff); line-height: 1.05; }+.mn-counter-sub { display: block; margin-top: 5px; font-size: var(--text-2xs, .66rem); font-weight: 500; color: var(--ink-dim, #888); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }++/* Feed head */+.mn-feed-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: var(--space-md, 16px); flex-wrap: wrap; }+.mn-section-h { font-family: var(--font-display, sans-serif); font-size: var(--text-lg, 1.05rem); font-weight: 600; color: var(--ink-bright, #fff); margin: 0; }+.mn-count { font-size: var(--text-sm, .8rem); color: var(--ink-faint, #666); }++/* Card grid */+.mn-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: var(--space-md, 16px); }+.mn-card { display: flex; flex-direction: column; background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.07)); border-radius: var(--radius-lg, 14px); overflow: hidden; transition: border-color .14s ease, transform .14s ease, background .14s ease; }+.mn-card:hover { border-color: var(--stroke-strong, rgba(255,255,255,.18)); background: var(--surface-2, rgba(255,255,255,.05)); transform: translateY(-2px); }++.mn-card-thumb { display: block; aspect-ratio: 1 / 1; background: var(--bg-0, #0a0a0a); position: relative; }+.mn-card-mv, .mn-card-thumb img { width: 100%; height: 100%; display: block; object-fit: cover; --poster-color: transparent; background: radial-gradient(circle at 50% 40%, var(--surface-2, rgba(255,255,255,.05)), var(--bg-0, #0a0a0a)); }+.mn-card-noglb { width: 100%; height: 100%; display: grid; place-items: center; font-family: var(--font-mono, monospace); font-size: var(--text-xl, 1.2rem); font-weight: 700; color: var(--ink-faint, #555); background: var(--surface-1, rgba(255,255,255,.03)); }++.mn-card-body { padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 6px; min-width: 0; }+.mn-card-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-width: 0; }+.mn-card-name { font-size: var(--text-md, .85rem); font-weight: 600; color: var(--ink-bright, #fff); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }+.mn-card-prompt { margin: 0; font-size: var(--text-2xs, .7rem); color: var(--ink-dim, #999); line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.mn-card-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }+.mn-card-agent { font-size: var(--text-2xs, .68rem); color: var(--ink-faint, #666); text-decoration: none; }+.mn-card-agent:hover { color: var(--ink, #e8e8e8); }++.mn-chip { flex: 0 0 auto; font-size: var(--text-2xs, .64rem); font-weight: 600; letter-spacing: .02em; color: var(--ink-dim, #aaa); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-sm, 6px); padding: 1px 7px; white-space: nowrap; }+.mn-chip--net { text-transform: capitalize; }+.mn-tag { font-size: var(--text-2xs, .6rem); font-weight: 700; letter-spacing: .03em; text-transform: uppercase; color: var(--ink-dim, #aaa); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: var(--radius-sm, 6px); padding: 1px 6px; }+.mn-tag--paid { color: var(--success, #4ade80); border-color: var(--success, #4ade80); }++.mn-card-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 4px; }+.mn-card-link { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .68rem); color: var(--ink-faint, #666); text-decoration: none; }+.mn-card-link:hover { color: var(--ink-bright, #fff); }+.mn-time { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .64rem); color: var(--ink-faint, #555); white-space: nowrap; }++/* Skeleton / empty / error */+.mn-skeleton { aspect-ratio: 3 / 4; border-radius: var(--radius-lg, 14px); background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,.03)) 25%, var(--surface-2, rgba(255,255,255,.06)) 37%, var(--surface-1, rgba(255,255,255,.03)) 63%); background-size: 400% 100%; animation: mn-shimmer 1.4s ease infinite; }+@keyframes mn-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }+.mn-empty, .mn-error { grid-column: 1 / -1; text-align: center; padding: var(--space-xl, 40px) var(--space-md, 16px); color: var(--ink-dim, #888); border: 1px dashed var(--stroke, rgba(255,255,255,.12)); border-radius: var(--radius-lg, 14px); }+.mn-empty-title { color: var(--ink-bright, #fff); font-weight: 600; margin-bottom: 4px; }+.mn-empty-sub a, .mn-error a { color: var(--ink-bright, #fff); }+.mn-empty-sub code { font-family: var(--font-mono, monospace); color: var(--ink-dim, #aaa); }+.mn-retry { appearance: none; font: inherit; cursor: pointer; color: var(--ink-bright, #fff); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: var(--radius-sm, 6px); padding: 3px 10px; margin-left: 4px; }+.mn-retry:hover { background: var(--surface-3, rgba(255,255,255,.08)); }++.mn-footer-state { text-align: center; margin-top: var(--space-lg, 24px); font-size: var(--text-sm, .8rem); color: var(--ink-faint, #666); min-height: 1.4em; }++/* About */+.mn-about { margin-top: var(--space-2xl, 64px); padding-top: var(--space-lg, 24px); border-top: 1px solid var(--stroke, rgba(255,255,255,.07)); }+.mn-about-body { margin: 0; max-width: 760px; font-size: var(--text-sm, .85rem); line-height: 1.6; color: var(--ink-dim, #999); }+.mn-about-body a { color: var(--ink-bright, #fff); }+.mn-about-body code { font-family: var(--font-mono, monospace); color: var(--ink, #ccc); background: var(--surface-2, rgba(255,255,255,.05)); border-radius: 4px; padding: 1px 5px; }++@media (max-width: 880px) {+ .mn-counters { grid-template-columns: repeat(2, 1fr); }+}+@media (max-width: 520px) {+ .mn-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); }+}diff --git a/src/minted.js b/src/minted.jsnew file mode 100644index 000000000..dd1d94aa5--- /dev/null+++ b/src/minted.js@@ -0,0 +1,287 @@+/**+ * /minted — the public gallery of every generated 3D avatar minted as a+ * Metaplex Core NFT through three.ws (Prompt 08, task 5: surface minted 3D+ * assets in the existing launches pattern — the NFT counterpart of /launches).+ *+ * Data flow:+ * GET /api/v1/tokenized/launches?network=&offset=&limit= free, public, paginated+ *+ * Each card renders the GLB live (a <model-viewer>, not a static thumbnail),+ * its network, royalty terms, and — when it's a remix — the royalty payout it+ * routed to the original creator. No synthetic entries: an empty network is+ * shown as an honest, actionable empty state.+ */++import { createLogger } from './shared/log.js';+import { enterStagger, updateValue, liveDot, setLiveDot } from './ui-juice.js';++const log = createLogger('minted');++const PAGE_SIZE = 24;++const state = {+ network: 'mainnet',+ offset: 0,+ hasMore: false,+ loading: false,+ items: [],+ count: 0,+ royaltySum: 0,+ remixPaid: 0,+};++const $ = (id) => document.getElementById(id);+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++function shortAddr(a) {+ if (!a) return '';+ const s = String(a);+ return s.length > 12 ? `${s.slice(0, 6)}…${s.slice(-4)}` : s;+}++function timeAgo(iso) {+ const t = new Date(iso).getTime();+ if (!Number.isFinite(t)) return '';+ const s = Math.max(0, Math.round((Date.now() - t) / 1000));+ if (s < 60) return 'just now';+ const m = Math.round(s / 60);+ if (m < 60) return `${m}m ago`;+ const h = Math.round(m / 60);+ if (h < 24) return `${h}h ago`;+ const d = Math.round(h / 24);+ if (d < 30) return `${d}d ago`;+ const mo = Math.round(d / 30);+ if (mo < 12) return `${mo}mo ago`;+ return `${Math.round(mo / 12)}y ago`;+}++function explorerAssetUrl(mint, network) {+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';+ return `https://solscan.io/token/${mint}${cluster}`;+}++// ── counters ──────────────────────────────────────────────────────────────────++function renderCounters() {+ updateValue($('mn-c-total'), state.count, (n) => String(n), { flash: false });+ const avgRoyalty =+ state.count > 0 ? Math.round((state.royaltySum / state.count) * 10) / 10 : 0;+ $('mn-c-royalty').textContent = state.count ? `${avgRoyalty}%` : '—';+ updateValue($('mn-c-remix'), state.remixPaid, (n) => String(n), { flash: false });+ $('mn-c-network').textContent = state.network;+}++// ── cards ─────────────────────────────────────────────────────────────────────++function cardHTML(a) {+ const glbUrl = a.glb_url || '';+ const viewerUrl = a.viewer_url || (glbUrl ? `/app#model=${encodeURIComponent(glbUrl)}` : '#');+ const explorerUrl = explorerAssetUrl(a.mint, a.network);+ const name = a.name || 'three.ws 3D asset';++ const thumb = glbUrl+ ? `<model-viewer+ src="${esc(glbUrl)}"+ alt="${esc(name)}"+ class="mn-card-mv"+ reveal="auto"+ loading="lazy"+ disable-zoom+ disable-pan+ disable-tap+ interaction-prompt="none"+ camera-controls="false"+ auto-rotate+ rotation-per-second="16deg"+ environment-image="neutral"+ shadow-intensity="0"+ exposure="1"+ poster="${esc(a.image_url || '')}"+ ></model-viewer>`+ : a.image_url+ ? `<img src="${esc(a.image_url)}" alt="${esc(name)}" loading="lazy" decoding="async" />`+ : `<div class="mn-card-noglb" aria-hidden="true">3D</div>`;++ const royaltyPct = a.royalty?.percent != null ? `${a.royalty.percent}%` : '—';+ const remix = a.remix_royalty;+ const remixBadge = a.parent_mint+ ? remix?.paid+ ? `<span class="mn-tag mn-tag--paid" title="Royalty paid to the original creator">remix · royalty paid</span>`+ : `<span class="mn-tag" title="Derived from another creator's mint">remix</span>`+ : '';++ const agentLine = a.agent+ ? `<a class="mn-card-agent" href="${esc(a.agent.url)}">${esc(a.agent.name || 'Agent')}</a>`+ : '';++ const promptLine = a.provenance?.prompt+ ? `<p class="mn-card-prompt" title="${esc(a.provenance.prompt)}">“${esc(String(a.provenance.prompt).slice(0, 90))}${a.provenance.prompt.length > 90 ? '…' : ''}”</p>`+ : '';++ return (+ `<article class="mn-card" data-mn-id="${esc(a.mint)}">` ++ `<a class="mn-card-thumb" href="${esc(viewerUrl)}" aria-label="View ${esc(name)} in 3D viewer">${thumb}</a>` ++ `<div class="mn-card-body">` ++ `<div class="mn-card-top">` ++ `<span class="mn-card-name">${esc(name)}</span>` ++ `<span class="mn-chip" title="Enforced on-chain creator royalty">${royaltyPct} royalty</span>` ++ `</div>` ++ promptLine ++ `<div class="mn-card-meta">` ++ `<span class="mn-chip mn-chip--net">${esc(a.network)}</span>` ++ remixBadge ++ agentLine ++ `</div>` ++ `<div class="mn-card-foot">` ++ `<a class="mn-card-link" href="${esc(explorerUrl)}" target="_blank" rel="noopener">mint ${esc(shortAddr(a.mint))} ↗</a>` ++ `<span class="mn-time">${esc(timeAgo(a.created_at))}</span>` ++ `</div>` ++ `</div>` ++ `</article>`+ );+}++function skeleton() {+ return Array.from({ length: 8 }).map(() => `<div class="mn-skeleton"></div>`).join('');+}++function renderFeed() {+ const host = $('mn-feed');+ if (!host) return;+ if (!state.items.length) {+ host.innerHTML =+ `<div class="mn-empty"><div class="mn-empty-title">No 3D assets minted on ${esc(state.network)} yet</div>` ++ `<p class="mn-empty-sub">Generate an avatar at <a href="/forge">/forge</a>, then mint it as an NFT with ` ++ `the <code>mint_3d_asset</code> tool. <a href="/agent-identities">Try Agent Identity Studio →</a></p></div>`;+ return;+ }+ host.setAttribute('aria-busy', 'false');+ host.innerHTML = state.items.map(cardHTML).join('');+ enterStagger([...host.children], { step: 24 });+}++function updateCount() {+ const el = $('mn-count');+ if (!el) return;+ el.textContent = state.items.length+ ? `${state.items.length} shown${state.hasMore ? ' · more available' : ''}`+ : '';+}++// ── feed ─────────────────────────────────────────────────────────────────────++async function loadFeed(reset) {+ if (state.loading) return;+ state.loading = true;+ if (reset) {+ state.offset = 0;+ state.items = [];+ state.count = 0;+ state.royaltySum = 0;+ state.remixPaid = 0;+ }+ const host = $('mn-feed');+ if (reset && host) {+ host.setAttribute('aria-busy', 'true');+ host.innerHTML = skeleton();+ }+ setFeedLive('connecting');++ try {+ const params = new URLSearchParams({+ network: state.network,+ offset: String(state.offset),+ limit: String(PAGE_SIZE),+ });+ const res = await fetch(`/api/v1/tokenized/launches?${params}`, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`launches ${res.status}`);+ const data = await res.json();+ const launches = Array.isArray(data.launches) ? data.launches : [];+ state.items = reset ? launches : state.items.concat(launches);+ state.hasMore = Boolean(data.has_more);+ state.offset += launches.length;+ state.count = state.items.length;+ state.royaltySum = state.items.reduce((s, a) => s + (a.royalty?.percent || 0), 0);+ state.remixPaid = state.items.filter((a) => a.remix_royalty?.paid).length;+ renderFeed();+ renderCounters();+ updateCount();+ setFeedLive(state.items.length ? 'live' : 'idle');+ } catch (e) {+ log.warn('feed failed', e?.message);+ setFeedLive('error');+ if (reset && host) {+ host.setAttribute('aria-busy', 'false');+ host.innerHTML =+ `<div class="mn-error"><div class="mn-empty-title">Couldn’t reach the launch directory</div>` ++ `<p>The gallery is reconnecting. <button type="button" class="mn-retry" id="mn-retry">Retry</button></p></div>`;+ $('mn-retry')?.addEventListener('click', () => loadFeed(true));+ }+ } finally {+ state.loading = false;+ renderLoadMoreSentinel();+ }+}++// Auto-load-more on scroll — no button, matches the gallery's continuous feel.+let observer = null;+function renderLoadMoreSentinel() {+ const footer = $('mn-footer-state');+ if (!footer) return;+ footer.textContent = state.hasMore ? '' : state.items.length ? 'End of the gallery.' : '';+ if (!state.hasMore) {+ observer?.disconnect();+ return;+ }+ if (!observer && 'IntersectionObserver' in window) {+ observer = new IntersectionObserver(+ (entries) => {+ if (entries[0].isIntersecting && !state.loading && state.hasMore) loadFeed(false);+ },+ { rootMargin: '0px 0px 320px 0px' },+ );+ }+ observer?.observe(footer);+}++function setFeedLive(stateName) {+ const head = document.querySelector('.mn-feed-head .mn-count');+ if (!head) return;+ if (!head.previousElementSibling?.classList?.contains('juice-live')) {+ head.insertAdjacentHTML('beforebegin', liveDot(stateName));+ } else {+ setLiveDot(head.previousElementSibling, stateName);+ }+}++// ── controls ────────────────────────────────────────────────────────────────++function wireNetworkToggle() {+ for (const btn of document.querySelectorAll('[data-network]')) {+ btn.addEventListener('click', () => {+ const net = btn.dataset.network === 'devnet' ? 'devnet' : 'mainnet';+ if (net === state.network) return;+ state.network = net;+ for (const b of document.querySelectorAll('[data-network]')) {+ const on = b.dataset.network === net;+ b.classList.toggle('active', on);+ b.setAttribute('aria-selected', String(on));+ }+ loadFeed(true);+ });+ }+}++function init() {+ wireNetworkToggle();+ loadFeed(true);+ // Fresh mints land continuously — refresh the top of the feed periodically+ // while the tab is visible, same cadence as the API's own CDN window.+ setInterval(() => {+ if (document.hidden || state.offset > PAGE_SIZE) return;+ loadFeed(true);+ }, 30_000);+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);+else init();diff --git a/src/viewer.js b/src/viewer.jsindex 231ada8b2..efece9b79 100644--- a/src/viewer.js+++ b/src/viewer.js@@ -18,6 +18,7 @@ import {PointsMaterial,Scene,SkeletonHelper,+ Spherical,Vector3,WebGLRenderer,LinearToneMapping,@@ -69,6 +70,49 @@ Mesh.prototype.raycast = acceleratedRaycast;Cache.enabled = true;+// Canvas focus ring + reduced-motion opt-out, injected once per document.+// The viewer's <canvas> is appended directly into arbitrary host pages (forge,+// avatar-page, embeds, kiosks) with no guaranteed shared stylesheet, so this+// mirrors the pattern used by the SDK's <three-ws-viewer> (avatar-sdk/src/viewer.js):+// a tiny scoped <style> tag rather than assuming a page-level CSS file loaded.+// `var(--accent, …)` matches the site's existing focus-visible token+// (see src/character-creator.css, src/exchanges.css) with a safe fallback for+// pages that don't define it.+const VIEWER_A11Y_STYLE_ID = 'tws-viewer-canvas-a11y';+function ensureViewerA11yStyles() {+ if (typeof document === 'undefined' || document.getElementById(VIEWER_A11Y_STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = VIEWER_A11Y_STYLE_ID;+ style.textContent = `+ canvas.tws-viewer-canvas { outline: none; touch-action: none; }+ canvas.tws-viewer-canvas:focus-visible { outline: 2px solid var(--accent, #6ee7b7); outline-offset: -2px; }+ @media (prefers-reduced-motion: reduce) {+ canvas.tws-viewer-canvas { scroll-behavior: auto; }+ }+ `;+ document.head.appendChild(style);+}++function viewerPrefersReducedMotion() {+ return typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;+}++// Low-power heuristic: coarse pointer (touch) + few cores/little memory almost+// always means an entry-level phone/tablet. `deviceMemory` is Chromium-only+// and absent on iOS/Firefox, so it only ever *adds* signal, never gates alone.+// The touch requirement means desktop — mouse or trackpad, any core count —+// never matches, so default desktop behavior is unchanged. Mirrors+// avatar-sdk/src/viewer.js's identical heuristic for the lightweight SDK+// component, kept as a local copy since the two are separate bundles.+function viewerLooksLowPower() {+ if (typeof navigator === 'undefined' || typeof matchMedia === 'undefined') return false;+ const touch = matchMedia('(pointer: coarse)').matches;+ if (!touch) return false;+ const fewCores = typeof navigator.hardwareConcurrency === 'number' && navigator.hardwareConcurrency <= 4;+ const lowMem = typeof navigator.deviceMemory === 'number' && navigator.deviceMemory <= 4;+ return fewCores || lowMem;+}+// Draw a small gold coin sprite on a canvas for the pump.fun trade shower, so the// effect is self-contained (no external image asset to 404). A fresh texture is// returned each call; the caller owns disposal.@@ -218,12 +262,20 @@ export class Viewer {};this.defaultCamera.add(this.audioListener);- this.renderer = window.renderer = new WebGLRenderer({ antialias: true, alpha: true });+ // Quality auto-degrade: a touch device with few cores/little memory+ // (entry-level phone/tablet) skips MSAA — the single biggest GPU cost on+ // weak mobile GPUs — in exchange for a stable frame rate. Gated on a+ // coarse pointer, so desktop (mouse/trackpad) never matches — default+ // desktop behavior is unchanged.+ this._lowPower = viewerLooksLowPower();+ this.renderer = window.renderer = new WebGLRenderer({ antialias: !this._lowPower, alpha: true });this.renderer.setClearColor(0x000000, 1);// DPR cap: kiosk/embed modes default to 1.5 (saves ~40% fragment work on// retina). Override with options.maxPixelRatio. Standalone tabs default- // to 2.0 to preserve sharpness on high-DPI displays.- const dprCap = options.maxPixelRatio ?? (options.kiosk ? 1.5 : 2);+ // to 2.0 to preserve sharpness on high-DPI displays. Low-power devices+ // are capped at 1.0 regardless of mode — resolution is the second+ // biggest lever after MSAA on weak mobile GPUs.+ const dprCap = this._lowPower ? 1 : (options.maxPixelRatio ?? (options.kiosk ? 1.5 : 2));this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, dprCap));this.renderer.setSize(el.clientWidth, el.clientHeight);@@ -236,9 +288,29 @@ export class Viewer {this.controls.screenSpacePanning = true;this._onControlsChange = () => this.invalidate();this.controls.addEventListener('change', this._onControlsChange);+ // prefers-reduced-motion: OrbitControls damping (inertial drift after+ // pointer release) is opt-in in three.js and defaults off, so there's+ // nothing to disable here — this flag only gates the keyboard-orbit+ // step size below, keeping motion-sensitive users' arrow-key input+ // snappy/discrete rather than smoothed.+ this._reducedMotion = viewerPrefersReducedMotion();this.el.appendChild(this.renderer.domElement);+ // Accessibility: the canvas is the primary interactive surface but has+ // no accessible name or keyboard path by default. Make it a reachable,+ // labeled, orbit/zoom-able control — mirrors the SDK's lightweight+ // <three-ws-viewer> (avatar-sdk/src/viewer.js) so keyboard behavior is+ // consistent whichever viewer a page embeds.+ ensureViewerA11yStyles();+ const canvasEl = this.renderer.domElement;+ canvasEl.classList.add('tws-viewer-canvas');+ canvasEl.tabIndex = 0;+ canvasEl.setAttribute('role', 'img');+ canvasEl.setAttribute('aria-label', options.alt || options.title || '3D model viewer. Focus and use arrow keys to orbit, +/- to zoom.');+ this._onCanvasKeyDown = (e) => this._handleOrbitKeydown(e);+ canvasEl.addEventListener('keydown', this._onCanvasKeyDown);+// Post-processing: the CinematicPipeline owns the full post chain (SSAO,// depth-of-field, bloom, colour grade, chromatic aberration, film grain,// vignette) behind selectable presets. The default 'Studio' preset@@ -345,7 +417,43 @@ export class Viewer {}}-+ // Keyboard-only orbit + zoom for users who can't drag a pointer: arrow keys+ // rotate azimuth/polar around the current OrbitControls target, +/- and+ // PageUp/PageDown dolly. Scoped to the canvas element's own keydown (only+ // fires while the canvas has focus) so it never steals arrow-key+ // scroll/navigation elsewhere on the host page. Step sizes match+ // avatar-sdk/src/viewer.js's keyboard orbit for a consistent feel across+ // every three.ws viewer surface; reduced-motion halves the step so users+ // who asked for less motion get finer, calmer control instead of smoothing.+ _handleOrbitKeydown(event) {+ if (!this.controls || !this.activeCamera) return;+ const stepScale = this._reducedMotion ? 0.5 : 1;+ const rotateStep = 0.05 * stepScale;+ const zoomStep = 1.08;+ const offset = this._tempVec.subVectors(this.activeCamera.position, this.controls.target);+ const spherical = new Spherical().setFromVector3(offset);+ let handled = true;+ switch (event.key) {+ case 'ArrowLeft': spherical.theta -= rotateStep; break;+ case 'ArrowRight': spherical.theta += rotateStep; break;+ case 'ArrowUp': spherical.phi = Math.max(0.05, spherical.phi - rotateStep); break;+ case 'ArrowDown': spherical.phi = Math.min(Math.PI - 0.05, spherical.phi + rotateStep); break;+ case '+':+ case '=':+ case 'PageUp': spherical.radius /= zoomStep; break;+ case '-':+ case '_':+ case 'PageDown': spherical.radius *= zoomStep; break;+ default: handled = false;+ }+ if (!handled) return;+ event.preventDefault();+ event.stopPropagation();+ const newOffset = new Vector3().setFromSpherical(spherical);+ this.activeCamera.position.copy(this.controls.target).add(newOffset);+ this.controls.update();+ this.invalidate();+ }setCameraTarget(boneName) {if (!this.content) return;@@ -2165,6 +2273,10 @@ export class Viewer {if (this._onDblClick && this.renderer?.domElement) {this.renderer.domElement.removeEventListener('dblclick', this._onDblClick);}+ if (this._onCanvasKeyDown && this.renderer?.domElement) {+ this.renderer.domElement.removeEventListener('keydown', this._onCanvasKeyDown);+ this._onCanvasKeyDown = null;+ }if (this._onMessage) {window.removeEventListener('message', this._onMessage, false);}diff --git a/tests/bnb-move-sender.test.js b/tests/bnb-move-sender.test.jsnew file mode 100644index 000000000..7d25501a7--- /dev/null+++ b/tests/bnb-move-sender.test.js@@ -0,0 +1,156 @@+/**+ * Browser gasless move sender (src/bnb/move-sender.js) — unit tests.+ *+ * Pure engine-unit conversion (meters → int32 millimeters, radians → uint16+ * centidegrees, bounds check) plus `createMoveSender`'s dedupe/coalescing+ * behaviour, exercised with an injected fake `account`/mocked MegaFuel RPC —+ * no network, no DOM.+ */++import { describe, it, expect } from 'vitest';+import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';+import { createMoveSender, toContractPos, toContractFacing, isWithinWorldMovesRange, COORD_SCALE } from '../src/bnb/move-sender.js';+import { COORD_MAX } from '../api/_lib/bnb/world-moves.js';++const WORLD_MOVES_ADDR = '0x71Ddcb9865632Ca3c4325dE0E4a92Cc0065c8aaE'; // anvil-fork proof address (DEPLOYMENTS.md) — test fixture only+const account = privateKeyToAccount(generatePrivateKey());++/** Flush the fire-and-forget send chain (createMoveSender.updatePosition never returns a promise, by design — "never freeze the game"). */+function flushAsync() {+ return new Promise((resolve) => setTimeout(resolve, 10));+}++function mockPublicClient() {+ return {+ chain: { id: 97, name: 'BNB Smart Chain Testnet', nativeCurrency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 } },+ bnbRpcs: ['https://data-seed-prebsc-1-s1.bnbchain.org:8545'],+ async getTransactionCount() {+ return 0;+ },+ async estimateGas() {+ return 30000n;+ },+ };+}++describe('toContractPos', () => {+ it('scales meters to millimeters (COORD_SCALE=1000) and rounds', () => {+ expect(toContractPos({ x: 1.2345, y: -0.5, z: 0 })).toEqual({ x: 1235, y: -500, z: 0 });+ expect(COORD_SCALE).toBe(1000);+ });+});++describe('toContractFacing', () => {+ it('converts 0 radians to 0 centidegrees', () => {+ expect(toContractFacing(0)).toBe(0);+ });+ it('converts pi radians to 18000 centidegrees (180.00°)', () => {+ expect(toContractFacing(Math.PI)).toBe(18000);+ });+ it('wraps negative radians into [0, 2π) before converting', () => {+ expect(toContractFacing(-Math.PI / 2)).toBe(27000);+ });+ it('wraps a full turn (2π) back to 0, never 36000 (out of uint16 contract convention)', () => {+ expect(toContractFacing(2 * Math.PI)).toBe(0);+ });+});++describe('isWithinWorldMovesRange', () => {+ it('accepts an ordinary in-scene position', () => {+ expect(isWithinWorldMovesRange({ x: 10, y: 0, z: -5 })).toBe(true);+ });+ it('rejects a position whose millimeter-scaled coordinate exceeds COORD_MAX', () => {+ const metersJustOver = (COORD_MAX + 1) / COORD_SCALE;+ expect(isWithinWorldMovesRange({ x: metersJustOver, y: 0, z: 0 })).toBe(false);+ });+});++describe('createMoveSender', () => {+ it('does nothing until updatePosition is called', () => {+ const sender = createMoveSender({ account, worldId: 1, address: WORLD_MOVES_ADDR, publicClient: mockPublicClient() });+ expect(sender.stats).toMatchObject({ sent: 0, inFlight: false });+ });++ it('sends a sponsored move on the first updatePosition call', async () => {+ const sent = [];+ const sender = createMoveSender({+ account,+ worldId: 1,+ address: WORLD_MOVES_ADDR,+ publicClient: mockPublicClient(),+ onSent: (r) => sent.push(r),+ megafuelRpc: async (method) => {+ if (method === 'pm_isSponsorable') return { sponsorable: true };+ if (method === 'eth_sendRawTransaction') return '0x' + 'e'.repeat(64);+ throw new Error(`unexpected ${method}`);+ },+ });+ sender.updatePosition({ x: 1, y: 0, z: 2 }, 0);+ await flushAsync();+ expect(sent).toEqual([{ hash: '0x' + 'e'.repeat(64), mode: 'sponsored', sponsor: { sponsorable: true } }]);+ expect(sender.stats.sent).toBe(1);+ });++ it('skips a resubmit when the quantized position/facing is unchanged (stationary player)', async () => {+ let calls = 0;+ const sender = createMoveSender({+ account,+ worldId: 1,+ address: WORLD_MOVES_ADDR,+ publicClient: mockPublicClient(),+ megafuelRpc: async (method) => {+ calls++;+ if (method === 'pm_isSponsorable') return { sponsorable: true };+ return '0x' + 'f'.repeat(64);+ },+ });+ sender.updatePosition({ x: 1, y: 0, z: 2 }, 0);+ await flushAsync();+ const callsAfterFirst = calls;+ // Same position/facing (well under millimeter precision) — must NOT trigger a second send.+ sender.updatePosition({ x: 1.0000001, y: 0, z: 2 }, 0);+ await flushAsync();+ expect(calls).toBe(callsAfterFirst);+ expect(sender.stats.sent).toBe(1);+ });++ it('silently drops an out-of-range position instead of firing a doomed tx', async () => {+ let calls = 0;+ const sender = createMoveSender({+ account,+ worldId: 1,+ address: WORLD_MOVES_ADDR,+ publicClient: mockPublicClient(),+ megafuelRpc: async () => {+ calls++;+ return { sponsorable: true };+ },+ });+ sender.updatePosition({ x: 1e12, y: 0, z: 0 }, 0);+ await Promise.resolve();+ expect(calls).toBe(0);+ expect(sender.stats.sent).toBe(0);+ });++ it('stop() halts further sends', async () => {+ let calls = 0;+ const sender = createMoveSender({+ account,+ worldId: 1,+ address: WORLD_MOVES_ADDR,+ publicClient: mockPublicClient(),+ megafuelRpc: async (method) => {+ calls++;+ if (method === 'pm_isSponsorable') return { sponsorable: true };+ return '0x' + 'a'.repeat(64);+ },+ });+ sender.updatePosition({ x: 1, y: 0, z: 0 }, 0);+ await flushAsync();+ sender.stop();+ const callsAfterStop = calls;+ sender.updatePosition({ x: 5, y: 0, z: 0 }, 0);+ await flushAsync();+ expect(calls).toBe(callsAfterStop);+ });+});diff --git a/tests/bnb-onchain-ghosts.test.js b/tests/bnb-onchain-ghosts.test.jsnew file mode 100644index 000000000..7abe5a137--- /dev/null+++ b/tests/bnb-onchain-ghosts.test.js@@ -0,0 +1,98 @@+/**+ * On-chain presence ghost-state tracker (src/bnb/onchain-ghosts.js) — unit+ * tests. Pure logic only: feed timestamped positions, tick(dt), assert+ * smooth intermediate frames and stale-player eviction. No THREE.js, no+ * network, no DOM.+ */++import { describe, it, expect } from 'vitest';+import { createGhostTracker, GHOST_STALE_MS } from '../src/bnb/onchain-ghosts.js';++describe('createGhostTracker — upsert + interpolation', () => {+ it('a first sighting snaps instantly (no lerp-in from the origin)', () => {+ const g = createGhostTracker({ now: () => 1000 });+ g.upsert('0xAAA', { x: 10, y: 0, z: -5, facing: 100 });+ const entry = g.get('0xaaa');+ expect(entry).toMatchObject({ x: 10, y: 0, z: -5, facing: 100 });+ });++ it('lowercases the player key so case-inconsistent addresses collapse to one ghost', () => {+ const g = createGhostTracker({ now: () => 1000 });+ g.upsert('0xAbCdEf', { x: 1, y: 2, z: 3, facing: 0 });+ g.upsert('0xabcdef', { x: 5, y: 5, z: 5, facing: 0 });+ expect(g.size).toBe(1);+ });++ it('tick() moves current position toward the target, converging over several frames', () => {+ let now = 0;+ const g = createGhostTracker({ now: () => now, lerp: 0.22 });+ g.upsert('0xaaa', { x: 0, y: 0, z: 0, facing: 0 }, 0);+ g.upsert('0xaaa', { x: 100, y: 0, z: 0, facing: 0 }, 10); // new target far away+ now = 10;+ const before = g.get('0xaaa').x;+ g.tick(1 / 60, 10);+ const afterOneFrame = g.get('0xaaa').x;+ expect(afterOneFrame).toBeGreaterThan(before);+ expect(afterOneFrame).toBeLessThan(100);+ for (let i = 0; i < 60; i++) g.tick(1 / 60, 10 + i);+ expect(g.get('0xaaa').x).toBeGreaterThan(99); // converges close to the target+ });++ it('facing interpolates the SHORT way around the wrap (e.g. 350° → 10° goes forward through 0°, not backward through 180°)', () => {+ let now = 0;+ const g = createGhostTracker({ now: () => now, lerp: 0.5, facingRange: 36000 });+ g.upsert('0xaaa', { x: 0, y: 0, z: 0, facing: 35000 }, 0); // 350.00°+ g.upsert('0xaaa', { x: 0, y: 0, z: 0, facing: 1000 }, 0); // target 10.00°+ g.tick(1, 0);+ const facing = g.get('0xaaa').facing;+ // Short path from 350° to 10° passes through 0°/360°, landing near 0 or near+ // 35999 — NOT anywhere near 180° (which the naive/long-way interpolation+ // would produce).+ const distanceFromWrapPoint = Math.min(facing, 36000 - facing);+ expect(distanceFromWrapPoint).toBeLessThan(18000);+ });++ it('tick() drops (and reports) a player who has gone stale', () => {+ let now = 0;+ const g = createGhostTracker({ now: () => now, staleMs: GHOST_STALE_MS });+ g.upsert('0xaaa', { x: 0, y: 0, z: 0, facing: 0 }, 0);+ now = GHOST_STALE_MS + 1;+ const dead = g.tick(1 / 60, now);+ expect(dead).toEqual(['0xaaa']);+ expect(g.size).toBe(0);+ });++ it('tick() keeps a player who moved recently even under a custom staleMs', () => {+ let now = 0;+ const g = createGhostTracker({ now: () => now, staleMs: 2000 });+ g.upsert('0xaaa', { x: 0, y: 0, z: 0, facing: 0 }, 0);+ now = 1000;+ const dead = g.tick(1 / 60, now);+ expect(dead).toEqual([]);+ expect(g.size).toBe(1);+ });++ it('remove() explicitly evicts a player (e.g. a real-time Left event) without waiting for staleness', () => {+ const g = createGhostTracker({ now: () => 0 });+ g.upsert('0xaaa', { x: 0, y: 0, z: 0, facing: 0 });+ expect(g.size).toBe(1);+ expect(g.remove('0xAAA')).toBe(true); // case-insensitive+ expect(g.size).toBe(0);+ });++ it('clear() empties every tracked ghost', () => {+ const g = createGhostTracker({ now: () => 0 });+ g.upsert('0xaaa', { x: 0, y: 0, z: 0, facing: 0 });+ g.upsert('0xbbb', { x: 1, y: 1, z: 1, facing: 0 });+ g.clear();+ expect(g.size).toBe(0);+ });++ it('values() iterates every live ghost with its player key intact', () => {+ const g = createGhostTracker({ now: () => 0 });+ g.upsert('0xaaa', { x: 1, y: 2, z: 3, facing: 0 });+ const all = [...g.values()];+ expect(all).toHaveLength(1);+ expect(all[0].player).toBe('0xaaa');+ });+});diff --git a/tests/bnb-world-config-endpoint.test.js b/tests/bnb-world-config-endpoint.test.jsnew file mode 100644index 000000000..fc362ca14--- /dev/null+++ b/tests/bnb-world-config-endpoint.test.js@@ -0,0 +1,107 @@+/**+ * GET /api/bnb/world-config — integration tests (prompt 16).+ *+ * `api/_lib/bnb/world-moves.js`'s `worldMovesAddress` and+ * `api/_lib/rate-limit.js` are mocked so the suite runs deterministically —+ * both the "deployed" and the honest "not deployed yet" states are exercised+ * without touching env vars or a live RPC.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const rl = { ok: true };+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })) },+ clientIp: () => '127.0.0.1',+}));++const worldMovesState = { address: null };+vi.mock('../api/_lib/bnb/world-moves.js', async () => {+ const actual = await vi.importActual('../api/_lib/bnb/world-moves.js');+ return {+ ...actual,+ worldMovesAddress: vi.fn((network) => {+ if (!worldMovesState.address) {+ throw new actual.WorldMovesError('no WorldMoves contract deployed yet', { code: 'no_deployment' });+ }+ return worldMovesState.address;+ }),+ };+});++const { default: handler } = await import('../api/bnb/world-config.js');++function makeReq(url) {+ return { method: 'GET', url, headers: { origin: 'https://three.ws' }, socket: { remoteAddress: '127.0.0.1' } };+}+function makeRes() {+ const r = { statusCode: 200, _h: {}, _b: null };+ r.setHeader = (k, v) => { r._h[k] = v; };+ r.getHeader = (k) => r._h[k];+ r.end = (b) => { r._b = b; };+ Object.defineProperty(r, '_s', { get() { return this.statusCode; } });+ Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });+ return r;+}+async function call(qs = '') {+ const req = makeReq(`/api/bnb/world-config${qs}`);+ const res = makeRes();+ await handler(req, res);+ return res;+}++beforeEach(() => {+ rl.ok = true;+ worldMovesState.address = null;+});+afterEach(() => {+ vi.clearAllMocks();+});++describe('GET /api/bnb/world-config — not yet deployed (honest default state)', () => {+ it('200 with deployed:false, address:null when no contract is configured', async () => {+ const r = await call('?network=testnet');+ expect(r._s).toBe(200);+ const body = r.json();+ expect(body.deployed).toBe(false);+ expect(body.address).toBe(null);+ expect(body.network).toBe('bscTestnet');+ expect(body.chainId).toBe(97);+ expect(body.worldId).toBe(1);+ expect(Array.isArray(body.rpcs)).toBe(true);+ expect(body.rpcs.length).toBeGreaterThan(0);+ });+});++describe('GET /api/bnb/world-config — deployed', () => {+ it('200 with deployed:true and the configured address', async () => {+ worldMovesState.address = '0x71Ddcb9865632Ca3c4325dE0E4a92Cc0065c8aaE';+ const r = await call('?network=testnet');+ expect(r._s).toBe(200);+ const body = r.json();+ expect(body.deployed).toBe(true);+ expect(body.address).toBe('0x71Ddcb9865632Ca3c4325dE0E4a92Cc0065c8aaE');+ });++ it('defaults to mainnet when network is omitted', async () => {+ worldMovesState.address = '0x0000000000000000000000000000000000dEaD';+ const r = await call('');+ expect(r._s).toBe(200);+ expect(r.json().network).toBe('bscMainnet');+ expect(r.json().chainId).toBe(56);+ });++ it('400 on an unknown network param', async () => {+ const r = await call('?network=nonsense');+ expect(r._s).toBe(400);+ expect(r.json().error).toBe('bad_request');+ });+});++describe('GET /api/bnb/world-config — rate limiting', () => {+ it('429 when the limiter declines', async () => {+ rl.ok = false;+ const r = await call('?network=testnet');+ expect(r._s).toBe(429);+ });+});diff --git a/tests/bnb-world-moves.test.js b/tests/bnb-world-moves.test.jsnew file mode 100644index 000000000..d63c35cf3--- /dev/null+++ b/tests/bnb-world-moves.test.js@@ -0,0 +1,283 @@+/**+ * WorldMoves gasless move sender (api/_lib/bnb/world-moves.js) — unit tests.+ *+ * `buildMoveTx` calldata is checked byte-for-byte against a hand-decoded+ * expectation. `MoveCoalescer` is exercised as pure logic — a controllable+ * deferred `sendFn`, no network, no timers — feeding it a burst of positions+ * faster than a "confirmation" resolves and asserting only the latest input+ * survives per in-flight cycle. `sendMove` reuses the same+ * megafuelRpc/publicClient injection pattern tests/bnb-megafuel.test.js+ * already proved, so the sponsored + self-pay + decline paths are exercised+ * for real (no live network).+ */++import { describe, it, expect, vi } from 'vitest';+import { decodeFunctionData } from 'viem';+import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';+import {+ buildMoveTx,+ buildJoinTx,+ buildLeaveTx,+ buildCheckpointTx,+ sendMove,+ sendJoin,+ sendLeave,+ worldMovesAddress,+ WorldMovesError,+ MoveCoalescer,+ WORLD_MOVES_ABI,+ COORD_MIN,+ COORD_MAX,+} from '../api/_lib/bnb/world-moves.js';++const WORLD_MOVES_ADDR = '0x71Ddcb9865632Ca3c4325dE0E4a92Cc0065c8aaE'; // anvil-fork proof address (DEPLOYMENTS.md) — test fixture only+const account = privateKeyToAccount(generatePrivateKey());++function mockPublicClient() {+ return {+ chain: { id: 97, name: 'BNB Smart Chain Testnet', nativeCurrency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 } },+ bnbRpcs: ['https://data-seed-prebsc-1-s1.bnbchain.org:8545'],+ async getTransactionCount() {+ return 0;+ },+ async estimateGas() {+ return 30000n;+ },+ };+}++describe('worldMovesAddress', () => {+ it('returns opts.address when given, bypassing env config entirely', () => {+ expect(worldMovesAddress('bscTestnet', { address: WORLD_MOVES_ADDR })).toBe(WORLD_MOVES_ADDR);+ });++ it('throws a typed WorldMovesError when no address is configured or passed', () => {+ expect(() => worldMovesAddress('bscTestnet')).toThrow(WorldMovesError);+ try {+ worldMovesAddress('bscMainnet');+ throw new Error('expected throw');+ } catch (err) {+ expect(err).toBeInstanceOf(WorldMovesError);+ expect(err.code).toBe('no_deployment');+ expect(err.message).toContain('WORLD_MOVES_ADDRESS_MAINNET');+ }+ });+});++describe('buildMoveTx', () => {+ it('encodes the right calldata for known args', () => {+ const tx = buildMoveTx(1, { x: 10, y: -5, z: 3 }, 36, { address: WORLD_MOVES_ADDR });+ expect(tx.to).toBe(WORLD_MOVES_ADDR);+ expect(tx.value).toBe(0n);+ const decoded = decodeFunctionData({ abi: WORLD_MOVES_ABI, data: tx.data });+ expect(decoded.functionName).toBe('move');+ expect(decoded.args).toEqual([1, 10, -5, 3, 36]);+ });++ it('round-trips coordinate extremes (COORD_MIN/COORD_MAX) without reverting client-side', () => {+ const tx = buildMoveTx(1, { x: COORD_MIN, y: COORD_MAX, z: 0 }, 0, { address: WORLD_MOVES_ADDR });+ const decoded = decodeFunctionData({ abi: WORLD_MOVES_ABI, data: tx.data });+ expect(decoded.args).toEqual([1, COORD_MIN, COORD_MAX, 0, 0]);+ });++ it('rejects an out-of-bounds coordinate before ever building calldata', () => {+ expect(() => buildMoveTx(1, { x: COORD_MAX + 1, y: 0, z: 0 }, 0, { address: WORLD_MOVES_ADDR })).toThrow(WorldMovesError);+ expect(() => buildMoveTx(1, { x: COORD_MIN - 1, y: 0, z: 0 }, 0, { address: WORLD_MOVES_ADDR })).toThrow(/coord_out_of_bounds|bounds/);+ });++ it('rejects a facing outside uint16 range', () => {+ expect(() => buildMoveTx(1, { x: 0, y: 0, z: 0 }, 65536, { address: WORLD_MOVES_ADDR })).toThrow(WorldMovesError);+ expect(() => buildMoveTx(1, { x: 0, y: 0, z: 0 }, -1, { address: WORLD_MOVES_ADDR })).toThrow(WorldMovesError);+ });++ it('rejects a non-uint32 worldId', () => {+ expect(() => buildMoveTx(-1, { x: 0, y: 0, z: 0 }, 0, { address: WORLD_MOVES_ADDR })).toThrow(WorldMovesError);+ expect(() => buildMoveTx(1.5, { x: 0, y: 0, z: 0 }, 0, { address: WORLD_MOVES_ADDR })).toThrow(WorldMovesError);+ });+});++describe('buildJoinTx / buildLeaveTx / buildCheckpointTx', () => {+ it('encode join() and leave() with just the worldId', () => {+ const join = buildJoinTx(7, { address: WORLD_MOVES_ADDR });+ expect(decodeFunctionData({ abi: WORLD_MOVES_ABI, data: join.data })).toMatchObject({ functionName: 'join', args: [7] });+ const leave = buildLeaveTx(7, { address: WORLD_MOVES_ADDR });+ expect(decodeFunctionData({ abi: WORLD_MOVES_ABI, data: leave.data })).toMatchObject({ functionName: 'leave', args: [7] });+ });++ it('encodes checkpoint() identically shaped to move()', () => {+ const cp = buildCheckpointTx(7, { x: 1, y: 2, z: 3 }, 100, { address: WORLD_MOVES_ADDR });+ const decoded = decodeFunctionData({ abi: WORLD_MOVES_ABI, data: cp.data });+ expect(decoded.functionName).toBe('checkpoint');+ expect(decoded.args).toEqual([7, 1, 2, 3, 100]);+ });+});++describe('MoveCoalescer — pure logic, no network', () => {+ /** A send fn whose resolution is controlled externally, to simulate "slower than the caller's update rate". */+ function deferredSend(log) {+ let resolvers = [];+ const send = (input) => {+ log.push(input);+ return new Promise((resolve) => resolvers.push(() => resolve({ hash: `0x${log.length}`, mode: 'sponsored' })));+ };+ return { send, resolveNext: () => resolvers.shift()?.() };+ }++ it('launches the first submit immediately (no artificial delay)', async () => {+ const log = [];+ const { send } = deferredSend(log);+ const c = new MoveCoalescer(send);+ c.submit('a');+ await Promise.resolve();+ expect(log).toEqual(['a']);+ expect(c.stats.inFlight).toBe(true);+ });++ it('a burst of submits while one send is in flight collapses to latest-wins, coalescing the rest', async () => {+ const log = [];+ const { send, resolveNext } = deferredSend(log);+ const c = new MoveCoalescer(send);++ c.submit(1); // launches immediately+ await Promise.resolve();+ c.submit(2); // queued (pending=2)+ c.submit(3); // 2 is dropped (coalesced), pending=3+ c.submit(4); // 3 is dropped (coalesced), pending=4++ expect(c.stats.coalesced).toBe(2);+ expect(c.stats.hasPending).toBe(true);+ expect(log).toEqual([1]); // only the first send has actually been launched so far++ resolveNext(); // 1 resolves → launches the latest pending (4), NOT 2 or 3+ await Promise.resolve();+ await Promise.resolve();+ expect(log).toEqual([1, 4]);++ resolveNext(); // 4 resolves → nothing pending, coalescer goes idle+ await Promise.resolve();+ expect(c.stats).toMatchObject({ sent: 2, coalesced: 2, inFlight: false, hasPending: false });+ });++ it('never exceeds one in-flight send at a time under a sustained burst', async () => {+ const log = [];+ const { send, resolveNext } = deferredSend(log);+ const c = new MoveCoalescer(send);+ for (let i = 0; i < 50; i++) c.submit(i);+ expect(log.length).toBe(1); // only the very first submit actually launched+ expect(c.stats.inFlight).toBe(true);+ resolveNext();+ await Promise.resolve();+ await Promise.resolve();+ expect(log.length).toBe(2); // resolving launches exactly one more — the latest (49)+ expect(log[1]).toBe(49);+ expect(c.stats.coalesced).toBe(48);+ });++ it('a failed send is reported via onError and does not wedge the coalescer', async () => {+ const errors = [];+ const sent = [];+ let calls = 0;+ const c = new MoveCoalescer(+ async (input) => {+ calls++;+ if (calls === 1) throw new Error('megafuel declined');+ return { hash: '0xok', mode: 'self-pay' };+ },+ { onError: (err, input) => errors.push([err.message, input]), onSent: (result, input) => sent.push([result, input]) },+ );+ c.submit('a');+ await Promise.resolve();+ await Promise.resolve();+ expect(errors).toEqual([['megafuel declined', 'a']]);+ c.submit('b');+ await Promise.resolve();+ await Promise.resolve();+ expect(sent).toEqual([[{ hash: '0xok', mode: 'self-pay' }, 'b']]);+ expect(c.stats).toMatchObject({ sent: 1, errors: 1 });+ });++ it('dispose() stops launching further sends but lets an in-flight one settle', async () => {+ const log = [];+ const { send, resolveNext } = deferredSend(log);+ const c = new MoveCoalescer(send);+ c.submit(1);+ await Promise.resolve();+ c.submit(2);+ c.dispose();+ resolveNext();+ await Promise.resolve();+ await Promise.resolve();+ expect(log).toEqual([1]); // 2 never launches — disposed before it could+ expect(c.stats.sent).toBe(1);+ c.submit(3);+ expect(log).toEqual([1]); // submit() after dispose() is a no-op+ });++ it('rejects a non-function sendFn', () => {+ expect(() => new MoveCoalescer(null)).toThrow(WorldMovesError);+ });+});++describe('sendMove / sendJoin / sendLeave — sponsored + self-pay + decline (mocked MegaFuel + RPC)', () => {+ it('sendMove returns mode:"sponsored" when MegaFuel accepts the probe', async () => {+ const result = await sendMove(+ { account, worldId: 1, pos: { x: 10, y: -5, z: 3 }, facing: 36, network: 'bscTestnet' },+ {+ address: WORLD_MOVES_ADDR,+ publicClient: mockPublicClient(),+ megafuelRpc: async (method) => {+ if (method === 'pm_isSponsorable') return { sponsorable: true, sponsorAddress: '0xabc' };+ if (method === 'eth_sendRawTransaction') return '0x' + 'a'.repeat(64);+ throw new Error(`unexpected method ${method}`);+ },+ },+ );+ expect(result.mode).toBe('sponsored');+ expect(result.hash).toBe('0x' + 'a'.repeat(64));+ });++ it('sendMove falls back to self-pay when MegaFuel declines', async () => {+ const walletClient = { sendTransaction: vi.fn().mockResolvedValue('0x' + 'b'.repeat(64)) };+ const result = await sendMove(+ { account, worldId: 1, pos: { x: 1, y: 1, z: 1 }, facing: 0, network: 'bscTestnet' },+ {+ address: WORLD_MOVES_ADDR,+ publicClient: mockPublicClient(),+ walletClient,+ megafuelRpc: async () => ({ sponsorable: false, reason: 'no policy for this address' }),+ },+ );+ expect(result.mode).toBe('self-pay');+ expect(result.reason).toMatch(/no policy/);+ expect(walletClient.sendTransaction).toHaveBeenCalledTimes(1);+ });++ it('sendMove self-pays when MegaFuel is unreachable (RPC throws)', async () => {+ const walletClient = { sendTransaction: vi.fn().mockResolvedValue('0x' + 'c'.repeat(64)) };+ const result = await sendMove(+ { account, worldId: 1, pos: { x: 1, y: 1, z: 1 }, facing: 0, network: 'bscTestnet' },+ {+ address: WORLD_MOVES_ADDR,+ publicClient: mockPublicClient(),+ walletClient,+ megafuelRpc: async () => {+ throw new Error('network unreachable');+ },+ },+ );+ expect(result.mode).toBe('self-pay');+ expect(walletClient.sendTransaction).toHaveBeenCalledTimes(1);+ });++ it('sendJoin and sendLeave route through the same sponsored path', async () => {+ const megafuelRpc = async (method) => {+ if (method === 'pm_isSponsorable') return { sponsorable: true };+ if (method === 'eth_sendRawTransaction') return '0x' + 'd'.repeat(64);+ throw new Error(`unexpected ${method}`);+ };+ const join = await sendJoin({ account, worldId: 1 }, { address: WORLD_MOVES_ADDR, publicClient: mockPublicClient(), megafuelRpc });+ expect(join.mode).toBe('sponsored');+ const leave = await sendLeave({ account, worldId: 1 }, { address: WORLD_MOVES_ADDR, publicClient: mockPublicClient(), megafuelRpc });+ expect(leave.mode).toBe('sponsored');+ });+});diff --git a/tests/coin-liquidations.test.js b/tests/coin-liquidations.test.jsnew file mode 100644index 000000000..5e98bc7a0--- /dev/null+++ b/tests/coin-liquidations.test.js@@ -0,0 +1,124 @@+// Coverage for api/coin/liquidations.js — the proxy in front of the+// standalone services/liquidation-collector. Tests the endpoint's+// composition/branching only (env gating, timeout, upstream failure, success+// pass-through), not the real collector or exchange streams beneath it.+//+// Hard requirement under test: NEVER fabricate liquidation data. Every+// non-2xx path must return 503 { error: 'collector_offline' } — no synthetic+// numbers, ever.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../api/_lib/http.js', () => ({+ wrap: (fn) => fn,+ cors: () => false,+ method: () => true,+ rateLimited: (res) => {+ res._json = { status: 429, body: { error: 'rate_limited' } };+ return res;+ },+ json: (res, status, body, headers = {}) => {+ res._json = { status, body, headers };+ return res;+ },+}));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '1.2.3.4',+}));++const { default: handler } = await import('../api/coin/liquidations.js');+const { limits } = await import('../api/_lib/rate-limit.js');++function fakeRes() {+ return { setHeader() {}, end() {}, statusCode: 200 };+}+function call(url = '/api/coin/liquidations') {+ const res = fakeRes();+ return handler({ method: 'GET', url, headers: {} }, res).then(() => res);+}++const ORIGINAL_ENV = process.env.LIQUIDATION_COLLECTOR_URL;+const originalFetch = global.fetch;++beforeEach(() => {+ limits.publicIp.mockResolvedValue({ success: true });+ global.fetch = vi.fn();+});++afterEach(() => {+ if (ORIGINAL_ENV === undefined) delete process.env.LIQUIDATION_COLLECTOR_URL;+ else process.env.LIQUIDATION_COLLECTOR_URL = ORIGINAL_ENV;+ global.fetch = originalFetch;+ vi.restoreAllMocks();+});++describe('GET /api/coin/liquidations', () => {+ it('503s with collector_offline when LIQUIDATION_COLLECTOR_URL is unset — no fetch attempted', async () => {+ delete process.env.LIQUIDATION_COLLECTOR_URL;+ const res = await call();+ expect(res._json.status).toBe(503);+ expect(res._json.body.error).toBe('collector_offline');+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('proxies a real collector snapshot through unchanged on success', async () => {+ process.env.LIQUIDATION_COLLECTOR_URL = 'http://localhost:3033';+ const snapshot = {+ liquidations: [+ { exchange: 'Binance', price: 61234.5, qty: 0.42, severity: 'LARGE', side: 'LONG', symbol: 'BTC', time: 1735689600000, value: 257184.89 },+ ],+ summary: {+ dominantSide: 'LONG PAIN', largeCount: 1, longCount: 1, longValue: 257184.89,+ megaCount: 0, shortCount: 0, shortValue: 0, totalCount: 1, totalValue: 257184.89,+ },+ symbolStats: [{ count: 1, longValue: 257184.89, shortValue: 0, symbol: 'BTC' }],+ timestamp: '2026-07-08T12:00:00.000Z',+ };+ global.fetch.mockResolvedValue({+ ok: true,+ json: async () => snapshot,+ });+ const res = await call();+ expect(global.fetch).toHaveBeenCalledWith(+ 'http://localhost:3033/liquidations',+ expect.objectContaining({ headers: { accept: 'application/json' } }),+ );+ expect(res._json.status).toBe(200);+ expect(res._json.body).toEqual(snapshot);+ expect(res._json.headers['cache-control']).toContain('s-maxage=15');+ expect(res._json.headers['cache-control']).toContain('stale-while-revalidate=60');+ });++ it('503s with collector_offline when the upstream fetch times out', async () => {+ process.env.LIQUIDATION_COLLECTOR_URL = 'http://localhost:3033';+ global.fetch.mockRejectedValue(Object.assign(new Error('The operation was aborted'), { name: 'TimeoutError' }));+ const res = await call();+ expect(res._json.status).toBe(503);+ expect(res._json.body.error).toBe('collector_offline');+ });++ it('503s with collector_offline when the collector responds non-2xx', async () => {+ process.env.LIQUIDATION_COLLECTOR_URL = 'http://localhost:3033';+ global.fetch.mockResolvedValue({ ok: false, status: 502 });+ const res = await call();+ expect(res._json.status).toBe(503);+ expect(res._json.body.error).toBe('collector_offline');+ });++ it('503s when the collector is down (connection refused)', async () => {+ process.env.LIQUIDATION_COLLECTOR_URL = 'http://localhost:3033';+ global.fetch.mockRejectedValue(new Error('connect ECONNREFUSED 127.0.0.1:3033'));+ const res = await call();+ expect(res._json.status).toBe(503);+ expect(res._json.body.error).toBe('collector_offline');+ });++ it('429s when rate limited, before touching the collector', async () => {+ limits.publicIp.mockResolvedValue({ success: false });+ process.env.LIQUIDATION_COLLECTOR_URL = 'http://localhost:3033';+ const res = await call();+ expect(res._json.status).toBe(429);+ expect(global.fetch).not.toHaveBeenCalled();+ });+});diff --git a/vercel.json b/vercel.jsonindex e3712f7b8..dd7979373 100644--- a/vercel.json+++ b/vercel.json@@ -821,6 +821,10 @@"src": "/launches/?","dest": "/launches.html"},+ {+ "src": "/minted/?",+ "dest": "/minted.html"+ },{"src": "/pulse/?","dest": "/pulse.html"diff --git a/vite.config.js b/vite.config.jsindex 9c43d19be..898cc1410 100644--- a/vite.config.js+++ b/vite.config.js@@ -387,6 +387,7 @@ const appConfig = {'agent-wallet': resolve(__dirname, 'pages/agent-wallet.html'),guardian: resolve(__dirname, 'pages/guardian.html'),launches: resolve(__dirname, 'pages/launches.html'),+ minted: resolve(__dirname, 'pages/minted.html'),pulse: resolve(__dirname, 'pages/pulse.html'),diorama: resolve(__dirname, 'pages/diorama.html'),'x402-revenue': resolve(__dirname, 'pages/x402-revenue.html'),@@ -899,6 +900,8 @@ support: resolve(__dirname, 'pages/support.html'),'/bounties/': resolve(root, 'pages/bounties.html'),'/launches': resolve(root, 'pages/launches.html'),'/launches/': resolve(root, 'pages/launches.html'),+ '/minted': resolve(root, 'pages/minted.html'),+ '/minted/': resolve(root, 'pages/minted.html'),'/pulse': resolve(root, 'pages/pulse.html'),'/pulse/': resolve(root, 'pages/pulse.html'),'/x402-revenue': resolve(root, 'pages/x402-revenue.html'),